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