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