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