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