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