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