]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Avoid full metrics computation with Update:FitCursor
[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 docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1280 {
1281         docstring str;
1282         if (!opt.ignoreformat) {
1283                 str = buffer_to_latex(buffer);
1284         } else {
1285                 // OutputParams runparams(&buffer.params().encoding());
1286                 OutputParams runparams(encodings.fromLyXName("utf8"));
1287                 runparams.nice = true;
1288                 setFindParams(runparams);
1289                 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1290                 if (ignoreFormats.getDeleted()) {
1291                         option |= AS_STR_SKIPDELETE;
1292                         runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1293                 }
1294                 else {
1295                         runparams.find_set_feature(OutputParams::SearchWithDeleted);
1296                 }
1297                 if (ignoreFormats.getNonContent()) {
1298                         runparams.find_add_feature(OutputParams::SearchNonOutput);
1299                 }
1300                 string t("");
1301                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1302                         Paragraph const & par = buffer.paragraphs().at(pit);
1303                         string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1304                                                                 option,
1305                                                                 &runparams), !opt.ignoreformat);
1306                         LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1307                                 << add << "'");
1308                         t += add;
1309                 }
1310                 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1311                 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1312                 str = from_utf8(t);
1313         }
1314         return str;
1315 }
1316
1317
1318 /// Return separation pos between the leading material and the rest
1319 static size_t identifyLeading(string const & s)
1320 {
1321         string t = s;
1322         // @TODO Support \item[text]
1323         // Kornel: Added textsl, textsf, textit, texttt and noun
1324         // + allow to search for colored text too
1325         while (regex_replace(t, t, "^\\\\(("
1326                              "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1327                              "lyxaddress|lyxrightaddress|"
1328                              "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1329                              "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1330                              "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1331                              "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1332                || regex_replace(t, t, "^\\$", "")
1333                || regex_replace(t, t, "^\\\\\\[", "")
1334                || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1335                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1336                ;
1337         LYXERR(Debug::FINDVERBOSE, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1338         return s.size() - t.size();
1339 }
1340
1341 /*
1342  * Given a latexified string, retrieve some handled features
1343  * The features of the regex will later be compared with the features
1344  * of the searched text. If the regex features are not a
1345  * subset of the analized, then, in not format ignoring search
1346  * we can early stop the search in the relevant inset.
1347  */
1348 typedef map<string, bool> Features;
1349
1350 static Features identifyFeatures(string const & s)
1351 {
1352         static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1353         static regex const valid("^("
1354                 "("
1355                         "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1356                                 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1357                                 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1358                         "(u|uu)line|(s|x)out|uwave|"
1359                         "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1360                 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1361         smatch sub;
1362         bool displ = true;
1363         Features info;
1364
1365         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1366                 sub = *it;
1367                 if (displ) {
1368                         if (sub.str(1).compare("regexp") == 0) {
1369                                 displ = false;
1370                                 continue;
1371                         }
1372                         string token = sub.str(1);
1373                         smatch sub2;
1374                         if (regex_match(token, sub2, valid)) {
1375                                 info[token] = true;
1376                         }
1377                         else {
1378                                 // ignore
1379                         }
1380                 }
1381                 else {
1382                         if (sub.str(1).compare("endregexp") == 0) {
1383                                 displ = true;
1384                                 continue;
1385                         }
1386                 }
1387         }
1388         return info;
1389 }
1390
1391 /*
1392  * defines values features of a key "\\[a-z]+{"
1393  */
1394 class KeyInfo {
1395 public:
1396         enum KeyType {
1397                 /* Char type with content discarded
1398                  * like \hspace{1cm} */
1399                 noContent,
1400                 /* Char, like \backslash */
1401                 isChar,
1402                 /* replace starting backslash with '#' */
1403                 isText,
1404                 /* \part, \section*, ... */
1405                 isSectioning,
1406                 /* title, author etc */
1407                 isTitle,
1408                 /* \foreignlanguage{ngerman}, ... */
1409                 isMain,
1410                 /* inside \code{}
1411                  * to discard language in content */
1412                 noMain,
1413                 isRegex,
1414                 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1415                 isMath,
1416                 /* fonts, colors, markups, ... */
1417                 isStandard,
1418                 /* footnotesize, ... large, ...
1419                  * Ignore all of them */
1420                 isSize,
1421                 invalid,
1422                 /* inputencoding, ...
1423                  * Discard also content, because they do not help in search */
1424                 doRemove,
1425                 /* twocolumns, ...
1426                  * like remove, but also all arguments */
1427                 removeWithArg,
1428                 /* item, listitem */
1429                 isList,
1430                 /* tex, latex, ... like isChar */
1431                 isIgnored,
1432                 /* like \lettrine[lines=5]{}{} */
1433                 cleanToStart,
1434                 // like isStandard, but always remove head
1435                 headRemove,
1436                 /* End of arguments marker for lettrine,
1437                  * so that they can be ignored */
1438                 endArguments
1439         };
1440         KeyInfo() = default;
1441         KeyInfo(KeyType type, int parcount, bool disable)
1442                 : keytype(type),
1443                   parenthesiscount(parcount),
1444                   disabled(disable) {}
1445         KeyType keytype = invalid;
1446         string head;
1447         int _tokensize = -1;
1448         int _tokenstart = -1;
1449         int _dataStart = -1;
1450         int _dataEnd = -1;
1451         int parenthesiscount = 1;
1452         bool disabled = false;
1453         bool used = false; /* by pattern */
1454 };
1455
1456 class Border {
1457 public:
1458         Border(int l=0, int u=0) : low(l), upper(u) {}
1459         int low;
1460         int upper;
1461 };
1462
1463 #define MAXOPENED 30
1464 class Intervall {
1465         bool isPatternString_;
1466 public:
1467         explicit Intervall(bool isPattern, string const & p)
1468                 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1469                   actualdeptindex(0), hasTitle(false), langcount(0)
1470         {
1471                 depts[0] = 0;
1472                 closes[0] = 0;
1473         }
1474
1475         string par;
1476         int ignoreidx;
1477         static vector<Border> borders;
1478         static vector<int> depts;
1479         static vector<int> closes;
1480         int actualdeptindex;
1481         int previousNotIgnored(int) const;
1482         int nextNotIgnored(int) const;
1483         void handleOpenP(int i);
1484         void handleCloseP(int i, bool closingAllowed);
1485         void resetOpenedP(int openPos);
1486         void addIntervall(int upper);
1487         void addIntervall(int low, int upper); /* if explicit */
1488         void removeAccents();
1489         void setForDefaultLang(KeyInfo const & defLang) const;
1490         int findclosing(int start, int end, char up, char down, int repeat);
1491         void removeInvalidClosings(void);
1492         void handleParentheses(int lastpos, bool closingAllowed);
1493         bool hasTitle;
1494         // Number of disabled language specs up
1495         // to current position in actual interval
1496         int langcount;
1497         int isOpeningPar(int pos) const;
1498         string titleValue;
1499         void output(ostringstream &os, int lastpos);
1500         // string show(int lastpos);
1501 };
1502
1503 vector<Border> Intervall::borders = vector<Border>(30);
1504 vector<int> Intervall::depts = vector<int>(30);
1505 vector<int> Intervall::closes = vector<int>(30);
1506
1507 int Intervall::isOpeningPar(int pos) const
1508 {
1509         if ((pos < 0) || (size_t(pos) >= par.size()))
1510                 return 0;
1511         if (par[pos] != '{')
1512                 return 0;
1513         if (size_t(pos) + 2 >= par.size())
1514                 return 1;
1515         if (par[pos+2] != '}')
1516                 return 1;
1517         if (par[pos+1] == '[' || par[pos+1] == ']')
1518                 return 3;
1519         return 1;
1520 }
1521
1522 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1523 {
1524         // Enable the use of first token again
1525         if (ignoreidx >= 0) {
1526                 int value = defLang._tokenstart + defLang._tokensize;
1527                 int borderidx = 0;
1528                 if (hasTitle)
1529                         borderidx = 1;
1530                 if (value > 0) {
1531                         if (borders[borderidx].low < value)
1532                                 borders[borderidx].low = value;
1533                         if (borders[borderidx].upper < value)
1534                                 borders[borderidx].upper = value;
1535                 }
1536         }
1537 }
1538
1539 #if 0
1540 // Not needed, because dpts and closes are now dynamically expanded
1541 static void checkDepthIndex(int val)
1542 {
1543         static int maxdepthidx = MAXOPENED-2;
1544         static int lastmaxdepth = 0;
1545         if (val > lastmaxdepth) {
1546                 LYXERR(Debug::INFO, "Depth reached " << val);
1547                 lastmaxdepth = val;
1548         }
1549         if (val > maxdepthidx) {
1550                 maxdepthidx = val;
1551                 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1552         }
1553 }
1554 #endif
1555
1556 #if 0
1557 // Not needed, because borders are now dynamically expanded
1558 static void checkIgnoreIdx(int val)
1559 {
1560         static int lastmaxignore = -1;
1561         if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1562                 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1563                 lastmaxignore = val;
1564         }
1565 }
1566 #endif
1567
1568 /*
1569  * Expand the region of ignored parts of the input latex string
1570  * The region is only relevant in output()
1571  */
1572 void Intervall::addIntervall(int low, int upper)
1573 {
1574         int idx;
1575         if (low == upper) return;
1576         for (idx = ignoreidx+1; idx > 0; --idx) {
1577                 if (low > borders[idx-1].upper) {
1578                         break;
1579                 }
1580         }
1581         Border br(low, upper);
1582         if (idx > ignoreidx) {
1583                 if (borders.size() <= size_t(idx)) {
1584                         borders.push_back(br);
1585                 }
1586                 else {
1587                         borders[idx] = br;
1588                 }
1589                 ignoreidx = idx;
1590                 // checkIgnoreIdx(ignoreidx);
1591                 return;
1592         }
1593         else {
1594                 // Expand only if one of the new bound is inside the interwall
1595                 // We know here that br.low > borders[idx-1].upper
1596                 if (br.upper < borders[idx].low) {
1597                         // We have to insert at this pos
1598                         if (size_t(ignoreidx+1) >= borders.size()) {
1599                                 borders.push_back(borders[ignoreidx]);
1600                         }
1601                         else {
1602                                 borders[ignoreidx+1] = borders[ignoreidx];
1603                         }
1604                         for (int i = ignoreidx; i > idx; --i) {
1605                                 borders[i] = borders[i-1];
1606                         }
1607                         borders[idx] = br;
1608                         ignoreidx += 1;
1609                         // checkIgnoreIdx(ignoreidx);
1610                         return;
1611                 }
1612                 // Here we know, that we are overlapping
1613                 if (br.low > borders[idx].low)
1614                         br.low = borders[idx].low;
1615                 // check what has to be concatenated
1616                 int count = 0;
1617                 for (int i = idx; i <= ignoreidx; i++) {
1618                         if (br.upper >= borders[i].low) {
1619                                 count++;
1620                                 if (br.upper < borders[i].upper)
1621                                         br.upper = borders[i].upper;
1622                         }
1623                         else {
1624                                 break;
1625                         }
1626                 }
1627                 // count should be >= 1 here
1628                 borders[idx] = br;
1629                 if (count > 1) {
1630                         for (int i = idx + count; i <= ignoreidx; i++) {
1631                                 borders[i-count+1] = borders[i];
1632                         }
1633                         ignoreidx -= count - 1;
1634                         return;
1635                 }
1636         }
1637 }
1638
1639 static void buildaccent(string n, string param, string values)
1640 {
1641         stringstream s(n);
1642         string name;
1643         const char delim = '|';
1644         while (getline(s, name, delim)) {
1645                 size_t start = 0;
1646                 for (char c : param) {
1647                         string key = name + "{" + c + "}";
1648                         // get the corresponding utf8-value
1649                         if ((values[start] & 0xc0) != 0xc0) {
1650                                 // should not happen, utf8 encoding starts at least with 11xxxxxx
1651                                 // but value for '\dot{i}' is 'i', which is ascii
1652                                 if ((values[start] & 0x80) == 0) {
1653                                         // is ascii
1654                                         accents[key] = values.substr(start, 1);
1655                                         // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1656                                 }
1657                                 start++;
1658                                 continue;
1659                         }
1660                         for (int j = 1; ;j++) {
1661                                 if (start + j >= values.size()) {
1662                                         accents[key] = values.substr(start, j);
1663                                         start = values.size() - 1;
1664                                         break;
1665                                 }
1666                                 else if ((values[start+j] & 0xc0) != 0x80) {
1667                                         // This is the first byte of following utf8 char
1668                                         accents[key] = values.substr(start, j);
1669                                         start += j;
1670                                         // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1671                                         break;
1672                                 }
1673                         }
1674                 }
1675         }
1676 }
1677
1678 // Helper function
1679 static string getutf8(unsigned uchar)
1680 {
1681 #define maxc 5
1682         string ret = string();
1683         char c[maxc] = {0};
1684         if (uchar <= 0x7f) {
1685                 c[maxc-1] = uchar & 0x7f;
1686         }
1687         else {
1688                 unsigned char rest = 0x40;
1689                 unsigned char first = 0x80;
1690                 int start = maxc-1;
1691                 for (int i = start; i >=0; --i) {
1692                         if (uchar < rest) {
1693                                 c[i] = first + uchar;
1694                                 break;
1695                         }
1696                         c[i] = 0x80 | (uchar &  0x3f);
1697                         uchar >>= 6;
1698                         rest >>= 1;
1699                         first >>= 1;
1700                         first |= 0x80;
1701                 }
1702         }
1703         for (int i = 0; i < maxc; i++) {
1704                 if (c[i] == 0) continue;
1705                 ret += c[i];
1706         }
1707         return(ret);
1708 }
1709
1710 static void addAccents(string latex_in, string unicode_out)
1711 {
1712         latex_in = latex_in.substr(1);
1713         AccentsIterator it_ac = accents.find(latex_in);
1714         if (it_ac == accents.end()) {
1715                 accents[latex_in] = unicode_out;
1716         }
1717         else {
1718                 LYXERR0("Key " << latex_in  << " already set");
1719         }
1720 }
1721
1722 void static fillMissingUnicodesymbols()
1723 {
1724         addAccents("\\pounds", getutf8(0x00a3));
1725         addAccents("\\textsterling", getutf8(0x00a3));
1726         addAccents("\\textyen", getutf8(0x00a5));
1727         addAccents("\\yen", getutf8(0x00a5));
1728         addAccents("\\textsection", getutf8(0x00a7));
1729         addAccents("\\mathsection", getutf8(0x00a7));
1730         addAccents("\\textcopyright", getutf8(0x00a9));
1731         addAccents("\\copyright", getutf8(0x00a9));
1732         addAccents("\\textlnot", getutf8(0x00ac));
1733         addAccents("\\neg", getutf8(0x00ac));
1734         addAccents("\\textregistered", getutf8(0x00ae));
1735         addAccents("\\circledR", getutf8(0x00ae));
1736         addAccents("\\textpm", getutf8(0x00b1));
1737         addAccents("\\pm", getutf8(0x00b1));
1738         addAccents("\\textparagraph", getutf8(0x00b6));
1739         addAccents("\\mathparagraph", getutf8(0x00b6));
1740         addAccents("\\textperiodcentered", getutf8(0x00b7));
1741         addAccents("\\texttimes", getutf8(0x00d7));
1742         addAccents("\\times", getutf8(0x00d7));
1743         addAccents("\\O", getutf8(0x00d8));
1744         addAccents("\\dh", getutf8(0x00f0));
1745         addAccents("\\eth", getutf8(0x00f0));
1746         addAccents("\\textdiv", getutf8(0x00f7));
1747         addAccents("\\div", getutf8(0x00f7));
1748         addAccents("\\o", getutf8(0x00f8));
1749         addAccents("\\textcrlambda", getutf8(0x019b));
1750         addAccents("\\j", getutf8(0x0237));
1751         addAccents("\\textrevepsilon", getutf8(0x025c));
1752         addAccents("\\textbaru", getutf8(0x0289));
1753         addAccents("\\textquoteleft", getutf8(0x02bb));
1754         addAccents("\\textGamma", getutf8(0x0393));
1755         addAccents("\\Gamma", getutf8(0x0393));
1756         addAccents("\\textDelta", getutf8(0x0394));
1757         addAccents("\\Delta", getutf8(0x0394));
1758         addAccents("\\textTheta", getutf8(0x0398));
1759         addAccents("\\Theta", getutf8(0x0398));
1760         addAccents("\\textLambda", getutf8(0x039b));
1761         addAccents("\\Lambda", getutf8(0x039b));
1762         addAccents("\\textXi", getutf8(0x039e));
1763         addAccents("\\Xi", getutf8(0x039e));
1764         addAccents("\\textPi", getutf8(0x03a0));
1765         addAccents("\\Pi", getutf8(0x03a0));
1766         addAccents("\\textSigma", getutf8(0x03a3));
1767         addAccents("\\Sigma", getutf8(0x03a3));
1768         addAccents("\\textUpsilon", getutf8(0x03a5));
1769         addAccents("\\Upsilon", getutf8(0x03a5));
1770         addAccents("\\textPhi", getutf8(0x03a6));
1771         addAccents("\\Phi", getutf8(0x03a6));
1772         addAccents("\\textPsi", getutf8(0x03a8));
1773         addAccents("\\Psi", getutf8(0x03a8));
1774         addAccents("\\textOmega", getutf8(0x03a9));
1775         addAccents("\\Omega", getutf8(0x03a9));
1776         addAccents("\\textalpha", getutf8(0x03b1));
1777         addAccents("\\alpha", getutf8(0x03b1));
1778         addAccents("\\textbeta", getutf8(0x03b2));
1779         addAccents("\\beta", getutf8(0x03b2));
1780         addAccents("\\textgamma", getutf8(0x03b3));
1781         addAccents("\\gamma", getutf8(0x03b3));
1782         addAccents("\\textdelta", getutf8(0x03b4));
1783         addAccents("\\delta", getutf8(0x03b4));
1784         addAccents("\\textepsilon", getutf8(0x03b5));
1785         addAccents("\\varepsilon", getutf8(0x03b5));
1786         addAccents("\\textzeta", getutf8(0x03b6));
1787         addAccents("\\zeta", getutf8(0x03b6));
1788         addAccents("\\texteta", getutf8(0x03b7));
1789         addAccents("\\eta", getutf8(0x03b7));
1790         addAccents("\\texttheta", getutf8(0x03b8));
1791         addAccents("\\theta", getutf8(0x03b8));
1792         addAccents("\\textiota", getutf8(0x03b9));
1793         addAccents("\\iota", getutf8(0x03b9));
1794         addAccents("\\textkappa", getutf8(0x03ba));
1795         addAccents("\\kappa", getutf8(0x03ba));
1796         addAccents("\\textlambda", getutf8(0x03bb));
1797         addAccents("\\lambda", getutf8(0x03bb));
1798         addAccents("\\textmu", getutf8(0x03bc));
1799         addAccents("\\mu", getutf8(0x03bc));
1800         addAccents("\\textnu", getutf8(0x03bd));
1801         addAccents("\\nu", getutf8(0x03bd));
1802         addAccents("\\textxi", getutf8(0x03be));
1803         addAccents("\\xi", getutf8(0x03be));
1804         addAccents("\\textpi", getutf8(0x03c0));
1805         addAccents("\\pi", getutf8(0x03c0));
1806         addAccents("\\textrho", getutf8(0x03c1));
1807         addAccents("\\rho", getutf8(0x03c1));
1808         addAccents("\\textfinalsigma", getutf8(0x03c2));
1809         addAccents("\\varsigma", getutf8(0x03c2));
1810         addAccents("\\textsigma", getutf8(0x03c3));
1811         addAccents("\\sigma", getutf8(0x03c3));
1812         addAccents("\\texttau", getutf8(0x03c4));
1813         addAccents("\\tau", getutf8(0x03c4));
1814         addAccents("\\textupsilon", getutf8(0x03c5));
1815         addAccents("\\upsilon", getutf8(0x03c5));
1816         addAccents("\\textphi", getutf8(0x03c6));
1817         addAccents("\\varphi", getutf8(0x03c6));
1818         addAccents("\\textchi", getutf8(0x03c7));
1819         addAccents("\\chi", getutf8(0x03c7));
1820         addAccents("\\textpsi", getutf8(0x03c8));
1821         addAccents("\\psi", getutf8(0x03c8));
1822         addAccents("\\textomega", getutf8(0x03c9));
1823         addAccents("\\omega", getutf8(0x03c9));
1824         addAccents("\\textdigamma", getutf8(0x03dd));
1825         addAccents("\\digamma", getutf8(0x03dd));
1826         addAccents("\\hebalef", getutf8(0x05d0));
1827         addAccents("\\aleph", getutf8(0x05d0));
1828         addAccents("\\hebbet", getutf8(0x05d1));
1829         addAccents("\\beth", getutf8(0x05d1));
1830         addAccents("\\hebgimel", getutf8(0x05d2));
1831         addAccents("\\gimel", getutf8(0x05d2));
1832         addAccents("\\hebdalet", getutf8(0x05d3));
1833         addAccents("\\daleth", getutf8(0x05d3));
1834         addAccents("\\hebhe", getutf8(0x05d4));
1835         addAccents("\\hebvav", getutf8(0x05d5));
1836         addAccents("\\hebzayin", getutf8(0x05d6));
1837         addAccents("\\hebhet", getutf8(0x05d7));
1838         addAccents("\\hebtet", getutf8(0x05d8));
1839         addAccents("\\hebyod", getutf8(0x05d9));
1840         addAccents("\\hebfinalkaf", getutf8(0x05da));
1841         addAccents("\\hebkaf", getutf8(0x05db));
1842         addAccents("\\heblamed", getutf8(0x05dc));
1843         addAccents("\\hebfinalmem", getutf8(0x05dd));
1844         addAccents("\\hebmem", getutf8(0x05de));
1845         addAccents("\\hebfinalnun", getutf8(0x05df));
1846         addAccents("\\hebnun", getutf8(0x05e0));
1847         addAccents("\\hebsamekh", getutf8(0x05e1));
1848         addAccents("\\hebayin", getutf8(0x05e2));
1849         addAccents("\\hebfinalpe", getutf8(0x05e3));
1850         addAccents("\\hebpe", getutf8(0x05e4));
1851         addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1852         addAccents("\\hebtsadi", getutf8(0x05e6));
1853         addAccents("\\hebqof", getutf8(0x05e7));
1854         addAccents("\\hebresh", getutf8(0x05e8));
1855         addAccents("\\hebshin", getutf8(0x05e9));
1856         addAccents("\\hebtav", getutf8(0x05ea));
1857
1858         // Thai characters
1859         addAccents("\\thaiKoKai", getutf8(0x0e01));
1860         addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1861         addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1862         addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1863         addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1864         addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1865         addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1866         addAccents("\\thaiChoChan", getutf8(0x0e08));
1867         addAccents("\\thaiChoChing", getutf8(0x0e09));
1868         addAccents("\\thaiChoChang", getutf8(0x0e0a));
1869         addAccents("\\thaiSoSo", getutf8(0x0e0b));
1870         addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1871         addAccents("\\thaiYoYing", getutf8(0x0e0d));
1872         addAccents("\\thaiDoChada", getutf8(0x0e0e));
1873         addAccents("\\thaiToPatak", getutf8(0x0e0f));
1874         addAccents("\\thaiThoThan", getutf8(0x0e10));
1875         addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1876         addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1877         addAccents("\\thaiNoNen", getutf8(0x0e13));
1878         addAccents("\\thaiDoDek", getutf8(0x0e14));
1879         addAccents("\\thaiToTao", getutf8(0x0e15));
1880         addAccents("\\thaiThoThung", getutf8(0x0e16));
1881         addAccents("\\thaiThoThahan", getutf8(0x0e17));
1882         addAccents("\\thaiThoThong", getutf8(0x0e18));
1883         addAccents("\\thaiNoNu", getutf8(0x0e19));
1884         addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1885         addAccents("\\thaiPoPla", getutf8(0x0e1b));
1886         addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1887         addAccents("\\thaiFoFa", getutf8(0x0e1d));
1888         addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1889         addAccents("\\thaiFoFan", getutf8(0x0e1f));
1890         addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1891         addAccents("\\thaiMoMa", getutf8(0x0e21));
1892         addAccents("\\thaiYoYak", getutf8(0x0e22));
1893         addAccents("\\thaiRoRua", getutf8(0x0e23));
1894         addAccents("\\thaiRu", getutf8(0x0e24));
1895         addAccents("\\thaiLoLing", getutf8(0x0e25));
1896         addAccents("\\thaiLu", getutf8(0x0e26));
1897         addAccents("\\thaiWoWaen", getutf8(0x0e27));
1898         addAccents("\\thaiSoSala", getutf8(0x0e28));
1899         addAccents("\\thaiSoRusi", getutf8(0x0e29));
1900         addAccents("\\thaiSoSua", getutf8(0x0e2a));
1901         addAccents("\\thaiHoHip", getutf8(0x0e2b));
1902         addAccents("\\thaiLoChula", getutf8(0x0e2c));
1903         addAccents("\\thaiOAng", getutf8(0x0e2d));
1904         addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1905         addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1906         addAccents("\\thaiSaraA", getutf8(0x0e30));
1907         addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1908         addAccents("\\thaiSaraAa", getutf8(0x0e32));
1909         addAccents("\\thaiSaraAm", getutf8(0x0e33));
1910         addAccents("\\thaiSaraI", getutf8(0x0e34));
1911         addAccents("\\thaiSaraIi", getutf8(0x0e35));
1912         addAccents("\\thaiSaraUe", getutf8(0x0e36));
1913         addAccents("\\thaiSaraUee", getutf8(0x0e37));
1914         addAccents("\\thaiSaraU", getutf8(0x0e38));
1915         addAccents("\\thaiSaraUu", getutf8(0x0e39));
1916         addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1917         addAccents("\\thaiSaraE", getutf8(0x0e40));
1918         addAccents("\\thaiSaraAe", getutf8(0x0e41));
1919         addAccents("\\thaiSaraO", getutf8(0x0e42));
1920         addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1921         addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1922         addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1923         addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1924         addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1925         addAccents("\\thaiMaiEk", getutf8(0x0e48));
1926         addAccents("\\thaiMaiTho", getutf8(0x0e49));
1927         addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1928         addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1929         addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1930         addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1931         addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1932         addAccents("\\thaiFongman", getutf8(0x0e4f));
1933         addAccents("\\thaizero", getutf8(0x0e50));
1934         addAccents("\\thaione", getutf8(0x0e51));
1935         addAccents("\\thaitwo", getutf8(0x0e52));
1936         addAccents("\\thaithree", getutf8(0x0e53));
1937         addAccents("\\thaifour", getutf8(0x0e54));
1938         addAccents("\\thaifive", getutf8(0x0e55));
1939         addAccents("\\thaisix", getutf8(0x0e56));
1940         addAccents("\\thaiseven", getutf8(0x0e57));
1941         addAccents("\\thaieight", getutf8(0x0e58));
1942         addAccents("\\thainine", getutf8(0x0e59));
1943         addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1944         addAccents("\\thaiKhomut", getutf8(0x0e5b));
1945         addAccents("\\dag", getutf8(0x2020));
1946         addAccents("\\dagger", getutf8(0x2020));
1947         addAccents("\\textdagger", getutf8(0x2020));
1948         addAccents("\\ddag", getutf8(0x2021));
1949         addAccents("\\ddagger", getutf8(0x2021));
1950         addAccents("\\textdaggerdbl", getutf8(0x2021));
1951         addAccents("\\textbullet", getutf8(0x2022));
1952         addAccents("\\bullet", getutf8(0x2022));
1953         addAccents("\\dots", getutf8(0x2026));
1954         addAccents("\\ldots", getutf8(0x2026));
1955         addAccents("\\textellipsis", getutf8(0x2026));
1956         addAccents("\\textasciiacute", getutf8(0x2032));
1957         addAccents("\\prime", getutf8(0x2032));
1958         addAccents("\\textacutedbl", getutf8(0x2033));
1959         addAccents("\\dprime", getutf8(0x2033));
1960         addAccents("\\textasciigrave", getutf8(0x2035));
1961         addAccents("\\backprime", getutf8(0x2035));
1962         addAccents("\\textsubcircum{ }", getutf8(0x2038));
1963         addAccents("\\caretinsert", getutf8(0x2038));
1964         addAccents("\\textasteriskcentered", getutf8(0x204e));
1965         addAccents("\\ast", getutf8(0x204e));
1966         addAccents("\\textmho", getutf8(0x2127));
1967         addAccents("\\mho", getutf8(0x2127));
1968         addAccents("\\textleftarrow", getutf8(0x2190));
1969         addAccents("\\leftarrow", getutf8(0x2190));
1970         addAccents("\\textuparrow", getutf8(0x2191));
1971         addAccents("\\uparrow", getutf8(0x2191));
1972         addAccents("\\textrightarrow", getutf8(0x2192));
1973         addAccents("\\rightarrow", getutf8(0x2192));
1974         addAccents("\\textdownarrow", getutf8(0x2193));
1975         addAccents("\\downarrow", getutf8(0x2193));
1976         addAccents("\\textglobrise", getutf8(0x2197));
1977         addAccents("\\nearrow", getutf8(0x2197));
1978         addAccents("\\textglobfall", getutf8(0x2198));
1979         addAccents("\\searrow", getutf8(0x2198));
1980         addAccents("\\textsurd", getutf8(0x221a));
1981         addAccents("\\surd", getutf8(0x221a));
1982         addAccents("\\textbigcircle", getutf8(0x25ef));
1983         addAccents("\\bigcirc", getutf8(0x25ef));
1984         addAccents("\\FiveStar", getutf8(0x2605));
1985         addAccents("\\bigstar", getutf8(0x2605));
1986         addAccents("\\FiveStarOpen", getutf8(0x2606));
1987         addAccents("\\bigwhitestar", getutf8(0x2606));
1988         addAccents("\\Checkmark", getutf8(0x2713));
1989         addAccents("\\checkmark", getutf8(0x2713));
1990         addAccents("\\CrossMaltese", getutf8(0x2720));
1991         addAccents("\\maltese", getutf8(0x2720));
1992         addAccents("\\textlangle", getutf8(0x27e8));
1993         addAccents("\\langle", getutf8(0x27e8));
1994         addAccents("\\textrangle", getutf8(0x27e9));
1995         addAccents("\\rangle", getutf8(0x27e9));
1996 }
1997
1998 static void buildAccentsMap()
1999 {
2000         accents["imath"] = "ı";
2001         accents["i"] = "ı";
2002         accents["jmath"] = "ȷ";
2003         accents["cdot"] = "·";
2004         accents["textasciicircum"] = "^";
2005         accents["mathcircumflex"] = "^";
2006         accents["guillemotright"] = "»";
2007         accents["guillemotleft"] = "«";
2008         accents["hairspace"]     = getutf8(0xf0000);    // select from free unicode plane 15
2009         accents["thinspace"]     = getutf8(0xf0002);    // and used _only_ by findadv
2010         accents["negthinspace{}"]= getutf8(0xf0003);    // to omit backslashed latex macros
2011         accents["medspace"]      = getutf8(0xf0004);    // See https://en.wikipedia.org/wiki/Private_Use_Areas
2012         accents["negmedspace{}"] = getutf8(0xf0005);
2013         accents["thickspace"]    = getutf8(0xf0006);
2014         accents["negthickspace{}"]= getutf8(0xf0007);
2015         accents["lyx"]           = getutf8(0xf0010);    // Used logos
2016         accents["LyX"]           = getutf8(0xf0010);
2017         accents["tex"]           = getutf8(0xf0011);
2018         accents["TeX"]           = getutf8(0xf0011);
2019         accents["latex"]         = getutf8(0xf0012);
2020         accents["LaTeX"]         = getutf8(0xf0012);
2021         accents["latexe"]        = getutf8(0xf0013);
2022         accents["LaTeXe"]        = getutf8(0xf0013);
2023         accents["lyxarrow"]      = getutf8(0xf0020);
2024         accents["braceleft"]     = getutf8(0xf0030);
2025         accents["braceright"]    = getutf8(0xf0031);
2026         accents["lyxtilde"]      = getutf8(0xf0032);
2027         accents["sim"]           = getutf8(0xf0032);
2028         accents["lyxdollar"]     = getutf8(0xf0033);
2029         accents["backslash lyx"]           = getutf8(0xf0010);  // Used logos inserted with starting \backslash
2030         accents["backslash LyX"]           = getutf8(0xf0010);
2031         accents["backslash tex"]           = getutf8(0xf0011);
2032         accents["backslash TeX"]           = getutf8(0xf0011);
2033         accents["backslash latex"]         = getutf8(0xf0012);
2034         accents["backslash LaTeX"]         = getutf8(0xf0012);
2035         accents["backslash latexe"]        = getutf8(0xf0013);
2036         accents["backslash LaTeXe"]        = getutf8(0xf0013);
2037         accents["backslash lyxarrow"]      = getutf8(0xf0020);
2038         accents["ddot{\\imath}"] = "ï";
2039         buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
2040                     "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ");   // umlaut
2041         buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
2042                     "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ");      // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
2043         accents["acute{\\imath}"] = "í";
2044         buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2045                     "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2046         buildaccent("dacute|H|h", "oOuU", "őŐűŰ");  // double acute
2047         buildaccent("mathring|r", "aAuUwy",
2048                     "åÅůŮẘẙ");  // ring
2049         accents["check{\\imath}"] = "ǐ";
2050         accents["check{\\jmath}"] = "ǰ";
2051         buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2052                     "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ");        // caron
2053         accents["hat{\\imath}"] = "î";
2054         accents["hat{\\jmath}"] = "ĵ";
2055         buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2056                     "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ");  // circ
2057         accents["bar{\\imath}"] = "ī";
2058         buildaccent("bar|=", "aAeEiIoOuUyY",
2059                     "āĀēĒīĪōŌūŪȳȲ");        // macron
2060         accents["tilde{\\imath}"] = "ĩ";
2061         buildaccent("tilde", "aAeEiInNoOuUvVyY",
2062                     "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ");  // tilde
2063         accents["breve{\\imath}"] = "ĭ";
2064         buildaccent("breve|u", "aAeEgGiIoOuU",
2065                     "ăĂĕĔğĞĭĬŏŎŭŬ");        // breve
2066         accents["grave{\\imath}"] = "ì";
2067         buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2068                     "àÀèÈìÌòÒùÙǹǸẁẀỳỲ");    // grave
2069         buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2070                     "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ");      // dot below
2071         buildaccent("ogonek|k", "AaEeIiUuOo",
2072                     "ĄąĘęĮįŲųǪǫ");    // ogonek
2073         buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2074                     "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ");        // cedilla
2075         buildaccent("subring|textsubring", "Aa",
2076                     "Ḁḁ");  // subring
2077         buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2078                     "ḒḓḘḙḼḽṊṋṰṱṶṷ");    // subcircum
2079         buildaccent("subtilde|textsubtilde", "EeIiUu",
2080                     "ḚḛḬḭṴṵ");      // subtilde
2081         accents["dgrave{\\imath}"] = "ȉ";
2082         accents["textdoublegrave{\\i}"] = "ȉ";
2083         buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2084                     "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2085         accents["rcap{\\imath}"] = "ȋ";
2086         accents["textroundcap{\\i}"] = "ȋ";
2087         buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2088                     "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2089         buildaccent("slashed", "oO",
2090                     "øØ"); // slashed
2091         fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2092         // LYXERR0("Number of accents " << accents.size());
2093 }
2094
2095 /*
2096  * Created accents in math or regexp environment
2097  * are macros, but we need the utf8 equivalent
2098  */
2099 void Intervall::removeAccents()
2100 {
2101         if (accents.empty())
2102                 buildAccentsMap();
2103         static regex const accre("\\\\("
2104                                  "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]*\\}"
2105                                  "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2106                                  "|("
2107                                  "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2108                                  "|[A-Za-z]+"
2109                                  ")"
2110                                  "(?![a-zA-Z]))");
2111         smatch sub;
2112         for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2113                 sub = *itacc;
2114                 string key = sub.str(1);
2115                 AccentsIterator it_ac = accents.find(key);
2116                 if (it_ac != accents.end()) {
2117                         string val = it_ac->second;
2118                         size_t pos = sub.position(size_t(0));
2119                         for (size_t i = 0; i < val.size(); i++) {
2120                                 par[pos+i] = val[i];
2121                         }
2122                         // Remove possibly following space too
2123                         if (par[pos+sub.str(0).size()] == ' ')
2124                                 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2125                         else
2126                                 addIntervall(pos+val.size(), pos + sub.str(0).size());
2127                         for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2128                                 // remove traces of any remaining chars
2129                                 par[i] = ' ';
2130                         }
2131                 }
2132                 else {
2133                         LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2134                 }
2135         }
2136 }
2137
2138 void Intervall::handleOpenP(int i)
2139 {
2140         actualdeptindex++;
2141         if ((size_t) actualdeptindex >= depts.size()) {
2142                 depts.resize(actualdeptindex + 30);
2143                 closes.resize(actualdeptindex + 30);
2144         }
2145         depts[actualdeptindex] = i+1;
2146         closes[actualdeptindex] = -1;
2147         // checkDepthIndex(actualdeptindex);
2148 }
2149
2150 void Intervall::handleCloseP(int i, bool closingAllowed)
2151 {
2152         if (actualdeptindex <= 0) {
2153                 if (! closingAllowed)
2154                         LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex");  /* should not happen, but the latex input may be wrong */
2155                 // if we are at the very end
2156                 addIntervall(i, i+1);
2157         }
2158         else {
2159                 closes[actualdeptindex] = i+1;
2160                 actualdeptindex--;
2161         }
2162 }
2163
2164 void Intervall::resetOpenedP(int openPos)
2165 {
2166         // Used as initializer for foreignlanguage entry
2167         actualdeptindex = 1;
2168         depts[1] = openPos+1;
2169         closes[1] = -1;
2170 }
2171
2172 int Intervall::previousNotIgnored(int start) const
2173 {
2174         int idx = 0;                          /* int intervalls */
2175         for (idx = ignoreidx; idx >= 0; --idx) {
2176                 if (start > borders[idx].upper)
2177                         return start;
2178                 if (start >= borders[idx].low)
2179                         start = borders[idx].low-1;
2180         }
2181         return start;
2182 }
2183
2184 int Intervall::nextNotIgnored(int start) const
2185 {
2186         int idx = 0;                          /* int intervalls */
2187         for (idx = 0; idx <= ignoreidx; idx++) {
2188                 if (start < borders[idx].low)
2189                         return start;
2190                 if (start < borders[idx].upper)
2191                         start = borders[idx].upper;
2192         }
2193         return start;
2194 }
2195
2196 typedef unordered_map<string, KeyInfo> KeysMap;
2197 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2198 typedef vector< KeyInfo> Entries;
2199 static KeysMap keys = unordered_map<string, KeyInfo>();
2200
2201 class LatexInfo {
2202 private:
2203         int entidx_;
2204         Entries entries_;
2205         Intervall interval_;
2206         void buildKeys(bool);
2207         void buildEntries(bool);
2208         void makeKey(const string &, KeyInfo, bool isPatternString);
2209         void processRegion(int start, int region_end); /*  remove {} parts */
2210         void removeHead(KeyInfo const &, int count=0);
2211
2212 public:
2213         LatexInfo(string const & par, bool isPatternString)
2214                 : entidx_(-1), interval_(isPatternString, par)
2215         {
2216                 buildKeys(isPatternString);
2217                 entries_ = vector<KeyInfo>();
2218                 buildEntries(isPatternString);
2219         }
2220         int getFirstKey() {
2221                 entidx_ = 0;
2222                 if (entries_.empty()) {
2223                         return -1;
2224                 }
2225                 if (entries_[0].keytype == KeyInfo::isTitle) {
2226                         interval_.hasTitle = true;
2227                         if (! entries_[0].disabled) {
2228                                 interval_.titleValue = entries_[0].head;
2229                         }
2230                         else {
2231                                 interval_.titleValue = "";
2232                         }
2233                         removeHead(entries_[0]);
2234                         if (entries_.size() > 1)
2235                                 return 1;
2236                         else
2237                                 return -1;
2238                 }
2239                 return 0;
2240         }
2241         int getNextKey() {
2242                 entidx_++;
2243                 if (int(entries_.size()) > entidx_) {
2244                         return entidx_;
2245                 }
2246                 else {
2247                         return -1;
2248                 }
2249         }
2250         bool setNextKey(int idx) {
2251                 if ((idx == entidx_) && (entidx_ >= 0)) {
2252                         entidx_--;
2253                         return true;
2254                 }
2255                 else
2256                         return false;
2257         }
2258         int find(int start, KeyInfo::KeyType keytype) const {
2259                 if (start < 0)
2260                         return -1;
2261                 int tmpIdx = start;
2262                 while (tmpIdx < int(entries_.size())) {
2263                         if (entries_[tmpIdx].keytype == keytype)
2264                                 return tmpIdx;
2265                         tmpIdx++;
2266                 }
2267                 return -1;
2268         }
2269         int process(ostringstream & os, KeyInfo const & actual);
2270         int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2271         // string show(int lastpos) { return interval.show(lastpos);}
2272         int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2273         KeyInfo &getKeyInfo(int keyinfo) {
2274                 static KeyInfo invalidInfo = KeyInfo();
2275                 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2276                         return invalidInfo;
2277                 else
2278                         return entries_[keyinfo];
2279         }
2280         void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2281         void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2282 };
2283
2284
2285 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2286 {
2287         int skip = 0;
2288         int depth = 0;
2289         for (int i = start; i < end; i += 1 + skip) {
2290                 char c;
2291                 c = par[i];
2292                 skip = 0;
2293                 if (c == '\\') skip = 1;
2294                 else if (c == up) {
2295                         depth++;
2296                 }
2297                 else if (c == down) {
2298                         if (depth == 0) {
2299                                 repeat--;
2300                                 if ((repeat <= 0) || (par[i+1] != up))
2301                                         return i;
2302                         }
2303                         --depth;
2304                 }
2305         }
2306         return end;
2307 }
2308
2309 void Intervall::removeInvalidClosings(void)
2310 {
2311         // this can happen, if there are deleted parts
2312         int skip = 0;
2313         int depth = 0;
2314         for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2315                 char c = par[i];
2316                 skip = 0;
2317                 if (c == '\\') skip = 1;
2318                 else if (c == '{')
2319                         depth++;
2320                 else if (c == '}') {
2321                         if (depth == 0) {
2322                                 addIntervall(i, i+1);
2323                                 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2324                         }
2325                         else
2326                                 --depth;
2327                 }
2328         }
2329 }
2330 class MathInfo {
2331         class MathEntry {
2332         public:
2333                 string wait;
2334                 size_t mathEnd;
2335                 size_t mathpostfixsize;
2336                 size_t mathStart;
2337                 size_t mathprefixsize;
2338                 size_t mathSize;
2339         };
2340         size_t actualIdx_;
2341         vector<MathEntry> entries_;
2342 public:
2343         MathInfo() {
2344                 actualIdx_ = 0;
2345         }
2346         void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2347                 MathEntry m = MathEntry();
2348                 m.wait = wait;
2349                 m.mathStart = start;
2350                 m.mathprefixsize = prefixsize;
2351                 m.mathEnd = end + postfixsize;
2352                 m.mathpostfixsize = postfixsize;
2353                 m.mathSize = m.mathEnd - m.mathStart;
2354                 entries_.push_back(m);
2355         }
2356         bool empty() const { return entries_.empty(); }
2357         size_t getEndPos() const {
2358                 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2359                         return 0;
2360                 }
2361                 return entries_[actualIdx_].mathEnd;
2362         }
2363         size_t getStartPos() const {
2364                 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2365                         return 100000;                    /*  definitely enough? */
2366                 }
2367                 return entries_[actualIdx_].mathStart;
2368         }
2369         size_t getPrefixSize() const {
2370                 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2371                         return 0;
2372                 }
2373                 return entries_[actualIdx_].mathprefixsize;
2374         }
2375         size_t getPostfixSize() const {
2376                 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2377                         return 0;
2378                 }
2379                 return entries_[actualIdx_].mathpostfixsize;
2380         }
2381         size_t getFirstPos() {
2382                 actualIdx_ = 0;
2383                 return getStartPos();
2384         }
2385         size_t getSize() const {
2386                 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2387                         return size_t(0);
2388                 }
2389                 return entries_[actualIdx_].mathSize;
2390         }
2391         void incrEntry() { actualIdx_++; }
2392 };
2393
2394 void LatexInfo::buildEntries(bool isPatternString)
2395 {
2396         static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2397         static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2398         static bool disableLanguageOverride = false;
2399         smatch sub, submath;
2400         bool evaluatingRegexp = false;
2401         MathInfo mi;
2402         bool evaluatingMath = false;
2403         bool evaluatingCode = false;
2404         size_t codeEnd = 0;
2405         bool evaluatingOptional = false;
2406         size_t optionalEnd = 0;
2407         int codeStart = -1;
2408         KeyInfo found;
2409         bool math_end_waiting = false;
2410         size_t math_pos = 10000;
2411         size_t math_prefix_size = 1;
2412         string math_end;
2413         static vector<string> usedText = vector<string>();
2414         static bool removeMathHull = false;
2415
2416         interval_.removeAccents();
2417         interval_.removeInvalidClosings();
2418
2419         for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2420                 submath = *itmath;
2421                 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2422                         // prefixed by odd count of '\\'
2423                         continue;
2424                 }
2425                 if (math_end_waiting) {
2426                         size_t pos = submath.position(size_t(2));
2427                         if ((math_end == "$") &&
2428                                         (submath.str(2) == "$")) {
2429                                 mi.insert("$", math_pos, 1, pos, 1);
2430                                 math_end_waiting = false;
2431                         }
2432                         else if ((math_end == "\\]") &&
2433                                  (submath.str(2) == "\\]")) {
2434                                 mi.insert("\\]", math_pos, 2, pos, 2);
2435                                 math_end_waiting = false;
2436                         }
2437                         else if ((submath.str(3).compare("end") == 0) &&
2438                                  (submath.str(5).compare(math_end) == 0)) {
2439                                 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2440                                 math_end_waiting = false;
2441                         }
2442                         else
2443                                 continue;
2444                 }
2445                 else {
2446                         if (submath.str(3).compare("begin") == 0) {
2447                                 math_end_waiting = true;
2448                                 math_end = submath.str(5);
2449                                 math_pos = submath.position(size_t(2));
2450                                 math_prefix_size = submath.str(2).length();
2451                         }
2452                         else if (submath.str(2).compare("\\[") == 0) {
2453                                 math_end_waiting = true;
2454                                 math_end = "\\]";
2455                                 math_pos = submath.position(size_t(2));
2456                         }
2457                         else if (submath.str(2) == "$") {
2458                                 size_t pos = submath.position(size_t(2));
2459                                 math_end_waiting = true;
2460                                 math_end = "$";
2461                                 math_pos = pos;
2462                         }
2463                 }
2464         }
2465         // Ignore language if there is math somewhere in pattern-string
2466         if (isPatternString) {
2467                 for (auto const & s: usedText) {
2468                         // Remove entries created in previous search runs
2469                         keys.erase(s);
2470                 }
2471                 usedText = vector<string>();
2472                 if (! mi.empty()) {
2473                         // Disable language
2474                         keys["foreignlanguage"].disabled = true;
2475                         disableLanguageOverride = true;
2476                         removeMathHull = false;
2477                 }
2478                 else {
2479                         removeMathHull = true;  // used later if not isPatternString
2480                         disableLanguageOverride = false;
2481                 }
2482         }
2483         else {
2484                 if (disableLanguageOverride) {
2485                         keys["foreignlanguage"].disabled = true;
2486                 }
2487         }
2488         math_pos = mi.getFirstPos();
2489         for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2490                 sub = *it;
2491                 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2492                         // prefixed by odd count of '\\'
2493                         continue;
2494                 }
2495                 string key = sub.str(5);
2496                 if (key == "") {
2497                         if (sub.str(2)[0] == '\\')
2498                                 key = sub.str(2)[1];
2499                         else {
2500                                 key = sub.str(2);
2501                         }
2502                 }
2503                 KeysIterator it_key = keys.find(key);
2504                 if (it_key != keys.end()) {
2505                         if (it_key->second.keytype == KeyInfo::headRemove) {
2506                                 KeyInfo found1 = it_key->second;
2507                                 found1.disabled = true;
2508                                 found1.head = "\\" + key + "{";
2509                                 found1._tokenstart = sub.position(size_t(2));
2510                                 found1._tokensize = found1.head.length();
2511                                 found1._dataStart = found1._tokenstart + found1.head.length();
2512                                 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2513                                 found1._dataEnd = endpos;
2514                                 removeHead(found1);
2515                                 continue;
2516                         }
2517                 }
2518                 if (evaluatingRegexp) {
2519                         if (sub.str(3).compare("endregexp") == 0) {
2520                                 evaluatingRegexp = false;
2521                                 // found._tokenstart already set
2522                                 found._dataEnd = sub.position(size_t(2)) + 13;
2523                                 found._dataStart = found._dataEnd;
2524                                 found._tokensize = found._dataEnd - found._tokenstart;
2525                                 found.parenthesiscount = 0;
2526                                 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2527                         }
2528                         else {
2529                                 continue;
2530                         }
2531                 }
2532                 else {
2533                         if (evaluatingMath) {
2534                                 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2535                                         continue;
2536                                 evaluatingMath = false;
2537                                 mi.incrEntry();
2538                                 math_pos = mi.getStartPos();
2539                         }
2540                         if (it_key == keys.end()) {
2541                                 found = KeyInfo(KeyInfo::isStandard, 0, true);
2542                                 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2543                                 found = KeyInfo(KeyInfo::isText, 0, false);
2544                                 if (isPatternString) {
2545                                         found.keytype = KeyInfo::isChar;
2546                                         found.disabled = false;
2547                                         found.used = true;
2548                                 }
2549                                 keys[key] = found;
2550                                 usedText.push_back(key);
2551                         }
2552                         else
2553                                 found = keys[key];
2554                         if (key.compare("regexp") == 0) {
2555                                 evaluatingRegexp = true;
2556                                 found._tokenstart = sub.position(size_t(2));
2557                                 found._tokensize = 0;
2558                                 continue;
2559                         }
2560                 }
2561                 // Handle the other params of key
2562                 if (found.keytype == KeyInfo::isIgnored)
2563                         continue;
2564                 else if (found.keytype == KeyInfo::isMath) {
2565                         if (size_t(sub.position(size_t(2))) == math_pos) {
2566                                 found = keys[key];
2567                                 found._tokenstart = sub.position(size_t(2));
2568                                 found._tokensize = mi.getSize();
2569                                 found._dataEnd = found._tokenstart + found._tokensize;
2570                                 found._dataStart = found._dataEnd;
2571                                 found.parenthesiscount = 0;
2572                                 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2573                                 if (removeMathHull) {
2574                                         interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2575                                         interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2576                                 }
2577                                 else {
2578                                         // Treate all math constructs as simple math
2579                                         interval_.par[found._tokenstart] = '$';
2580                                         interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2581                                         interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2582                                         interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2583                                 }
2584                                 evaluatingMath = true;
2585                         }
2586                         else {
2587                                 // begin|end of unknown env, discard
2588                                 // First handle tables
2589                                 // longtable|tabular
2590                                 bool discardComment;
2591                                 found = keys[key];
2592                                 found.keytype = KeyInfo::doRemove;
2593                                 if ((sub.str(7).compare("longtable") == 0) ||
2594                                                 (sub.str(7).compare("tabular") == 0)) {
2595                                         discardComment = true;        /* '%' */
2596                                 }
2597                                 else {
2598                                         discardComment = false;
2599                                         static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2600                                         smatch sub2;
2601                                         string token = sub.str(7);
2602                                         if (regex_match(token, sub2, removeArgs)) {
2603                                                 found.keytype = KeyInfo::removeWithArg;
2604                                         }
2605                                 }
2606                                 // discard spaces before pos(2)
2607                                 int pos = sub.position(size_t(2));
2608                                 int count;
2609                                 for (count = 0; pos - count > 0; count++) {
2610                                         char c = interval_.par[pos-count-1];
2611                                         if (discardComment) {
2612                                                 if ((c != ' ') && (c != '%'))
2613                                                         break;
2614                                         }
2615                                         else if (c != ' ')
2616                                                 break;
2617                                 }
2618                                 found._tokenstart = pos - count;
2619                                 if (sub.str(3).compare(0, 5, "begin") == 0) {
2620                                         size_t pos1 = pos + sub.str(2).length();
2621                                         if (sub.str(7).compare("cjk") == 0) {
2622                                                 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2623                                                 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2624                                                         pos1 += 2;
2625                                                 found.keytype = KeyInfo::isMain;
2626                                                 found._dataStart = pos1;
2627                                                 found._dataEnd = interval_.par.length();
2628                                                 found.disabled = keys["foreignlanguage"].disabled;
2629                                                 found.used = keys["foreignlanguage"].used;
2630                                                 found._tokensize = pos1 - found._tokenstart;
2631                                                 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2632                                         }
2633                                         else {
2634                                                 // Swallow possible optional params
2635                                                 while (interval_.par[pos1] == '[') {
2636                                                         pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2637                                                 }
2638                                                 // Swallow also the eventual parameter
2639                                                 if (interval_.par[pos1] == '{') {
2640                                                         found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2641                                                 }
2642                                                 else {
2643                                                         found._dataEnd = pos1;
2644                                                 }
2645                                                 found._dataStart = found._dataEnd;
2646                                                 found._tokensize = count + found._dataEnd - pos;
2647                                                 found.parenthesiscount = 0;
2648                                                 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2649                                                 found.disabled = true;
2650                                         }
2651                                 }
2652                                 else {
2653                                         // Handle "\end{...}"
2654                                         found._dataStart = pos + sub.str(2).length();
2655                                         found._dataEnd = found._dataStart;
2656                                         found._tokensize = count + found._dataEnd - pos;
2657                                         found.parenthesiscount = 0;
2658                                         found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2659                                         found.disabled = true;
2660                                 }
2661                         }
2662                 }
2663                 else if (found.keytype != KeyInfo::isRegex) {
2664                         found._tokenstart = sub.position(size_t(2));
2665                         if (found.parenthesiscount == 0) {
2666                                 // Probably to be discarded
2667                                 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2668                                 char following = interval_.par[following_pos];
2669                                 if (following == ' ')
2670                                         found.head = "\\" + sub.str(5) + " ";
2671                                 else if (following == '=') {
2672                                         // like \uldepth=1000pt
2673                                         found.head = sub.str(2);
2674                                 }
2675                                 else
2676                                         found.head = "\\" + key;
2677                                 found._tokensize = found.head.length();
2678                                 found._dataEnd = found._tokenstart + found._tokensize;
2679                                 found._dataStart = found._dataEnd;
2680                         }
2681                         else {
2682                                 int params = found._tokenstart + key.length() + 1;
2683                                 if (evaluatingOptional) {
2684                                         if (size_t(found._tokenstart) > optionalEnd) {
2685                                                 evaluatingOptional = false;
2686                                         }
2687                                         else {
2688                                                 found.disabled = true;
2689                                         }
2690                                 }
2691                                 int optend = params;
2692                                 while (interval_.par[optend] == '[') {
2693                                         // discard optional parameters
2694                                         optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2695                                 }
2696                                 if (optend > params) {
2697                                         key += interval_.par.substr(params, optend-params);
2698                                         evaluatingOptional = true;
2699                                         optionalEnd = optend;
2700                                         if (found.keytype == KeyInfo::isSectioning) {
2701                                                 // Remove optional values (but still keep in header)
2702                                                 interval_.addIntervall(params, optend);
2703                                         }
2704                                 }
2705                                 string token = sub.str(7);
2706                                 int closings;
2707                                 if (interval_.par[optend] != '{') {
2708                                         closings = 0;
2709                                         found.parenthesiscount = 0;
2710                                         found.head = "\\" + key;
2711                                 }
2712                                 else
2713                                         closings = found.parenthesiscount;
2714                                 if (found.parenthesiscount == 1) {
2715                                         found.head = "\\" + key + "{";
2716                                 }
2717                                 else if (found.parenthesiscount > 1) {
2718                                         if (token != "") {
2719                                                 found.head = sub.str(2) + "{";
2720                                                 closings = found.parenthesiscount - 1;
2721                                         }
2722                                         else {
2723                                                 found.head = "\\" + key + "{";
2724                                         }
2725                                 }
2726                                 found._tokensize = found.head.length();
2727                                 found._dataStart = found._tokenstart + found.head.length();
2728                                 if (found.keytype == KeyInfo::doRemove) {
2729                                         if (closings > 0) {
2730                                                 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2731                                                 if (endpar >= interval_.par.length())
2732                                                         found._dataStart = interval_.par.length();
2733                                                 else
2734                                                         found._dataStart = endpar;
2735                                                 found._tokensize = found._dataStart - found._tokenstart;
2736                                         }
2737                                         else {
2738                                                 found._dataStart = found._tokenstart + found._tokensize;
2739                                         }
2740                                         closings = 0;
2741                                 }
2742                                 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2743                                         found._dataStart += 15;
2744                                 }
2745                                 size_t endpos;
2746                                 if (closings < 1)
2747                                         endpos = found._dataStart - 1;
2748                                 else
2749                                         endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2750                                 if (found.keytype == KeyInfo::isList) {
2751                                         // Check if it really is list env
2752                                         static regex const listre("^([a-z]+)$");
2753                                         smatch sub2;
2754                                         if (!regex_match(token, sub2, listre)) {
2755                                                 // Change the key of this entry. It is not in a list/item environment
2756                                                 found.keytype = KeyInfo::endArguments;
2757                                         }
2758                                 }
2759                                 if (found.keytype == KeyInfo::noMain) {
2760                                         evaluatingCode = true;
2761                                         codeEnd = endpos;
2762                                         codeStart = found._dataStart;
2763                                 }
2764                                 else if (evaluatingCode) {
2765                                         if (size_t(found._dataStart) > codeEnd)
2766                                                 evaluatingCode = false;
2767                                         else if (found.keytype == KeyInfo::isMain) {
2768                                                 // Disable this key, treate it as standard
2769                                                 found.keytype = KeyInfo::isStandard;
2770                                                 found.disabled = true;
2771                                                 if ((codeEnd +1 >= interval_.par.length()) &&
2772                                                                 (found._tokenstart == codeStart)) {
2773                                                         // trickery, because the code inset starts
2774                                                         // with \selectlanguage ...
2775                                                         codeEnd = endpos;
2776                                                         if (entries_.size() > 1) {
2777                                                                 entries_[entries_.size()-1]._dataEnd = codeEnd;
2778                                                         }
2779                                                 }
2780                                         }
2781                                 }
2782                                 if ((endpos == interval_.par.length()) &&
2783                                                 (found.keytype == KeyInfo::doRemove)) {
2784                                         // Missing closing => error in latex-input?
2785                                         // therefore do not delete remaining data
2786                                         found._dataStart -= 1;
2787                                         found._dataEnd = found._dataStart;
2788                                 }
2789                                 else
2790                                         found._dataEnd = endpos;
2791                         }
2792                         if (isPatternString) {
2793                                 keys[key].used = true;
2794                         }
2795                 }
2796                 entries_.push_back(found);
2797         }
2798 }
2799
2800 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2801 {
2802         stringstream s(keysstring);
2803         string key;
2804         const char delim = '|';
2805         while (getline(s, key, delim)) {
2806                 KeyInfo keyII(keyI);
2807                 if (isPatternString) {
2808                         keyII.used = false;
2809                 }
2810                 else if ( !keys[key].used)
2811                         keyII.disabled = true;
2812                 keys[key] = keyII;
2813         }
2814 }
2815
2816 void LatexInfo::buildKeys(bool isPatternString)
2817 {
2818
2819         static bool keysBuilt = false;
2820         if (keysBuilt && !isPatternString) return;
2821
2822         // Keys to ignore in any case
2823         makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2824         makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2825         // Known standard keys with 1 parameter.
2826         // Split is done, if not at start of region
2827         makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2828         makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2829         makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2830         makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2831         makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2832         makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2833
2834         makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2835                 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2836         makeKey("section*|subsection*|subsubsection*|paragraph*",
2837                 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2838         makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2839         makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2840         // Regex
2841         makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2842
2843         // Split is done, if not at start of region
2844         makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2845         makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2846
2847         // Split is done always.
2848         makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2849
2850         // Known charaters
2851         // No split
2852         makeKey("backslash|textbackslash|slash",  KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2853         makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2854         makeKey("textasciiacute|texemdash",       KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2855         makeKey("dots|ldots",                     KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2856         // Spaces
2857         makeKey("quad|qquad|hfill|dotfill",               KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2858         makeKey("textvisiblespace|nobreakspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2859         makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2860         makeKey("thickspace|medspace|thinspace",          KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2861         // Skip
2862         // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2863         // Custom space/skip, remove the content (== length value)
2864         makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2865         // Found in fr/UserGuide.lyx
2866         makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2867         // quotes
2868         makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2869         makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2870         // Known macros to remove (including their parameter)
2871         // No split
2872         makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2873         makeKey("addtocounter|setlength",                 KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2874         // handle like standard keys with 1 parameter.
2875         makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2876
2877         if (ignoreFormats.getDeleted()) {
2878                 // Ignore deleted text
2879                 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2880         }
2881         else {
2882                 // but preserve added text
2883                 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2884         }
2885         makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2886
2887         // Macros to remove, but let the parameter survive
2888         // No split
2889         makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2890
2891         // Remove language spec from content of these insets
2892         makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2893
2894         // Same effect as previous, parameter will survive (because there is no one anyway)
2895         // No split
2896         makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2897         // Remove table decorations
2898         makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2899         // Discard shape-header.
2900         // For footnote or shortcut too, because of lang settings
2901         // and wrong handling if used 'KeyInfo::noMain'
2902         makeKey("circlepar|diamondpar|heartpar|nutpar",  KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2903         makeKey("trianglerightpar|hexagonpar|starpar",   KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2904         makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2905         makeKey("triangleleftpar|shapepar|dropuppar",    KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2906         makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics",     KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2907         makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2908         makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2909         // like ('tiny{}' or '\tiny ' ... )
2910         makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2911
2912         // Survives, like known character
2913         // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2914         makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2915         makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2916
2917         makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2918         makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2919         makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2920
2921         makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2922         // Remove RTL/LTR marker
2923         makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2924         makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2925         makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2926         makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2927         makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2928         makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2929         makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2930         if (isPatternString) {
2931                 // Allow the first searched string to rebuild the keys too
2932                 keysBuilt = false;
2933         }
2934         else {
2935                 // no need to rebuild again
2936                 keysBuilt = true;
2937         }
2938 }
2939
2940 /*
2941  * Keep the list of actual opened parentheses actual
2942  * (e.g. depth == 4 means there are 4 '{' not processed yet)
2943  */
2944 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2945 {
2946         int skip = 0;
2947         for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2948                 char c;
2949                 c = par[i];
2950                 skip = 0;
2951                 if (c == '\\') skip = 1;
2952                 else if (c == '{') {
2953                         handleOpenP(i);
2954                 }
2955                 else if (c == '}') {
2956                         handleCloseP(i, closingAllowed);
2957                 }
2958         }
2959 }
2960
2961 #if (0)
2962 string Intervall::show(int lastpos)
2963 {
2964         int idx = 0;                          /* int intervalls */
2965         string s;
2966         int i = 0;
2967         if ((unsigned) lastpos > par.size())
2968                 lastpos = par.size();
2969         for (idx = 0; idx <= ignoreidx; idx++) {
2970                 while (i < lastpos) {
2971                         int printsize;
2972                         if (i <= borders[idx].low) {
2973                                 if (borders[idx].low > lastpos)
2974                                         printsize = lastpos - i;
2975                                 else
2976                                         printsize = borders[idx].low - i;
2977                                 s += par.substr(i, printsize);
2978                                 i += printsize;
2979                                 if (i >= borders[idx].low)
2980                                         i = borders[idx].upper;
2981                         }
2982                         else {
2983                                 i = borders[idx].upper;
2984                                 break;
2985                         }
2986                 }
2987         }
2988         if (lastpos > i) {
2989                 s += par.substr(i, lastpos-i);
2990         }
2991         return s;
2992 }
2993 #endif
2994
2995 void Intervall::output(ostringstream &os, int lastpos)
2996 {
2997         // get number of chars to output
2998         int idx = 0;                          /* int intervalls */
2999         int i = 0;
3000         int printed = 0;
3001         string startTitle = titleValue;
3002         for (idx = 0; idx <= ignoreidx; idx++) {
3003                 if (i < lastpos) {
3004                         if (i <= borders[idx].low) {
3005                                 int printsize;
3006                                 if (borders[idx].low > lastpos)
3007                                         printsize = lastpos - i;
3008                                 else
3009                                         printsize = borders[idx].low - i;
3010                                 if (printsize > 0) {
3011                                         os << startTitle << par.substr(i, printsize);
3012                                         i += printsize;
3013                                         printed += printsize;
3014                                         startTitle = "";
3015                                 }
3016                                 handleParentheses(i, false);
3017                                 if (i >= borders[idx].low)
3018                                         i = borders[idx].upper;
3019                         }
3020                         else {
3021                                 i = borders[idx].upper;
3022                         }
3023                 }
3024                 else
3025                         break;
3026         }
3027         if (lastpos > i) {
3028                 os << startTitle << par.substr(i, lastpos-i);
3029                 printed += lastpos-i;
3030         }
3031         handleParentheses(lastpos, false);
3032         int startindex;
3033         if (keys["foreignlanguage"].disabled)
3034                 startindex = actualdeptindex-langcount;
3035         else
3036                 startindex = actualdeptindex;
3037         for (int i = startindex; i > 0; --i) {
3038                 os << "}";
3039         }
3040         if (hasTitle && (printed > 0))
3041                 os << "}";
3042         if (! isPatternString_)
3043                 os << "\n";
3044         handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3045 }
3046
3047 void LatexInfo::processRegion(int start, int region_end)
3048 {
3049         while (start < region_end) {          /* Let {[} and {]} survive */
3050                 int cnt = interval_.isOpeningPar(start);
3051                 if (cnt == 1) {
3052                         // Closing is allowed past the region
3053                         int closing = interval_.findclosing(start+1, interval_.par.length());
3054                         interval_.addIntervall(start, start+1);
3055                         interval_.addIntervall(closing, closing+1);
3056                 }
3057                 else if (cnt == 3)
3058                         start += 2;
3059                 start = interval_.nextNotIgnored(start+1);
3060         }
3061 }
3062
3063 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3064 {
3065         if (actual.parenthesiscount == 0) {
3066                 // "{\tiny{} ...}" ==> "{{} ...}"
3067                 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3068         }
3069         else {
3070                 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3071                 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3072                 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3073         }
3074 }
3075
3076 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3077 {
3078         int nextKeyIdx = 0;
3079         switch (actual.keytype)
3080         {
3081         case KeyInfo::isTitle: {
3082                 removeHead(actual);
3083                 nextKeyIdx = getNextKey();
3084                 break;
3085         }
3086         case KeyInfo::cleanToStart: {
3087                 actual._dataEnd = actual._dataStart;
3088                 nextKeyIdx = getNextKey();
3089                 // Search for end of arguments
3090                 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3091                 if (tmpIdx > 0) {
3092                         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3093                                 entries_[i].disabled = true;
3094                         }
3095                         actual._dataEnd = entries_[tmpIdx]._dataEnd;
3096                 }
3097                 while (interval_.par[actual._dataEnd] == ' ')
3098                         actual._dataEnd++;
3099                 interval_.addIntervall(0, actual._dataEnd+1);
3100                 interval_.actualdeptindex = 0;
3101                 interval_.depts[0] = actual._dataEnd+1;
3102                 interval_.closes[0] = -1;
3103                 break;
3104         }
3105         case KeyInfo::isText:
3106                 interval_.par[actual._tokenstart] = '#';
3107                 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3108                 nextKeyIdx = getNextKey();
3109                 break;
3110         case KeyInfo::noContent: {          /* char like "\hspace{2cm}" */
3111                 if (actual.disabled)
3112                         interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3113                 else
3114                         interval_.addIntervall(actual._dataStart, actual._dataEnd);
3115         }
3116                 // fall through
3117         case KeyInfo::isChar: {
3118                 nextKeyIdx = getNextKey();
3119                 break;
3120         }
3121         case KeyInfo::isSize: {
3122                 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3123                         if (actual.parenthesiscount == 0)
3124                                 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3125                         else {
3126                                 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3127                         }
3128                         nextKeyIdx = getNextKey();
3129                 } else {
3130                         // Here _dataStart points to '{', so correct it
3131                         actual._dataStart += 1;
3132                         actual._tokensize += 1;
3133                         actual.parenthesiscount = 1;
3134                         if (interval_.par[actual._dataStart] == '}') {
3135                                 // Determine the end if used like '{\tiny{}...}'
3136                                 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3137                                 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3138                         }
3139                         else {
3140                                 // Determine the end if used like '\tiny{...}'
3141                                 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3142                         }
3143                         // Split on this key if not at start
3144                         int start = interval_.nextNotIgnored(previousStart);
3145                         if (start < actual._tokenstart) {
3146                                 interval_.output(os, actual._tokenstart);
3147                                 interval_.addIntervall(start, actual._tokenstart);
3148                         }
3149                         // discard entry if at end of actual
3150                         nextKeyIdx = process(os, actual);
3151                 }
3152                 break;
3153         }
3154         case KeyInfo::endArguments: {
3155                 // Remove trailing '{}' too
3156                 actual._dataStart += 1;
3157                 actual._dataEnd += 1;
3158                 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3159                 nextKeyIdx = getNextKey();
3160                 break;
3161         }
3162         case KeyInfo::noMain:
3163                 // fall through
3164         case KeyInfo::isStandard: {
3165                 if (actual.disabled) {
3166                         removeHead(actual);
3167                         processRegion(actual._dataStart, actual._dataStart+1);
3168                         nextKeyIdx = getNextKey();
3169                 } else {
3170                         // Split on this key if not at datastart of calling entry
3171                         int start = interval_.nextNotIgnored(previousStart);
3172                         if (start < actual._tokenstart) {
3173                                 interval_.output(os, actual._tokenstart);
3174                                 interval_.addIntervall(start, actual._tokenstart);
3175                         }
3176                         // discard entry if at end of actual
3177                         nextKeyIdx = process(os, actual);
3178                 }
3179                 break;
3180         }
3181         case KeyInfo::removeWithArg: {
3182                 nextKeyIdx = getNextKey();
3183                 // Search for end of arguments
3184                 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3185                 if (tmpIdx > 0) {
3186                         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3187                                 entries_[i].disabled = true;
3188                         }
3189                         actual._dataEnd = entries_[tmpIdx]._dataEnd;
3190                 }
3191                 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3192                 break;
3193         }
3194         case KeyInfo::doRemove: {
3195                 // Remove the key with all parameters and following spaces
3196                 size_t pos;
3197                 size_t start;
3198                 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3199                         start = actual._dataEnd;
3200                 else
3201                         start = actual._dataEnd+1;
3202                 for (pos = start; pos < interval_.par.length(); pos++) {
3203                         if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3204                                 break;
3205                 }
3206                 // Remove also enclosing parentheses [] and {}
3207                 int numpars = 0;
3208                 int spaces = 0;
3209                 while (actual._tokenstart > numpars) {
3210                         if (pos+numpars >= interval_.par.size())
3211                                 break;
3212                         else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3213                                 numpars++;
3214                         else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3215                                 numpars++;
3216                         else
3217                                 break;
3218                 }
3219                 if (numpars > 0) {
3220                         if (interval_.par[pos+numpars] == ' ')
3221                                 spaces++;
3222                 }
3223
3224                 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3225                 nextKeyIdx = getNextKey();
3226                 break;
3227         }
3228         case KeyInfo::isList: {
3229                 // Discard space before _tokenstart
3230                 int count;
3231                 for (count = 0; count < actual._tokenstart; count++) {
3232                         if (interval_.par[actual._tokenstart-count-1] != ' ')
3233                                 break;
3234                 }
3235                 nextKeyIdx = getNextKey();
3236                 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3237                 if (tmpIdx > 0) {
3238                         // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3239                         // with arguments
3240                         // How else can we catch this one?
3241                         for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3242                                 entries_[i].disabled = true;
3243                         }
3244                         actual._dataEnd = entries_[tmpIdx]._dataEnd;
3245                 }
3246                 else if (nextKeyIdx > 0) {
3247                         // Ignore any lang entries inside data region
3248                         for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3249                                 if (entries_[i].keytype == KeyInfo::isMain)
3250                                         entries_[i].disabled = true;
3251                         }
3252                 }
3253                 if (actual.disabled) {
3254                         interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3255                 }
3256                 else {
3257                         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3258                 }
3259                 if (interval_.par[actual._dataEnd+1] == '[') {
3260                         int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3261                         if ((interval_.par[actual._dataEnd+2] == '{') &&
3262                                         (interval_.par[posdown-1] == '}')) {
3263                                 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3264                                 interval_.addIntervall(posdown-1, posdown+1);
3265                         }
3266                         else {
3267                                 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3268                                 interval_.addIntervall(posdown, posdown+1);
3269                         }
3270                         int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3271                         if (blk > posdown) {
3272                                 // Discard at most 1 space after empty item
3273                                 int count;
3274                                 for (count = 0; count < 1; count++) {
3275                                         if (interval_.par[blk+count] != ' ')
3276                                                 break;
3277                                 }
3278                                 if (count > 0)
3279                                         interval_.addIntervall(blk, blk+count);
3280                         }
3281                 }
3282                 break;
3283         }
3284         case KeyInfo::isSectioning: {
3285                 // Discard spaces before _tokenstart
3286                 int count;
3287                 int val = actual._tokenstart;
3288                 for (count = 0; count < actual._tokenstart;) {
3289                         val = interval_.previousNotIgnored(val-1);
3290                         if (val < 0 || interval_.par[val] != ' ')
3291                                 break;
3292                         else {
3293                                 count = actual._tokenstart - val;
3294                         }
3295                 }
3296                 if (actual.disabled) {
3297                         removeHead(actual, count);
3298                         nextKeyIdx = getNextKey();
3299                 } else {
3300                         interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3301                         nextKeyIdx = process(os, actual);
3302                 }
3303                 break;
3304         }
3305         case KeyInfo::isMath: {
3306                 // Same as regex, use the content unchanged
3307                 nextKeyIdx = getNextKey();
3308                 break;
3309         }
3310         case KeyInfo::isRegex: {
3311                 // DO NOT SPLIT ON REGEX
3312                 // Do not disable
3313                 nextKeyIdx = getNextKey();
3314                 break;
3315         }
3316         case KeyInfo::isIgnored: {
3317                 // Treat like a character for now
3318                 nextKeyIdx = getNextKey();
3319                 break;
3320         }
3321         case KeyInfo::isMain: {
3322                 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3323                         interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3324                 if (actual._tokenstart > 0) {
3325                         int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3326                         if ((prev >= 0) && interval_.par[prev] == '%')
3327                                 interval_.addIntervall(prev, prev+1);
3328                 }
3329                 if (actual.disabled) {
3330                         removeHead(actual);
3331                         interval_.langcount++;
3332                         if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3333                                         (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3334                                 // Discard also the space before math-equation
3335                                 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3336                         }
3337                         nextKeyIdx = getNextKey();
3338                         // interval.resetOpenedP(actual._dataStart-1);
3339                 }
3340                 else {
3341                         if (actual._tokenstart < 26) {
3342                                 // for the first (and maybe dummy) language
3343                                 interval_.setForDefaultLang(actual);
3344                         }
3345                         interval_.resetOpenedP(actual._dataStart-1);
3346                 }
3347                 break;
3348         }
3349         case KeyInfo::invalid:
3350         case KeyInfo::headRemove:
3351                 // These two cases cannot happen, already handled
3352                 // fall through
3353         default: {
3354                 // LYXERR(Debug::INFO, "Unhandled keytype");
3355                 nextKeyIdx = getNextKey();
3356                 break;
3357         }
3358         }
3359         return nextKeyIdx;
3360 }
3361
3362 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3363 {
3364         int end = interval_.nextNotIgnored(actual._dataEnd);
3365         int oldStart = actual._dataStart;
3366         int nextKeyIdx = getNextKey();
3367         while (true) {
3368                 if ((nextKeyIdx < 0) ||
3369                                 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3370                                 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3371                         if (oldStart <= end) {
3372                                 processRegion(oldStart, end);
3373                                 oldStart = end+1;
3374                         }
3375                         break;
3376                 }
3377                 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3378
3379                 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3380                         (void) dispatch(os, actual._dataStart, nextKey);
3381                         end = nextKey._tokenstart;
3382                         break;
3383                 }
3384                 processRegion(oldStart, nextKey._tokenstart);
3385                 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3386
3387                 oldStart = nextKey._dataEnd+1;
3388         }
3389         // now nextKey is either invalid or is outside of actual._dataEnd
3390         // output the remaining and discard myself
3391         if (oldStart <= end) {
3392                 processRegion(oldStart, end);
3393         }
3394         if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3395                 end += 1;
3396                 // This is the normal case.
3397                 // But if using the firstlanguage, the closing may be missing
3398         }
3399         // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3400         int output_end;
3401         if (actual._dataEnd < end)
3402                 output_end = interval_.nextNotIgnored(actual._dataEnd);
3403         else if (interval_.par.size() > (size_t) end)
3404                 output_end = interval_.nextNotIgnored(end);
3405         else
3406                 output_end = interval_.par.size();
3407         if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3408                 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3409         }
3410         // Remove possible empty data
3411         int dstart = interval_.nextNotIgnored(actual._dataStart);
3412         while (interval_.isOpeningPar(dstart) == 1) {
3413                 interval_.addIntervall(dstart, dstart+1);
3414                 int dend = interval_.findclosing(dstart+1, output_end);
3415                 interval_.addIntervall(dend, dend+1);
3416                 dstart = interval_.nextNotIgnored(dstart+1);
3417         }
3418         if (dstart < output_end)
3419                 interval_.output(os, output_end);
3420         if (nextKeyIdx < 0)
3421                 interval_.addIntervall(0, end);
3422         else
3423                 interval_.addIntervall(actual._tokenstart, end);
3424         return nextKeyIdx;
3425 }
3426
3427 string splitOnKnownMacros(string par, bool isPatternString)
3428 {
3429         ostringstream os;
3430         LatexInfo li(par, isPatternString);
3431         // LYXERR(Debug::INFO, "Berfore split: " << par);
3432         KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3433         DummyKey.head = "";
3434         DummyKey._tokensize = 0;
3435         DummyKey._dataStart = 0;
3436         DummyKey._dataEnd = par.length();
3437         DummyKey.disabled = true;
3438         int firstkeyIdx = li.getFirstKey();
3439         string s;
3440         if (firstkeyIdx >= 0) {
3441                 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3442                 DummyKey._tokenstart = firstKey._tokenstart;
3443                 int nextkeyIdx;
3444                 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3445                         // Use dummy firstKey
3446                         firstKey = DummyKey;
3447                         (void) li.setNextKey(firstkeyIdx);
3448                 }
3449                 else {
3450                         if (par.substr(firstKey._dataStart, 2) == "% ")
3451                                 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3452                 }
3453                 nextkeyIdx = li.process(os, firstKey);
3454                 while (nextkeyIdx >= 0) {
3455                         // Check for a possible gap between the last
3456                         // entry and this one
3457                         int datastart = li.nextNotIgnored(firstKey._dataStart);
3458                         KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3459                         if ((nextKey._tokenstart > datastart)) {
3460                                 // Handle the gap
3461                                 firstKey._dataStart = datastart;
3462                                 firstKey._dataEnd = par.length();
3463                                 (void) li.setNextKey(nextkeyIdx);
3464                                 // Fake the last opened parenthesis
3465                                 li.setForDefaultLang(firstKey);
3466                                 nextkeyIdx = li.process(os, firstKey);
3467                         }
3468                         else {
3469                                 if (nextKey.keytype != KeyInfo::isMain) {
3470                                         firstKey._dataStart = datastart;
3471                                         firstKey._dataEnd = nextKey._dataEnd+1;
3472                                         (void) li.setNextKey(nextkeyIdx);
3473                                         li.setForDefaultLang(firstKey);
3474                                         nextkeyIdx = li.process(os, firstKey);
3475                                 }
3476                                 else {
3477                                         nextkeyIdx = li.process(os, nextKey);
3478                                 }
3479                         }
3480                 }
3481                 // Handle the remaining
3482                 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3483                 firstKey._dataEnd = par.length();
3484                 // Check if ! empty
3485                 if ((firstKey._dataStart < firstKey._dataEnd) &&
3486                                 (par[firstKey._dataStart] != '}')) {
3487                         li.setForDefaultLang(firstKey);
3488                         (void) li.process(os, firstKey);
3489                 }
3490                 s = os.str();
3491                 // return string definitelly impossible to match, but should be known
3492         }
3493         else
3494                 s = par;                            /* no known macros found */
3495         // LYXERR(Debug::INFO, "After split: " << s);
3496         return s;
3497 }
3498
3499 /*
3500  * Try to unify the language specs in the latexified text.
3501  * Resulting modified string is set to "", if
3502  * the searched tex does not contain all the features in the search pattern
3503  */
3504 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3505 {
3506         static Features regex_f;
3507         static int missed = 0;
3508         static bool regex_with_format = false;
3509
3510         int parlen = par.length();
3511
3512         while ((parlen > 0) && (par[parlen-1] == '\n')) {
3513                 parlen--;
3514         }
3515 #if 0
3516         if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3517                 // Happens to be there in case of description or labeling environment
3518                 parlen--;
3519         }
3520 #endif
3521         string result;
3522         if (withformat) {
3523                 // Split the latex input into pieces which
3524                 // can be digested by our search engine
3525                 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3526                 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3527                         // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3528                         string doclang = pbuf->params().language->polyglossia();
3529                         static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3530                         smatch sub;
3531                         bool toIgnoreLang = true;
3532                         for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3533                                 sub = *it;
3534                                 if (sub.str(2) != doclang) {
3535                                         toIgnoreLang = false;
3536                                         break;
3537                                 }
3538                         }
3539                         setIgnoreFormat("language", toIgnoreLang, false);
3540
3541                 }
3542                 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3543                 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3544         }
3545         else
3546                 result = par.substr(0, parlen);
3547         if (isPatternString) {
3548                 missed = 0;
3549                 if (withformat) {
3550                         regex_f = identifyFeatures(result);
3551                         string features = "";
3552                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3553                                 string a = it->first;
3554                                 regex_with_format = true;
3555                                 features += " " + a;
3556                                 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3557                         }
3558                         LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3559
3560                 }
3561         } else if (regex_with_format) {
3562                 Features info = identifyFeatures(result);
3563                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3564                         string a = it->first;
3565                         bool b = it->second;
3566                         if (b && ! info[a]) {
3567                                 missed++;
3568                                 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3569                                 return "";
3570                         }
3571                 }
3572
3573         }
3574         else {
3575                 // LYXERR(Debug::INFO, "No regex formats");
3576         }
3577         return result;
3578 }
3579
3580
3581 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3582 static void identifyClosing(string & t, bool ignoreformat)
3583 {
3584         do {
3585                 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3586                 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3587                         continue;
3588                 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3589                         continue;
3590                 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3591                         continue;
3592                 if (! ignoreformat) {
3593                         if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3594                                 continue;
3595                 }
3596                 break;
3597         } while (true);
3598         return;
3599 }
3600
3601 static int num_replaced = 0;
3602 static bool previous_single_replace = true;
3603
3604 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3605 {
3606 #if QTSEARCH
3607         if (regexp_str.empty() || regexp2_str.empty()) {
3608                 regexIsValid = false;
3609                 regexError = "Invalid empty regex";
3610                 return;
3611         }
3612         // Handle \w properly
3613         QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3614         if (! opt.casesensitive) {
3615                 popts |= QRegularExpression::CaseInsensitiveOption;
3616         }
3617         regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3618         regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3619         regexError = "";
3620         if (regexp.isValid() && regexp2.isValid()) {
3621                 regexIsValid = true;
3622                 // Check '{', '}' pairs inside the regex
3623                 int balanced = 0;
3624                 int skip = 1;
3625                 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3626                         char c = par_as_string[i];
3627                         if (c == '\\') {
3628                                 skip = 2;
3629                                 continue;
3630                         }
3631                         if (c == '{')
3632                                 balanced++;
3633                         else if (c == '}') {
3634                                 balanced--;
3635                                 if (balanced < 0)
3636                                         break;
3637                         }
3638                         skip = 1;
3639                 }
3640                 if (balanced != 0) {
3641                         regexIsValid = false;
3642                         regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3643                 }
3644         }
3645         else {
3646                 regexIsValid = false;
3647                 if (!regexp.isValid())
3648                         regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3649                 else
3650                         regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3651         }
3652 #else
3653         (void)par_as_string;
3654         if (opt.casesensitive) {
3655                 regexp = regex(regexp_str);
3656                 regexp2 = regex(regexp2_str);
3657         }
3658         else {
3659                 regexp = regex(regexp_str, std::regex_constants::icase);
3660                 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3661         }
3662 #endif
3663 }
3664
3665 static void modifyRegexForMatchWord(string &t)
3666 {
3667         string s("");
3668         regex wordre("(\\\\)*((\\.|\\\\b))");
3669         size_t lastpos = 0;
3670         smatch sub;
3671         for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3672                 sub = *it;
3673                 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3674                         continue;
3675                 }
3676                 else if (sub.str(2) == "\\\\b")
3677                         return;
3678                 if (lastpos < (size_t) sub.position(2))
3679                         s += t.substr(lastpos, sub.position(2) - lastpos);
3680                 s += "\\S";
3681                 lastpos = sub.position(2) + sub.length(2);
3682         }
3683         if (lastpos == 0) {
3684                 s = "\\b" + t + "\\b";
3685                 t = s;
3686                 return;
3687         }
3688         else if (lastpos < t.length())
3689                 s += t.substr(lastpos, t.length() - lastpos);
3690         t = "\\b" + s + "\\b";
3691 }
3692
3693 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3694         : p_buf(&buf), p_first_buf(&buf), opt(opt)
3695 {
3696         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3697         docstring const & ds = stringifySearchBuffer(find_buf, opt);
3698         if (ds.empty() ) {
3699                 CreateRegexp(opt, "", "", "");
3700                 return;
3701         }
3702         use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3703         if (opt.replace_all && previous_single_replace) {
3704                 previous_single_replace = false;
3705                 num_replaced = 0;
3706         }
3707         else if (!opt.replace_all) {
3708                 num_replaced = 0;       // count number of replaced strings
3709                 previous_single_replace = true;
3710         }
3711         // When using regexp, braces are hacked already by escape_for_regex()
3712         par_as_string = convertLF2Space(ds, opt.ignoreformat);
3713
3714         size_t lead_size = 0;
3715         // correct the language settings
3716         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3717         if (par_as_string.empty()) {
3718                 CreateRegexp(opt, "", "", "");
3719                 return;
3720         }
3721         opt.matchAtStart = false;
3722         if (!use_regexp) {
3723                 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3724                 if (opt.ignoreformat) {
3725                         lead_size = 0;
3726                 }
3727                 else {
3728                         lead_size = identifyLeading(par_as_string);
3729                 }
3730                 lead_as_string = par_as_string.substr(0, lead_size);
3731                 string lead_as_regex_string = string2regex(lead_as_string);
3732                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3733                 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3734                 /* Handle whole words too in this case
3735                 */
3736                 if (opt.matchword) {
3737                         par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3738                         opt.matchword = false;
3739                 }
3740                 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3741                 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3742                 CreateRegexp(opt, regexp_str, regexp2_str);
3743                 use_regexp = true;
3744                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3745                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3746                 return;
3747         }
3748
3749         if (!opt.ignoreformat) {
3750                 lead_size = identifyLeading(par_as_string);
3751                 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3752                 lead_as_string = par_as_string.substr(0, lead_size);
3753                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3754         }
3755
3756         // Here we are using regexp
3757         LASSERT(use_regexp, /**/);
3758         {
3759                 string lead_as_regexp;
3760                 if (lead_size > 0) {
3761                         lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3762                         (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3763                         (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3764                         par_as_string = par_as_string_nolead;
3765                         LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3766                         LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3767                 }
3768                 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3769                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3770                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3771                 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3772                 ++close_wildcards;
3773                 size_t lng = par_as_string.size();
3774                 if (!opt.ignoreformat) {
3775                         // Remove extra '\}' at end if not part of \{\.\}
3776                         while(lng > 2) {
3777                                 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3778                                         if (lng >= 6) {
3779                                                 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3780                                                         break;
3781                                         }
3782                                         lng -= 2;
3783                                         open_braces++;
3784                                 }
3785                                 else
3786                                         break;
3787                         }
3788                         if (lng < par_as_string.size())
3789                                 par_as_string.resize(lng);
3790                 }
3791                 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3792                 if ((lng > 0) && (par_as_string[0] == '^')) {
3793                         par_as_string = par_as_string.substr(1);
3794                         --lng;
3795                         opt.matchAtStart = true;
3796                 }
3797                 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3798                 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3799                 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3800
3801                 // If entered regexp must match at begin of searched string buffer
3802                 // Kornel: Added parentheses to use $1 for size of the leading string
3803                 string regexp_str;
3804                 string regexp2_str;
3805                 {
3806                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3807                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
3808                         // so the convert has no effect in that case
3809                         for (int i = 7; i > 0; --i) {
3810                                 string orig = "\\\\" + std::to_string(i);
3811                                 string dest = "\\" + std::to_string(i+2);
3812                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
3813                         }
3814                         if (opt.matchword) {
3815                                 modifyRegexForMatchWord(par_as_string);
3816                                 // opt.matchword = false;
3817                         }
3818                         regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3819                         regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3820                 }
3821                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3822                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3823                 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3824         }
3825 }
3826
3827 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3828 {
3829         MatchResult mres;
3830
3831         mres.searched_size = len;
3832
3833         docstring docstr = stringifyFromForSearch(opt, cur, len);
3834         string str;
3835         str = convertLF2Space(docstr, opt.ignoreformat);
3836         if (!opt.ignoreformat) {
3837                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3838                 // remove closing '}' and '\n' to allow for use of '$' in regex
3839                 size_t lng = str.size();
3840                 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3841                         lng--;
3842                 if (lng != str.size()) {
3843                         str = str.substr(0, lng);
3844                 }
3845                 // Replace occurences of '~' to ' '
3846                 static std::regex specialChars { R"(~)" };
3847                 str = std::regex_replace(str, specialChars,  R"( )" );
3848         }
3849         if (str.empty()) {
3850                 mres.match_len = -1;
3851                 return mres;
3852         }
3853         LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3854
3855         LASSERT(use_regexp, /**/);
3856         {
3857                 // use_regexp always true
3858                 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3859 #if QTSEARCH
3860                 QString qstr = QString::fromStdString(str);
3861                 QRegularExpression const *p_regexp;
3862                 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3863                 if (at_begin == MatchStringAdv::MatchFromStart) {
3864                         p_regexp = &regexp;
3865                 } else {
3866                         p_regexp = &regexp2;
3867                 }
3868                 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3869                 if (!match.hasMatch())
3870                         return mres;
3871 #else
3872                 regex const *p_regexp;
3873                 regex_constants::match_flag_type flags;
3874                 if (at_begin == MatchStringAdv::MatchFromStart) {
3875                         flags = regex_constants::match_continuous;
3876                         p_regexp = &regexp;
3877                 } else {
3878                         flags = regex_constants::match_default;
3879                         p_regexp = &regexp2;
3880                 }
3881                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3882                 if (re_it == sregex_iterator())
3883                         return mres;
3884                 match_results<string::const_iterator> const & m = *re_it;
3885 #endif
3886                 // Whole found string, including the leading
3887                 // std: m[0].second - m[0].first
3888                 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3889                 //
3890                 // Size of the leading string
3891                 // std: m[1].second - m[1].first
3892                 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3893                 int leadingsize = 0;
3894 #if QTSEARCH
3895                 if (match.lastCapturedIndex() > 0) {
3896                         leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3897                 }
3898
3899 #else
3900                 if (m.size() > 2) {
3901                         leadingsize = m[1].second - m[1].first;
3902                 }
3903 #endif
3904 #if QTSEARCH
3905                 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3906                 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3907                 // because of different number of closing at end of string
3908                 // we have to 'unify' the length of the post-match.
3909                 // Done by ignoring closing parenthesis and linefeeds at string end
3910                 int matchend = match.capturedEnd(0);
3911                 size_t strsize = qstr.size();
3912                 if (!opt.ignoreformat) {
3913                         while (mres.match_len > 1) {
3914                                 QChar c = qstr.at(matchend - 1);
3915                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3916                                         mres.match_len--;
3917                                         matchend--;
3918                                 }
3919                                 else
3920                                         break;
3921                         }
3922                         while (strsize > (size_t) match.capturedEnd(0)) {
3923                                 QChar c = qstr.at(strsize-1);
3924                                 if ((c == '\n') || (c == '}')) {
3925                                         --strsize;
3926                                 }
3927                                 else
3928                                         break;
3929                         }
3930                 }
3931                 // LYXERR0(qstr.toStdString());
3932                 mres.match2end = strsize - matchend;
3933                 mres.pos = match.capturedStart(2);
3934 #else
3935                 mres.match_prefix = m[2].second - m[2].first;
3936                 mres.match_len = m[0].second - m[2].second;
3937                 // ignore closing parenthesis and linefeeds at string end
3938                 size_t strend = m[0].second - m[0].first;
3939                 int matchend = strend;
3940                 size_t strsize = str.size();
3941                 if (!opt.ignoreformat) {
3942                         while (mres.match_len > 1) {
3943                                 char c = str.at(matchend - 1);
3944                                 if ((c == '\n') || (c == '}') || (c == '{')) {
3945                                         mres.match_len--;
3946                                         matchend--;
3947                                 }
3948                                 else
3949                                         break;
3950                         }
3951                         while (strsize > strend) {
3952                                 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3953                                         --strsize;
3954                                 }
3955                                 else
3956                                         break;
3957                         }
3958                 }
3959                 // LYXERR0(str);
3960                 mres.match2end = strsize - matchend;
3961                 mres.pos = m[2].first - m[0].first;;
3962 #endif
3963                 if (mres.match2end < 0)
3964                         mres.match_len = 0;
3965                 mres.leadsize = leadingsize;
3966 #if QTSEARCH
3967                 if (mres.match_len > 0) {
3968                         string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3969                         mres.result.push_back(a0);
3970                         for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3971                                 mres.result.push_back(match.captured(i).toStdString());
3972                         }
3973                 }
3974 #else
3975                 if (mres.match_len > 0) {
3976                         string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3977                         mres.result.push_back(a0);
3978                         for (size_t i = 3; i < m.size(); i++) {
3979                                 mres.result.push_back(m[i]);
3980                         }
3981                 }
3982 #endif
3983                 return mres;
3984         }
3985 }
3986
3987
3988 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3989 {
3990         MatchResult mres = findAux(cur, len, at_begin);
3991         LYXERR(Debug::FINDVERBOSE,
3992                "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3993                << ", matchAtStart=" << opt.matchAtStart
3994                << ", inTexted=" << cur.inTexted());
3995         if (mres.match_len > 0) {
3996                 if (opt.matchAtStart) {
3997                         if (cur.pos() > 0 || mres.match_prefix > 0)
3998                                 mres.match_len = 0;
3999                 }
4000         }
4001         return mres;
4002 }
4003
4004 #if 0
4005 static bool simple_replace(string &t, string from, string to)
4006 {
4007         regex repl("(\\\\)*(" + from + ")");
4008         string s("");
4009         size_t lastpos = 0;
4010         smatch sub;
4011         for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
4012                 sub = *it;
4013                 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4014                         continue;
4015                 if (lastpos < (size_t) sub.position(2))
4016                         s += t.substr(lastpos, sub.position(2) - lastpos);
4017                 s += to;
4018                 lastpos = sub.position(2) + sub.length(2);
4019         }
4020         if (lastpos == 0)
4021                 return false;
4022         else if (lastpos < t.length())
4023                 s += t.substr(lastpos, t.length() - lastpos);
4024         t = s;
4025         return true;
4026 }
4027 #endif
4028
4029 string MatchStringAdv::convertLF2Space(docstring const &s, bool ignore_format) const
4030 {
4031         // Using original docstring to handle '\n'
4032
4033         if (s.size() == 0) return "";
4034         stringstream t;
4035         size_t pos;
4036         size_t start = 0;
4037         size_t end = s.size() - 1;
4038         if (!ignore_format) {
4039                 while (s[start] == '\n' && start <= end)
4040                         start++;
4041                 while (end >= start && s[end] == '\n')
4042                         end--;
4043                 if (start >= end + 1)
4044                         return "";
4045         }
4046         do {
4047                 bool dospace = true;
4048                 int skip = -1;
4049                 pos = s.find('\n', start);
4050                 if (pos >= end) {
4051                         t << lyx::to_utf8(s.substr(start, end + 1 - start));
4052                         break;
4053                 }
4054                 if (!ignore_format) {
4055                         if ((pos > start + 1) &&
4056                              s[pos-1] == '\\' &&
4057                              s[pos-2] == '\\') {
4058                                 skip = 2;
4059                                 if ((pos > start + 2) &&
4060                                     (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4061                                      s[pos-3] == '~' || isSpace(s[pos-3]))) {
4062                                         // discard "\\\\\n", do not replace with space
4063                                         dospace = false;
4064                                 }
4065                         }
4066                         else if (pos > start) {
4067                                 if (s[pos-1] == '%') {
4068                                         skip = 1;
4069                                         while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4070                                                 skip++;
4071                                         if ((pos > start+skip) &&
4072                                             (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4073                                              s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4074                                                 // discard '%%%%%\n'
4075                                                 dospace = false;
4076                                         }
4077                                 }
4078                                 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4079                                         dospace = false;
4080                                         skip = 0;       // remove the '\n' only
4081                                 }
4082                         }
4083                 }
4084                 else {
4085                         dospace = true;
4086                         skip = 0;
4087                 }
4088                 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4089                 if (dospace)
4090                         t << ' ';
4091                 start = pos+1;
4092         } while (start <= end);
4093         return(t.str());
4094 }
4095
4096 docstring stringifyFromCursor(DocIterator const & cur, int len)
4097 {
4098         LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4099         if (cur.inTexted()) {
4100                 Paragraph const & par = cur.paragraph();
4101                 // TODO what about searching beyond/across paragraph breaks ?
4102                 // TODO Try adding a AS_STR_INSERTS as last arg
4103                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4104                                         int(par.size()) : cur.pos() + len;
4105                 // OutputParams runparams(&cur.buffer()->params().encoding());
4106                 OutputParams runparams(encodings.fromLyXName("utf8"));
4107                 runparams.nice = true;
4108                 setFindParams(runparams);
4109                 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4110                 if (ignoreFormats.getDeleted()) {
4111                         option |= AS_STR_SKIPDELETE;
4112                         runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4113                 }
4114                 else {
4115                         runparams.find_set_feature(OutputParams::SearchWithDeleted);
4116                 }
4117                 if (ignoreFormats.getNonContent()) {
4118                         runparams.find_add_feature(OutputParams::SearchNonOutput);
4119                 }
4120                 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4121                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
4122                 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4123                                                                         option,
4124                                                                         &runparams), false));
4125                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4126                 return res;
4127         } else if (cur.inMathed()) {
4128                 CursorSlice cs = cur.top();
4129                 MathData md = cs.cell();
4130                 MathData::const_iterator it_end =
4131                                 (( len == -1 || cs.pos() + len > int(md.size()))
4132                                  ? md.end()
4133                                  : md.begin() + cs.pos() + len );
4134                 MathData md2(cur.buffer());
4135                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4136                         md2.push_back(*it);
4137                 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4138                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4139                 return res;
4140         }
4141         LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4142         return docstring();
4143 }
4144
4145 /** Computes the LaTeX export of buf starting from cur and ending len positions
4146  * after cur, if len is positive, or at the paragraph or innermost inset end
4147  * if len is -1.
4148  */
4149 docstring latexifyFromCursor(DocIterator const & cur, int len)
4150 {
4151         /*
4152         LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4153         LYXERR(Debug::FINDVERBOSE, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4154                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4155         */
4156         Buffer const & buf = *cur.buffer();
4157
4158         odocstringstream ods;
4159         otexstream os(ods);
4160         //OutputParams runparams(&buf.params().encoding());
4161         OutputParams runparams(encodings.fromLyXName("utf8"));
4162         runparams.nice = false;
4163         setFindParams(runparams);
4164         if (ignoreFormats.getDeleted()) {
4165                 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4166         }
4167         else {
4168                 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4169         }
4170         if (ignoreFormats.getNonContent()) {
4171                 runparams.find_add_feature(OutputParams::SearchNonOutput);
4172         }
4173
4174         if (cur.inTexted()) {
4175                 // @TODO what about searching beyond/across paragraph breaks ?
4176                 pos_type endpos = cur.paragraph().size();
4177                 if (len != -1 && endpos > cur.pos() + len)
4178                         endpos = cur.pos() + len;
4179                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4180                           string(), cur.pos(), endpos, true);
4181                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4182                 return(ods.str());
4183         } else if (cur.inMathed()) {
4184                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4185                 for (int s = cur.depth() - 1; s >= 0; --s) {
4186                         CursorSlice const & cs = cur[s];
4187                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4188                                 TeXMathStream ws(os);
4189                                 cs.asInsetMath()->asHullInset()->header_write(ws);
4190                                 break;
4191                         }
4192                 }
4193
4194                 CursorSlice const & cs = cur.top();
4195                 MathData md = cs.cell();
4196                 MathData::const_iterator it_end =
4197                                 ((len == -1 || cs.pos() + len > int(md.size()))
4198                                  ? md.end()
4199                                  : md.begin() + cs.pos() + len);
4200                 MathData md2(cur.buffer());
4201                 for (MathData::const_iterator it = md.begin() + cs.pos();
4202                      it != it_end; ++it)
4203                         md2.push_back(*it);
4204
4205                 ods << asString(md2);
4206                 // Retrieve the math environment type, and add '$' or '$]'
4207                 // or others (\end{equation}) accordingly
4208                 for (int s = cur.depth() - 1; s >= 0; --s) {
4209                         CursorSlice const & cs2 = cur[s];
4210                         InsetMath * inset = cs2.asInsetMath();
4211                         if (inset && inset->asHullInset()) {
4212                                 TeXMathStream ws(os);
4213                                 inset->asHullInset()->footer_write(ws);
4214                                 break;
4215                         }
4216                 }
4217                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4218         } else {
4219                 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4220         }
4221         return ods.str();
4222 }
4223
4224 #if defined(ResultsDebug)
4225 // Debugging output
4226 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4227 {
4228         LYXERR0( "from:\t\t\t" << from);
4229         string status;
4230         if (mres.pos_len > 0) {
4231                 // Set in finalize
4232                 status = "FINALSEARCH";
4233         }
4234         else {
4235                 if (mres.match_len > 0) {
4236                         if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4237                                 status = "Good Match";
4238                         else
4239                                 status = "Matched in";
4240                 }
4241                 else
4242                         status = "MissedSearch";
4243         }
4244
4245         LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4246         if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4247                 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4248         if ((mres.pos > 0) || (mres.match_prefix > 0))
4249                 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4250         for (size_t i = 0; i < mres.result.size(); i++)
4251                 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4252 }
4253 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4254 #else
4255 #define displayMres(s, txt, cur)
4256 #endif
4257
4258 /** Finalize an advanced find operation, advancing the cursor to the innermost
4259  ** position that matches, plus computing the length of the matching text to
4260  ** be selected
4261  ** Return the cur.pos() difference between start and end of found match
4262  **/
4263 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4264 {
4265         // Search the foremost position that matches (avoids find of entire math
4266         // inset when match at start of it)
4267         DocIterator old_cur(cur.buffer());
4268         MatchResult mres;
4269         static MatchResult fail = MatchResult();
4270         MatchResult max_match;
4271         // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4272         // Happens with e.g. hyperlinks
4273         // either one sees "http://www.bla.bla" or nothing
4274         // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4275         // and although we search for only 3 chars, we find the whole hyperlink inset
4276         MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4277         if (!match.opt.forward && match.opt.ignoreformat) {
4278                 if (expected.pos > 0)
4279                         return fail;
4280         }
4281         LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4282         if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4283                 // Search for deepest match
4284                 old_cur = cur;
4285                 max_match = expected;
4286                 do {
4287                         size_t d = cur.depth();
4288                         cur.forwardPos();
4289                         if (!cur)
4290                                 break;
4291                         if (cur.depth() < d)
4292                                 break;
4293                         if (cur.depth() == d)
4294                                 break;
4295                         size_t lastd = d;
4296                         while (cur && cur.depth() > lastd) {
4297                                 lastd = cur.depth();
4298                                 mres = match(cur, -1, at_begin);
4299                                 displayMres(mres, "Checking innermost", cur);
4300                                 if (mres.match_len > 0)
4301                                         break;
4302                                 // maybe deeper?
4303                                 cur.forwardPos();
4304                         }
4305                         if (mres.match_len < expected.match_len)
4306                                 break;
4307                         max_match = mres;
4308                         old_cur = cur;;
4309                 } while(1);
4310                 cur = old_cur;
4311         }
4312         else {
4313                 // (expected.match_len <= 0)
4314                 mres = match(cur, -1, MatchStringAdv::MatchFromStart);      /* match valid only if not searching whole words */
4315                 displayMres(mres, "Start with negative match", cur);
4316                 max_match = mres;
4317         }
4318         // Only now we are really at_begin
4319         if ((max_match.match_len <= 0) ||
4320             (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4321                 return fail;
4322         LYXERR(Debug::FINDVERBOSE, "Ok");
4323
4324         // Compute the match length
4325         int len = 1;
4326         if (cur.pos() + len > cur.lastpos())
4327                 return fail;
4328
4329         LASSERT(match.use_regexp, /**/);
4330         {
4331                 int minl = 1;
4332                 int maxl = cur.lastpos() - cur.pos();
4333                 // Greedy behaviour while matching regexps
4334                 while (maxl > minl) {
4335                         MatchResult mres2;
4336                         mres2 = match(cur, len, at_begin);
4337                         displayMres(mres2, "Finalize loop", cur);
4338                         int actual_match_len = mres2.match_len;
4339                         if (actual_match_len >= max_match.match_len) {
4340                                 // actual_match_len > max_match _can_ happen,
4341                                 // if the search area splits
4342                                 // some following word so that the regex
4343                                 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4344                                 // splitted word)
4345                                 // This means, the len value is too big
4346                                 actual_match_len = max_match.match_len;
4347                                 max_match = mres2;
4348                                 max_match.match_len = actual_match_len;
4349                                 maxl = len;
4350                                 if (maxl - minl < 4)
4351                                         len = (maxl + minl)/2;
4352                                 else
4353                                         len = minl + (maxl - minl + 3)/4;
4354                         }
4355                         else {
4356                                 // (actual_match_len < max_match.match_len)
4357                                 minl = len + 1;
4358                                 len = (maxl + minl)/2;
4359                         }
4360                 }
4361                 len = minl;
4362                 old_cur = cur;
4363                 // Search for real start of matched characters
4364                 while (len > 1) {
4365                         MatchResult actual_match;
4366                         do {
4367                                 cur.forwardPos();
4368                         } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4369                         if (cur.depth() < old_cur.depth()) {
4370                                 // Outer inset?
4371                                 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4372                                 break;
4373                         }
4374                         if (cur.pos() != old_cur.pos()) {
4375                                 // OK, forwarded 1 pos in actual inset
4376                                 actual_match = match(cur, len-1, at_begin);
4377                                 if (actual_match.match_len == max_match.match_len) {
4378                                         // Ha, got it! The shorter selection has the same match length
4379                                         len--;
4380                                         old_cur = cur;
4381                                         max_match = actual_match;
4382                                 }
4383                                 else {
4384                                         // OK, the shorter selection matches less chars, revert to previous value
4385                                         cur = old_cur;
4386                                         break;
4387                                 }
4388                         }
4389                         else {
4390                                 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4391                                 actual_match = match(cur, len, at_begin);
4392                                 if (actual_match.match_len == max_match.match_len) {
4393                                         old_cur = cur;
4394                                         max_match = actual_match;
4395                                 }
4396                         }
4397                 }
4398                 if (len == 0)
4399                         return fail;
4400                 else {
4401                         max_match.pos_len = len;
4402                         displayMres(max_match, "SEARCH RESULT", cur)
4403                                         return max_match;
4404                 }
4405         }
4406 }
4407
4408 /// Finds forward
4409 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4410 {
4411         if (!cur)
4412                 return 0;
4413         int repeat = 0;
4414         DocIterator orig_cur;   // to be used if repeat not successful
4415         MatchResult orig_mres;
4416         do {
4417                 orig_cur = cur;
4418                 cur.forwardPos();
4419         } while (cur.depth() > orig_cur.depth());
4420         cur = orig_cur;
4421         while (!theApp()->longOperationCancelled() && cur) {
4422                 //(void) findAdvForwardInnermost(cur);
4423                 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4424                 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4425                 string msg = "Starting";
4426                 if (repeat > 0)
4427                         msg = "Repeated";
4428                 displayMres(mres, msg + " findForwardAdv", cur)
4429                                 int match_len = mres.match_len;
4430                 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4431                         LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4432                         match_len = 0;
4433                 }
4434                 if (match_len <= 0) {
4435                         if (repeat > 0) {
4436                                 repeat--;
4437                         }
4438                         else {
4439                                 // This should exit nested insets, if any, or otherwise undefine the currsor.
4440                                 cur.pos() = cur.lastpos();
4441                         }
4442                         LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4443                         cur.forwardPos();
4444                 }
4445                 else {  // match_len > 0
4446                         // Try to find the begin of searched string
4447                         int increment;
4448                         int firstInvalid = cur.lastpos() - cur.pos();
4449                         {
4450                                 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4451                                 int incrcur = (firstInvalid + 1 )*3/4;
4452                                 if (incrcur < incrmatch)
4453                                         increment = incrcur;
4454                                 else
4455                                         increment = incrmatch;
4456                                 if (increment < 1)
4457                                         increment = 1;
4458                         }
4459                         LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4460                         while (increment > 0) {
4461                                 DocIterator old_cur = cur;
4462                                 if (cur.pos() + increment >= cur.lastpos()) {
4463                                         increment /= 2;
4464                                         continue;
4465                                 }
4466                                 cur.pos() = cur.pos() + increment;
4467                                 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4468                                 displayMres(mres2, "findForwardAdv loop", cur)
4469                                 switch (interpretMatch(mres, mres2)) {
4470                                         case MatchResult::newIsTooFar:
4471                                                 // behind the expected match
4472                                                 firstInvalid = increment;
4473                                                 cur = old_cur;
4474                                                 increment /= 2;
4475                                                 break;
4476                                         case MatchResult::newIsBetter:
4477                                                 // not reached yet, but cur.pos()+increment is better
4478                                                 mres = mres2;
4479                                                 firstInvalid -= increment;
4480                                                 if (increment > firstInvalid*3/4)
4481                                                         increment = firstInvalid*3/4;
4482                                                 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4483                                                         if (increment >= mres2.match_prefix)
4484                                                                 increment = (mres2.match_prefix+1)*3/4;
4485                                                 }
4486                                                 break;
4487                                         default:
4488                                                 // Todo@
4489                                                 // Handle not like MatchResult::newIsTooFar
4490                                                 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4491                                                 firstInvalid--;
4492                                                 increment = increment*3/4;
4493                                                 cur = old_cur;
4494                                                 break;
4495                                 }
4496                         }
4497                         if (mres.match_len > 0) {
4498                                 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4499                                         // The match seems to indicate some deeper level
4500                                         repeat = 2;
4501                                         orig_cur = cur;
4502                                         orig_mres = mres;
4503                                         cur.forwardPos();
4504                                         continue;
4505                                 }
4506                         }
4507                         else if (repeat > 0) {
4508                                 // should never be reached.
4509                                 cur = orig_cur;
4510                                 mres = orig_mres;
4511                         }
4512                         // LYXERR0("Leaving first loop");
4513                         LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4514                         MatchResult found_match = findAdvFinalize(cur, match, mres);
4515                         if (found_match.match_len > 0) {
4516                                 match.FillResults(found_match);
4517                                 return found_match.pos_len;
4518                         }
4519                         else {
4520                                 // try next possible match
4521                                 cur.forwardPos();
4522                                 repeat = false;
4523                                 continue;
4524                         }
4525                 }
4526         }
4527         return 0;
4528 }
4529
4530
4531 /// Find the most backward consecutive match within same paragraph while searching backwards.
4532 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4533 {
4534         DocIterator cur_begin = cur;
4535         cur_begin.pos() = 0;
4536         DocIterator tmp_cur = cur;
4537         MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4538         Inset & inset = cur.inset();
4539         for (; cur != cur_begin; cur.backwardPos()) {
4540                 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4541                 DocIterator new_cur = cur;
4542                 new_cur.backwardPos();
4543                 if (new_cur == cur || &new_cur.inset() != &inset
4544                     || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4545                         break;
4546                 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4547                 if (new_mr.match_len == mr.match_len)
4548                         break;
4549                 mr = new_mr;
4550         }
4551         LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4552         return mr;
4553 }
4554
4555
4556 /// Finds backwards
4557 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4558 {
4559         if (! cur)
4560                 return 0;
4561         // Backup of original position
4562         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4563         if (cur == cur_begin)
4564                 return 0;
4565         cur.backwardPos();
4566         DocIterator cur_orig(cur);
4567         bool pit_changed = false;
4568         do {
4569                 cur.pos() = 0;
4570                 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4571
4572                 if (found_match.match_len > 0) {
4573                         if (pit_changed)
4574                                 cur.pos() = cur.lastpos();
4575                         else
4576                                 cur.pos() = cur_orig.pos();
4577                         LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4578                         DocIterator cur_prev_iter;
4579                         do {
4580                                 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4581                                 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4582                                        << (found_match.match_len > 0) << ", cur: " << cur);
4583                                 if (found_match.match_len > 0) {
4584                                         MatchResult found_mr = findMostBackwards(cur, match, found_match);
4585                                         if (found_mr.pos_len > 0) {
4586                                                 match.FillResults(found_mr);
4587                                                 return found_mr.pos_len;
4588                                         }
4589                                 }
4590
4591                                 // Stop if begin of document reached
4592                                 if (cur == cur_begin)
4593                                         break;
4594                                 cur_prev_iter = cur;
4595                                 cur.backwardPos();
4596                         } while (true);
4597                 }
4598                 if (cur == cur_begin)
4599                         break;
4600                 if (cur.pit() > 0)
4601                         --cur.pit();
4602                 else
4603                         cur.backwardPos();
4604                 pit_changed = true;
4605         } while (!theApp()->longOperationCancelled());
4606         return 0;
4607 }
4608
4609
4610 } // namespace
4611
4612
4613 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4614                                  DocIterator const & cur, int len)
4615 {
4616         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4617                 return docstring();
4618         if (!opt.ignoreformat)
4619                 return latexifyFromCursor(cur, len);
4620         else
4621                 return stringifyFromCursor(cur, len);
4622 }
4623
4624
4625 FindAndReplaceOptions::FindAndReplaceOptions(
4626                 docstring const & _find_buf_name, bool _casesensitive,
4627                 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4628                 docstring const & _repl_buf_name, bool _keep_case,
4629                 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4630         : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4631           forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4632           repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4633 {
4634 }
4635
4636
4637 namespace {
4638
4639
4640 /** Check if 'len' letters following cursor are all non-lowercase */
4641 static bool allNonLowercase(Cursor const & cur, int len)
4642 {
4643         pos_type beg_pos = cur.selectionBegin().pos();
4644         pos_type end_pos = cur.selectionBegin().pos() + len;
4645         if (len > cur.lastpos() + 1 - beg_pos) {
4646                 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4647                 len = cur.lastpos() + 1 - beg_pos;
4648                 end_pos = beg_pos + len;
4649         }
4650         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4651                 if (isLowerCase(cur.paragraph().getChar(pos)))
4652                         return false;
4653         return true;
4654 }
4655
4656
4657 /** Check if first letter is upper case and second one is lower case */
4658 static bool firstUppercase(Cursor const & cur)
4659 {
4660         char_type ch1, ch2;
4661         pos_type pos = cur.selectionBegin().pos();
4662         if (pos >= cur.lastpos() - 1) {
4663                 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4664                 return false;
4665         }
4666         ch1 = cur.paragraph().getChar(pos);
4667         ch2 = cur.paragraph().getChar(pos + 1);
4668         bool result = isUpperCase(ch1) && isLowerCase(ch2);
4669         LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4670                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4671                << ch2 << "(" << char(ch2) << ")"
4672                << ", result=" << result << ", cur=" << cur);
4673         return result;
4674 }
4675
4676
4677 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4678  **
4679  ** \fixme What to do with possible further paragraphs in replace buffer ?
4680  **/
4681 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4682 {
4683         ParagraphList::iterator pit = buffer.paragraphs().begin();
4684         LASSERT(!pit->empty(), /**/);
4685         pos_type right = pos_type(1);
4686         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4687         right = pit->size();
4688         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4689 }
4690 } // namespace
4691
4692 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4693 {
4694         // Should replace the string "$" + std::to_string(matchnum) with replacement
4695         // if the char '$' is not prefixed with odd number of char '\\'
4696         static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4697         string s;
4698         size_t lastpos = 0;
4699         smatch sub;
4700         for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4701                 sub = *it;
4702                 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4703                         continue;
4704                 int num = stoi(sub.str(3), nullptr, 10);
4705                 if (num >= maxmatchnum)
4706                         continue;
4707                 if (lastpos < (size_t) sub.position(2))
4708                         s += t.substr(lastpos, sub.position(2) - lastpos);
4709                 s += replacements[num];
4710                 lastpos = sub.position(2) + sub.length(2);
4711         }
4712         if (lastpos == 0)
4713                 return false;
4714         else if (lastpos < t.length())
4715                 s += t.substr(lastpos, t.length() - lastpos);
4716         t = s;
4717         return true;
4718 }
4719
4720 ///
4721 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4722 {
4723         Cursor & cur = bv->cursor();
4724         if (opt.repl_buf_name.empty()
4725                         || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4726                         || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4727                 return 0;
4728
4729         DocIterator sel_beg = cur.selectionBegin();
4730         DocIterator sel_end = cur.selectionEnd();
4731         if (&sel_beg.inset() != &sel_end.inset()
4732                         || sel_beg.pit() != sel_end.pit()
4733                         || sel_beg.idx() != sel_end.idx())
4734                 return 0;
4735         int sel_len = sel_end.pos() - sel_beg.pos();
4736         LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4737                << ", sel_len: " << sel_len << endl);
4738         if (sel_len == 0)
4739                 return 0;
4740         LASSERT(sel_len > 0, return 0);
4741
4742         if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4743                 return 0;
4744
4745         // Build a copy of the replace buffer, adapted to the KeepCase option
4746         Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4747         ostringstream oss;
4748         repl_buffer_orig.write(oss);
4749         string lyx = oss.str();
4750         if (matchAdv.valid_matches > 0)
4751                 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4752         Buffer repl_buffer(string(), false);
4753         repl_buffer.setInternal(true);
4754         repl_buffer.setUnnamed(true);
4755         LASSERT(repl_buffer.readString(lyx), return 0);
4756         if (opt.keep_case && sel_len >= 2) {
4757                 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4758                 if (cur.inTexted()) {
4759                         if (firstUppercase(cur))
4760                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4761                         else if (allNonLowercase(cur, sel_len))
4762                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4763                 }
4764         }
4765         cap::cutSelection(cur, false);
4766         if (cur.inTexted()) {
4767                 repl_buffer.changeLanguage(
4768                                         repl_buffer.language(),
4769                                         cur.getFont().language());
4770                 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4771                 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4772                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4773                                         repl_buffer.params().documentClassPtr(),
4774                                         repl_buffer.params().authors(),
4775                                         bv->buffer().errorList("Paste"));
4776                 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4777                 sel_len = repl_buffer.paragraphs().begin()->size();
4778         } else if (cur.inMathed()) {
4779                 odocstringstream ods;
4780                 otexstream os(ods);
4781                 // OutputParams runparams(&repl_buffer.params().encoding());
4782                 OutputParams runparams(encodings.fromLyXName("utf8"));
4783                 runparams.nice = false;
4784                 setFindParams(runparams);
4785                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4786                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4787                 docstring repl_latex = ods.str();
4788                 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4789                 string s;
4790                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4791                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4792                 repl_latex = from_utf8(s);
4793                 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4794                 MathData ar(cur.buffer());
4795                 asArray(repl_latex, ar, Parse::NORMAL);
4796                 cur.insert(ar);
4797                 sel_len = ar.size();
4798                 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4799         }
4800         if (cur.pos() >= sel_len)
4801                 cur.pos() -= sel_len;
4802         else
4803                 cur.pos() = 0;
4804         LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4805         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4806         bv->processUpdateFlags(Update::Force);
4807         return 1;
4808 }
4809
4810 static bool isWordChar(char_type c)
4811 {
4812         return isLetterChar(c) || isNumberChar(c);
4813 }
4814
4815 /// Perform a FindAdv operation.
4816 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4817 {
4818         DocIterator cur;
4819         int pos_len = 0;
4820
4821         // e.g., when invoking word-findadv from mini-buffer wither with
4822         //       wrong options syntax or before ever opening advanced F&R pane
4823         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4824                 return false;
4825
4826         try {
4827                 MatchStringAdv matchAdv(bv->buffer(), opt);
4828 #if QTSEARCH
4829                 if (!matchAdv.regexIsValid) {
4830                         bv->message(lyx::from_utf8(matchAdv.regexError));
4831                         return(false);
4832                 }
4833 #endif
4834                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4835                 if (length > 0)
4836                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4837                 num_replaced += findAdvReplace(bv, opt, matchAdv);
4838                 cur = bv->cursor();
4839                 if (opt.forward) {
4840                         if (opt.matchword && cur.pos() > 0) {  // Skip word-characters if we are in the mid of a word
4841                                 if (cur.inTexted()) {
4842                                         Paragraph const & par = cur.paragraph();
4843                                         int len_limit, new_pos;
4844                                         if (cur.lastpos() < par.size())
4845                                                 len_limit = cur.lastpos();
4846                                         else
4847                                                 len_limit = par.size();
4848                                         for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4849                                                 if (!isWordChar(par.getChar(new_pos)))
4850                                                         break;
4851                                         }
4852                                         if (new_pos > cur.pos())
4853                                                 cur.pos() = new_pos;
4854                                 }
4855                                 else if (cur.inMathed()) {
4856                                         // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4857                                         // I am not sure, we should consider the selection
4858                                         bool sel = bv->cursor().selection();
4859                                         if (!sel && cur.pos() < cur.lastpos()) {
4860                                                 CursorSlice const & cs = cur.top();
4861                                                 MathData md = cs.cell();
4862                                                 int len = -1;
4863                                                 MathData::const_iterator it_end = md.end();
4864                                                 MathData md2(cur.buffer());
4865                                                 // Start the check with one character before actual cursor position
4866                                                 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4867                                                     it != it_end; ++it)
4868                                                         md2.push_back(*it);
4869                                                 docstring inp = asString(md2);
4870                                                 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4871                                                         if (!isWordChar(inp[len]))
4872                                                                 break;
4873                                                 }
4874                                                 // len == 0 means previous char was a word separator
4875                                                 // len == 1       search starts with a word separator
4876                                                 // len == 2 ...   we have to skip len -1 chars
4877                                                 if (len > 1)
4878                                                         cur.pos() = cur.pos() + len - 1;
4879                                         }
4880                                 }
4881                                 opt.matchword = false;
4882                         }
4883                         pos_len = findForwardAdv(cur, matchAdv);
4884                 }
4885                 else
4886                         pos_len = findBackwardsAdv(cur, matchAdv);
4887         } catch (exception & ex) {
4888                 bv->message(from_utf8(ex.what()));
4889                 return false;
4890         }
4891
4892         if (pos_len == 0) {
4893                 if (num_replaced > 0) {
4894                         switch (num_replaced)
4895                         {
4896                         case 1:
4897                                 bv->message(_("One match has been replaced."));
4898                                 break;
4899                         case 2:
4900                                 bv->message(_("Two matches have been replaced."));
4901                                 break;
4902                         default:
4903                                 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4904                                 break;
4905                         }
4906                         num_replaced = 0;
4907                 }
4908                 else {
4909                         bv->message(_("Match not found."));
4910                 }
4911                 return false;
4912         }
4913
4914         if (num_replaced > 0)
4915                 bv->message(_("Match has been replaced."));
4916         else
4917                 bv->message(_("Match found."));
4918
4919         if (cur.pos() + pos_len > cur.lastpos()) {
4920                 // Prevent crash in bv->putSelectionAt()
4921                 // Should never happen, maybe LASSERT() here?
4922                 pos_len = cur.lastpos() - cur.pos();
4923         }
4924         LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4925         bv->putSelectionAt(cur, pos_len, !opt.forward);
4926
4927         return true;
4928 }
4929
4930
4931 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4932 {
4933         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4934            << opt.casesensitive << ' '
4935            << opt.matchword << ' '
4936            << opt.forward << ' '
4937            << opt.expandmacros << ' '
4938            << opt.ignoreformat << ' '
4939            << opt.replace_all << ' '
4940            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4941            << opt.keep_case << ' '
4942            << int(opt.scope) << ' '
4943            << int(opt.restr);
4944
4945         LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4946
4947         return os;
4948 }
4949
4950
4951 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4952 {
4953         // LYXERR(Debug::FINDVERBOSE, "parsing");
4954         string s;
4955         string line;
4956         getline(is, line);
4957         while (line != "EOSS") {
4958                 if (! s.empty())
4959                         s = s + "\n";
4960                 s = s + line;
4961                 if (is.eof())   // Tolerate malformed request
4962                         break;
4963                 getline(is, line);
4964         }
4965         // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4966         opt.find_buf_name = from_utf8(s);
4967         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4968         is.get();       // Waste space before replace string
4969         s = "";
4970         getline(is, line);
4971         while (line != "EOSS") {
4972                 if (! s.empty())
4973                         s = s + "\n";
4974                 s = s + line;
4975                 if (is.eof())   // Tolerate malformed request
4976                         break;
4977                 getline(is, line);
4978         }
4979         // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
4980         opt.repl_buf_name = from_utf8(s);
4981         is >> opt.keep_case;
4982         int i;
4983         is >> i;
4984         opt.scope = FindAndReplaceOptions::SearchScope(i);
4985         is >> i;
4986         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4987
4988         /*
4989         LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4990                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4991                << opt.scope << ' ' << opt.restr);
4992         */
4993         return is;
4994 }
4995
4996 } // namespace lyx