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