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