]> git.lyx.org Git - features.git/blob - src/lyxfind.cpp
FindAdv: Polishing
[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 "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
53
54 #include "support/regex.h"
55 #include <map>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 namespace lyx {
61
62 namespace {
63
64 bool parse_bool(docstring & howto)
65 {
66         if (howto.empty())
67                 return false;
68         docstring var;
69         howto = split(howto, var, ' ');
70         return var == "1";
71 }
72
73
74 class MatchString : public binary_function<Paragraph, pos_type, int>
75 {
76 public:
77         MatchString(docstring const & str, bool cs, bool mw)
78                 : str(str), case_sens(cs), whole_words(mw)
79         {}
80
81         // returns true if the specified string is at the specified position
82         // del specifies whether deleted strings in ct mode will be considered
83         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
84         {
85                 return par.find(str, case_sens, whole_words, pos, del);
86         }
87
88 private:
89         // search string
90         docstring str;
91         // case sensitive
92         bool case_sens;
93         // match whole words only
94         bool whole_words;
95 };
96
97
98 int findForward(DocIterator & cur, MatchString const & match,
99                 bool find_del = true)
100 {
101         for (; cur; cur.forwardChar())
102                 if (cur.inTexted()) {
103                         int len = match(cur.paragraph(), cur.pos(), find_del);
104                         if (len > 0)
105                                 return len;
106                 }
107         return 0;
108 }
109
110
111 int findBackwards(DocIterator & cur, MatchString const & match,
112                   bool find_del = true)
113 {
114         while (cur) {
115                 cur.backwardChar();
116                 if (cur.inTexted()) {
117                         int len = match(cur.paragraph(), cur.pos(), find_del);
118                         if (len > 0)
119                                 return len;
120                 }
121         }
122         return 0;
123 }
124
125
126 bool searchAllowed(docstring const & str)
127 {
128         if (str.empty()) {
129                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
130                 return false;
131         }
132         return true;
133 }
134
135
136 bool findOne(BufferView * bv, docstring const & searchstr,
137              bool case_sens, bool whole, bool forward,
138              bool find_del = true, bool check_wrap = false)
139 {
140         if (!searchAllowed(searchstr))
141                 return false;
142
143         DocIterator cur = forward
144                 ? bv->cursor().selectionEnd()
145                 : bv->cursor().selectionBegin();
146
147         MatchString const match(searchstr, case_sens, whole);
148
149         int match_len = forward
150                 ? findForward(cur, match, find_del)
151                 : findBackwards(cur, match, find_del);
152
153         if (match_len > 0)
154                 bv->putSelectionAt(cur, match_len, !forward);
155         else if (check_wrap) {
156                 DocIterator cur_orig(bv->cursor());
157                 docstring q;
158                 if (forward)
159                         q = _("End of file reached while searching forward.\n"
160                           "Continue searching from the beginning?");
161                 else
162                         q = _("Beginning of file reached while searching backward.\n"
163                           "Continue searching from the end?");
164                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
165                         q, 0, 1, _("&Yes"), _("&No"));
166                 if (wrap_answer == 0) {
167                         if (forward) {
168                                 bv->cursor().clear();
169                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
170                         } else {
171                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
172                                 bv->cursor().backwardPos();
173                         }
174                         bv->clearSelection();
175                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
176                                 return true;
177                 }
178                 bv->cursor().setCursor(cur_orig);
179                 return false;
180         }
181
182         return match_len > 0;
183 }
184
185
186 int replaceAll(BufferView * bv,
187                docstring const & searchstr, docstring const & replacestr,
188                bool case_sens, bool whole)
189 {
190         Buffer & buf = bv->buffer();
191
192         if (!searchAllowed(searchstr) || buf.isReadonly())
193                 return 0;
194
195         DocIterator cur_orig(bv->cursor());
196
197         MatchString const match(searchstr, case_sens, whole);
198         int num = 0;
199
200         int const rsize = replacestr.size();
201         int const ssize = searchstr.size();
202
203         Cursor cur(*bv);
204         cur.setCursor(doc_iterator_begin(&buf));
205         int match_len = findForward(cur, match, false);
206         while (match_len > 0) {
207                 // Backup current cursor position and font.
208                 pos_type const pos = cur.pos();
209                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
210                 cur.recordUndo();
211                 int striked = ssize -
212                         cur.paragraph().eraseChars(pos, pos + match_len,
213                                                    buf.params().track_changes);
214                 cur.paragraph().insert(pos, replacestr, font,
215                                        Change(buf.params().track_changes
216                                               ? Change::INSERTED
217                                               : Change::UNCHANGED));
218                 for (int i = 0; i < rsize + striked; ++i)
219                         cur.forwardChar();
220                 ++num;
221                 match_len = findForward(cur, match, false);
222         }
223
224         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
225
226         cur_orig.fixIfBroken();
227         bv->setCursor(cur_orig);
228
229         return num;
230 }
231
232
233 // the idea here is that we are going to replace the string that
234 // is selected IF it is the search string.
235 // if there is a selection, but it is not the search string, then
236 // we basically ignore it. (FIXME We ought to replace only within
237 // the selection.)
238 // if there is no selection, then:
239 //  (i) if some search string has been provided, then we find it.
240 //      (think of how the dialog works when you hit "replace" the
241 //      first time.)
242 // (ii) if no search string has been provided, then we treat the
243 //      word the cursor is in as the search string. (why? i have no
244 //      idea.) but this only works in text?
245 //
246 // returns the number of replacements made (one, if any) and
247 // whether anything at all was done.
248 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
249                            docstring const & replacestr, bool case_sens,
250                            bool whole, bool forward, bool findnext)
251 {
252         Cursor & cur = bv->cursor();
253         bool found = false;
254         if (!cur.selection()) {
255                 // no selection, non-empty search string: find it
256                 if (!searchstr.empty()) {
257                         found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
258                         return make_pair(found, 0);
259                 }
260                 // empty search string
261                 if (!cur.inTexted())
262                         // bail in math
263                         return make_pair(false, 0);
264                 // select current word and treat it as the search string.
265                 // This causes a minor bug as undo will restore this selection,
266                 // which the user did not create (#8986).
267                 cur.innerText()->selectWord(cur, WHOLE_WORD);
268                 searchstr = cur.selectionAsString(false);
269         }
270
271         // if we still don't have a search string, report the error
272         // and abort.
273         if (!searchAllowed(searchstr))
274                 return make_pair(false, 0);
275
276         bool have_selection = cur.selection();
277         docstring const selected = cur.selectionAsString(false);
278         bool match =
279                 case_sens
280                 ? searchstr == selected
281                 : compare_no_case(searchstr, selected) == 0;
282
283         // no selection or current selection is not search word:
284         // just find the search word
285         if (!have_selection || !match) {
286                 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
287                 return make_pair(found, 0);
288         }
289
290         // we're now actually ready to replace. if the buffer is
291         // read-only, we can't, though.
292         if (bv->buffer().isReadonly())
293                 return make_pair(false, 0);
294
295         cap::replaceSelectionWithString(cur, replacestr);
296         if (forward) {
297                 cur.pos() += replacestr.length();
298                 LASSERT(cur.pos() <= cur.lastpos(),
299                         cur.pos() = cur.lastpos());
300         }
301         if (findnext)
302                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
303
304         return make_pair(true, 1);
305 }
306
307 } // namespace
308
309
310 docstring const find2string(docstring const & search,
311                             bool casesensitive, bool matchword, bool forward)
312 {
313         odocstringstream ss;
314         ss << search << '\n'
315            << int(casesensitive) << ' '
316            << int(matchword) << ' '
317            << int(forward);
318         return ss.str();
319 }
320
321
322 docstring const replace2string(docstring const & replace,
323                                docstring const & search,
324                                bool casesensitive, bool matchword,
325                                bool all, bool forward, bool findnext)
326 {
327         odocstringstream ss;
328         ss << replace << '\n'
329            << search << '\n'
330            << int(casesensitive) << ' '
331            << int(matchword) << ' '
332            << int(all) << ' '
333            << int(forward) << ' '
334            << int(findnext);
335         return ss.str();
336 }
337
338
339 bool lyxfind(BufferView * bv, FuncRequest const & ev)
340 {
341         if (!bv || ev.action() != LFUN_WORD_FIND)
342                 return false;
343
344         //lyxerr << "find called, cmd: " << ev << endl;
345
346         // data is of the form
347         // "<search>
348         //  <casesensitive> <matchword> <forward>"
349         docstring search;
350         docstring howto = split(ev.argument(), search, '\n');
351
352         bool casesensitive = parse_bool(howto);
353         bool matchword     = parse_bool(howto);
354         bool forward       = parse_bool(howto);
355
356         return findOne(bv, search, casesensitive, matchword, forward, true, true);
357 }
358
359
360 bool lyxreplace(BufferView * bv,
361                 FuncRequest const & ev, bool has_deleted)
362 {
363         if (!bv || ev.action() != LFUN_WORD_REPLACE)
364                 return false;
365
366         // data is of the form
367         // "<search>
368         //  <replace>
369         //  <casesensitive> <matchword> <all> <forward> <findnext>"
370         docstring search;
371         docstring rplc;
372         docstring howto = split(ev.argument(), rplc, '\n');
373         howto = split(howto, search, '\n');
374
375         bool casesensitive = parse_bool(howto);
376         bool matchword     = parse_bool(howto);
377         bool all           = parse_bool(howto);
378         bool forward       = parse_bool(howto);
379         bool findnext      = howto.empty() ? true : parse_bool(howto);
380
381         bool update = false;
382
383         if (!has_deleted) {
384                 int replace_count = 0;
385                 if (all) {
386                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
387                         update = replace_count > 0;
388                 } else {
389                         pair<bool, int> rv =
390                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
391                         update = rv.first;
392                         replace_count = rv.second;
393                 }
394
395                 Buffer const & buf = bv->buffer();
396                 if (!update) {
397                         // emit message signal.
398                         buf.message(_("String not found."));
399                 } else {
400                         if (replace_count == 0) {
401                                 buf.message(_("String found."));
402                         } else if (replace_count == 1) {
403                                 buf.message(_("String has been replaced."));
404                         } else {
405                                 docstring const str =
406                                         bformat(_("%1$d strings have been replaced."), replace_count);
407                                 buf.message(str);
408                         }
409                 }
410         } else if (findnext) {
411                 // if we have deleted characters, we do not replace at all, but
412                 // rather search for the next occurence
413                 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
414                         update = true;
415                 else
416                         bv->message(_("String not found."));
417         }
418         return update;
419 }
420
421
422 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
423 {
424         for (; cur; cur.forwardPos())
425                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
426                         return true;
427
428         if (check_wrap) {
429                 DocIterator cur_orig(bv->cursor());
430                 docstring q = _("End of file reached while searching forward.\n"
431                           "Continue searching from the beginning?");
432                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
433                         q, 0, 1, _("&Yes"), _("&No"));
434                 if (wrap_answer == 0) {
435                         bv->cursor().clear();
436                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
437                         bv->clearSelection();
438                         cur.setCursor(bv->cursor().selectionBegin());
439                         if (findNextChange(bv, cur, false))
440                                 return true;
441                 }
442                 bv->cursor().setCursor(cur_orig);
443         }
444
445         return false;
446 }
447
448
449 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
450 {
451         for (cur.backwardPos(); cur; cur.backwardPos()) {
452                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
453                         return true;
454         }
455
456         if (check_wrap) {
457                 DocIterator cur_orig(bv->cursor());
458                 docstring q = _("Beginning of file reached while searching backward.\n"
459                           "Continue searching from the end?");
460                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
461                         q, 0, 1, _("&Yes"), _("&No"));
462                 if (wrap_answer == 0) {
463                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
464                         bv->cursor().backwardPos();
465                         bv->clearSelection();
466                         cur.setCursor(bv->cursor().selectionBegin());
467                         if (findPreviousChange(bv, cur, false))
468                                 return true;
469                 }
470                 bv->cursor().setCursor(cur_orig);
471         }
472
473         return false;
474 }
475
476
477 bool selectChange(Cursor & cur, bool forward)
478 {
479         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
480                 return false;
481         Change ch = cur.paragraph().lookupChange(cur.pos());
482
483         CursorSlice tip1 = cur.top();
484         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
485                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
486                 if (!ch2.isSimilarTo(ch))
487                         break;
488         }
489         CursorSlice tip2 = cur.top();
490         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
491                 tip2.backwardPos();
492                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
493                 if (!ch2.isSimilarTo(ch)) {
494                         // take a step forward to correctly set the selection
495                         tip2.forwardPos();
496                         break;
497                 }
498         }
499         if (forward)
500                 swap(tip1, tip2);
501         cur.top() = tip1;
502         cur.bv().mouseSetCursor(cur, false);
503         cur.top() = tip2;
504         cur.bv().mouseSetCursor(cur, true);
505         return true;
506 }
507
508
509 namespace {
510
511
512 bool findChange(BufferView * bv, bool forward)
513 {
514         Cursor cur(*bv);
515         cur.setCursor(forward ? bv->cursor().selectionEnd()
516                       : bv->cursor().selectionBegin());
517         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
518         return selectChange(cur, forward);
519 }
520
521 } // namespace
522
523 bool findNextChange(BufferView * bv)
524 {
525         return findChange(bv, true);
526 }
527
528
529 bool findPreviousChange(BufferView * bv)
530 {
531         return findChange(bv, false);
532 }
533
534
535
536 namespace {
537
538 typedef vector<pair<string, string> > Escapes;
539
540 /// A map of symbols and their escaped equivalent needed within a regex.
541 /// @note Beware of order
542 Escapes const & get_regexp_escapes()
543 {
544         typedef std::pair<std::string, std::string> P;
545
546         static Escapes escape_map;
547         if (escape_map.empty()) {
548                 escape_map.push_back(P("$", "_x_$"));
549                 escape_map.push_back(P("{", "_x_{"));
550                 escape_map.push_back(P("}", "_x_}"));
551                 escape_map.push_back(P("[", "_x_["));
552                 escape_map.push_back(P("]", "_x_]"));
553                 escape_map.push_back(P("(", "_x_("));
554                 escape_map.push_back(P(")", "_x_)"));
555                 escape_map.push_back(P("+", "_x_+"));
556                 escape_map.push_back(P("*", "_x_*"));
557                 escape_map.push_back(P(".", "_x_."));
558                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
559                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
560                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
561                 escape_map.push_back(P("_x_", "\\"));
562         }
563         return escape_map;
564 }
565
566 /// A map of lyx escaped strings and their unescaped equivalent.
567 Escapes const & get_lyx_unescapes()
568 {
569         typedef std::pair<std::string, std::string> P;
570
571         static Escapes escape_map;
572         if (escape_map.empty()) {
573                 escape_map.push_back(P("\\%", "%"));
574                 escape_map.push_back(P("\\mathcircumflex ", "^"));
575                 escape_map.push_back(P("\\mathcircumflex", "^"));
576                 escape_map.push_back(P("\\backslash ", "\\"));
577                 escape_map.push_back(P("\\backslash", "\\"));
578                 escape_map.push_back(P("\\\\{", "_x_<"));
579                 escape_map.push_back(P("\\\\}", "_x_>"));
580                 escape_map.push_back(P("\\sim ", "~"));
581                 escape_map.push_back(P("\\sim", "~"));
582         }
583         return escape_map;
584 }
585
586 /// A map of escapes turning a regexp matching text to one matching latex.
587 Escapes const & get_regexp_latex_escapes()
588 {
589         typedef std::pair<std::string, std::string> P;
590
591         static Escapes escape_map;
592         if (escape_map.empty()) {
593                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
594                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
595                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
596                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
597                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
598                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
599                 escape_map.push_back(P("%", "\\\\\\%"));
600                 escape_map.push_back(P("#", "\\\\#"));
601         }
602         return escape_map;
603 }
604
605 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
606  ** the found occurrence were escaped.
607  **/
608 string apply_escapes(string s, Escapes const & escape_map)
609 {
610         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
611         Escapes::const_iterator it;
612         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
613 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
614                 unsigned int pos = 0;
615                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
616                         s.replace(pos, it->first.length(), it->second);
617                         LYXERR(Debug::FIND, "After escape: " << s);
618                         pos += it->second.length();
619 //                      LYXERR(Debug::FIND, "pos: " << pos);
620                 }
621         }
622         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
623         return s;
624 }
625
626
627 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
628 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
629 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
630 string escape_for_regex(string s, bool match_latex)
631 {
632         size_t pos = 0;
633         while (pos < s.size()) {
634                 size_t new_pos = s.find("\\regexp{", pos);
635                 if (new_pos == string::npos)
636                         new_pos = s.size();
637                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
638                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
639                 LYXERR(Debug::FIND, "t [lyx]: " << t);
640                 t = apply_escapes(t, get_regexp_escapes());
641                 LYXERR(Debug::FIND, "t [rxp]: " << t);
642                 s.replace(pos, new_pos - pos, t);
643                 new_pos = pos + t.size();
644                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
645                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
646                 if (new_pos == s.size())
647                         break;
648                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
649                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
650                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
651                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
652                 LYXERR(Debug::FIND, "t in regexp      : " << t);
653                 t = apply_escapes(t, get_lyx_unescapes());
654                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
655                 if (match_latex) {
656                         t = apply_escapes(t, get_regexp_latex_escapes());
657                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
658                 }
659                 if (end_pos == s.size()) {
660                         s.replace(new_pos, end_pos - new_pos, t);
661                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
662                         break;
663                 }
664                 s.replace(new_pos, end_pos + 13 - new_pos, t);
665                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
666                 pos = new_pos + t.size();
667                 LYXERR(Debug::FIND, "pos: " << pos);
668         }
669         return s;
670 }
671
672
673 /// Wrapper for lyx::regex_replace with simpler interface
674 bool regex_replace(string const & s, string & t, string const & searchstr,
675                    string const & replacestr)
676 {
677         lyx::regex e(searchstr, regex_constants::ECMAScript);
678         ostringstream oss;
679         ostream_iterator<char, char> it(oss);
680         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
681         // tolerate t and s be references to the same variable
682         bool rv = (s != oss.str());
683         t = oss.str();
684         return rv;
685 }
686
687
688 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
689  **
690  ** Verify that closed braces exactly match open braces. This avoids that, for example,
691  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
692  **
693  ** @param unmatched
694  ** Number of open braces that must remain open at the end for the verification to succeed.
695  **/
696 bool braces_match(string::const_iterator const & beg,
697                   string::const_iterator const & end,
698                   int unmatched = 0)
699 {
700         int open_pars = 0;
701         string::const_iterator it = beg;
702         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
703         for (; it != end; ++it) {
704                 // Skip escaped braces in the count
705                 if (*it == '\\') {
706                         ++it;
707                         if (it == end)
708                                 break;
709                 } else if (*it == '{') {
710                         ++open_pars;
711                 } else if (*it == '}') {
712                         if (open_pars == 0) {
713                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
714                                 return false;
715                         } else
716                                 --open_pars;
717                 }
718         }
719         if (open_pars != unmatched) {
720                 LYXERR(Debug::FIND, "Found " << open_pars
721                        << " instead of " << unmatched
722                        << " unmatched open braces at the end of count");
723                 return false;
724         }
725         LYXERR(Debug::FIND, "Braces match as expected");
726         return true;
727 }
728
729
730 /** The class performing a match between a position in the document and the FindAdvOptions.
731  **/
732 class MatchStringAdv {
733 public:
734         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
735
736         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
737          ** constructor as opt.search, under the opt.* options settings.
738          **
739          ** @param at_begin
740          **     If set, then match is searched only against beginning of text starting at cur.
741          **     If unset, then match is searched anywhere in text starting at cur.
742          **
743          ** @return
744          ** The length of the matching text, or zero if no match was found.
745          **/
746         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
747
748 public:
749         /// buffer
750         lyx::Buffer * p_buf;
751         /// first buffer on which search was started
752         lyx::Buffer * const p_first_buf;
753         /// options
754         FindAndReplaceOptions const & opt;
755
756 private:
757         /// Auxiliary find method (does not account for opt.matchword)
758         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
759
760         /** Normalize a stringified or latexified LyX paragraph.
761          **
762          ** Normalize means:
763          ** <ul>
764          **   <li>if search is not casesensitive, then lowercase the string;
765          **   <li>remove any newline at begin or end of the string;
766          **   <li>replace any newline in the middle of the string with a simple space;
767          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
768          ** </ul>
769          **
770          ** @todo Normalization should also expand macros, if the corresponding
771          ** search option was checked.
772          **/
773         string normalize(docstring const & s, bool hack_braces) const;
774         // normalized string to search
775         string par_as_string;
776         // regular expression to use for searching
777         lyx::regex regexp;
778         // same as regexp, but prefixed with a ".*"
779         lyx::regex regexp2;
780         // leading format material as string
781         string lead_as_string;
782         // par_as_string after removal of lead_as_string
783         string par_as_string_nolead;
784         // unmatched open braces in the search string/regexp
785         int open_braces;
786         // number of (.*?) subexpressions added at end of search regexp for closing
787         // environments, math mode, styles, etc...
788         int close_wildcards;
789         // Are we searching with regular expressions ?
790         bool use_regexp;
791 };
792
793
794 static docstring buffer_to_latex(Buffer & buffer)
795 {
796         OutputParams runparams(&buffer.params().encoding());
797         odocstringstream ods;
798         otexstream os(ods);
799         runparams.nice = true;
800         runparams.flavor = OutputParams::LATEX;
801         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
802         // No side effect of file copying and image conversion
803         runparams.dryrun = true;
804         runparams.for_search = true;
805         pit_type const endpit = buffer.paragraphs().size();
806         for (pit_type pit = 0; pit != endpit; ++pit) {
807                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
808                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
809         }
810         return ods.str();
811 }
812
813
814 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
815 {
816         docstring str;
817         if (!opt.ignoreformat) {
818                 str = buffer_to_latex(buffer);
819         } else {
820                 OutputParams runparams(&buffer.params().encoding());
821                 runparams.nice = true;
822                 runparams.flavor = OutputParams::LATEX;
823                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
824                 runparams.dryrun = true;
825                 runparams.for_search = true;
826                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
827                         Paragraph const & par = buffer.paragraphs().at(pit);
828                         LYXERR(Debug::FIND, "Adding to search string: '"
829                                << par.asString(pos_type(0), par.size(),
830                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
831                                                &runparams)
832                                << "'");
833                         str += par.asString(pos_type(0), par.size(),
834                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
835                                             &runparams);
836                 }
837         }
838         return str;
839 }
840
841
842 /// Return separation pos between the leading material and the rest
843 static size_t identifyLeading(string const & s)
844 {
845         string t = s;
846         // @TODO Support \item[text]
847         // Kornel: Added textsl, textsf, textit, texttt and noun
848         // + allow to search for colored text too
849         while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|minisec|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
850                || regex_replace(t, t, REGEX_BOS "\\$", "")
851                || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
852                || regex_replace(t, t, REGEX_BOS " ?\\\\item\\{[a-z]+\\}", "")
853                || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
854                ;
855         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
856         return s.find(t);
857 }
858
859 /*
860  * Given a latexified string, retrieve some handled features
861  * The features of the regex will later be compared with the features
862  * of the searched text. If the regex features are not a
863  * subset of the analized, then, in not format ignoring search
864  * we can early stop the search in the relevant inset.
865  */
866 typedef map<string, bool> Features;
867
868 static Features identifyFeatures(string const & s)
869 {
870         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
871         static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage|item)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)$");
872         smatch sub;
873         bool displ = true;
874         Features info;
875
876         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
877                 sub = *it;
878                 if (displ) {
879                         if (sub.str(1).compare("regexp") == 0) {
880                                 displ = false;
881                                 continue;
882                         }
883                         string token = sub.str(1);
884                         smatch sub2;
885                         if (regex_match(token, sub2, valid)) {
886                                 info[token] = true;
887                         }
888                         else {
889                                 // ignore
890                         }
891                 }
892                 else {
893                         if (sub.str(1).compare("endregexp") == 0) {
894                                 displ = true;
895                                 continue;
896                         }
897                 }
898         }
899         return(info);
900 }
901
902 /*
903  * defines values features of a key "\\[a-z]+{"
904  */
905 class KeyInfo {
906  public:
907   enum KeyType {
908     isChar,
909     isSectioning,
910     isMain,                             /* for \\foreignlanguage */
911     isRegex,
912     isMath,
913     isStandard,
914     isSize,
915     invalid,
916     doRemove,
917     isList,
918     isIgnored                           /* to be ignored by creating infos */
919   };
920  KeyInfo()
921    : keytype(invalid),
922     head(""),
923     parenthesiscount(1),
924     disabled(false),
925     used(false)
926   {};
927  KeyInfo(KeyType type, int parcount, bool disable)
928    : keytype(type),
929     parenthesiscount(parcount),
930     disabled(disable),
931     used(false) {};
932   KeyType keytype;
933   string head;
934   int _tokensize;
935   int _tokenstart;
936   int _dataStart;
937   int _dataEnd;
938   int parenthesiscount;
939   bool disabled;
940   bool used;                            /* by pattern */
941 };
942
943 class Border {
944  public:
945  Border(int l=0, int u=0) : low(l), upper(u) {};
946   int low;
947   int upper;
948 };
949
950 #define MAXOPENED 30
951 class Intervall {
952   bool isPatternString;
953  public:
954  Intervall(bool isPattern) : isPatternString(isPattern), ignoreidx(-1), actualdeptindex(0) { depts[0] = 0;};
955   string par;
956   int ignoreidx;
957   int depts[MAXOPENED];
958   int closes[MAXOPENED];
959   int actualdeptindex;
960   Border borders[2*MAXOPENED];
961   // int previousNotIgnored(int);
962   int nextNotIgnored(int);
963   void handleOpenP(int i);
964   void handleCloseP(int i, bool closingAllowed);
965   void resetOpenedP(int openPos);
966   void addIntervall(int upper);
967   void addIntervall(int low, int upper); /* if explicit */
968   void setForDefaultLang(int upTo);
969   int findclosing(int start, int end, char up, char down);
970   void handleParentheses(int lastpos, bool closingAllowed);
971   void output(ostringstream &os, int lastpos);
972   // string show(int lastpos);
973 };
974
975 void Intervall::setForDefaultLang(int upTo)
976 {
977   // Enable the use of first token again
978   if (ignoreidx >= 0) {
979     if (borders[0].low < upTo)
980       borders[0].low = upTo;
981     if (borders[0].upper < upTo)
982       borders[0].upper = upTo;
983   }
984 }
985
986 static void checkDepthIndex(int val)
987 {
988   static int maxdepthidx = MAXOPENED-2;
989   if (val > maxdepthidx) {
990     maxdepthidx = val;
991     LYXERR0("maxdepthidx now " << val);
992   }
993 }
994
995 static void checkIgnoreIdx(int val)
996 {
997   static int maxignoreidx = 2*MAXOPENED - 4;
998   if (val > maxignoreidx) {
999     maxignoreidx = val;
1000     LYXERR0("maxignoreidx now " << val);
1001   }
1002 }
1003
1004 /*
1005  * Expand the region of ignored parts of the input latex string
1006  * The region is only relevant in output()
1007  */
1008 void Intervall::addIntervall(int low, int upper)
1009 {
1010   int idx;
1011   if (low == upper) return;
1012   for (idx = ignoreidx+1; idx > 0; --idx) {
1013     if (low > borders[idx-1].upper) {
1014       break;
1015     }
1016   }
1017   Border br(low, upper);
1018   if (idx > ignoreidx) {
1019     borders[idx] = br;
1020     ignoreidx = idx;
1021     checkIgnoreIdx(ignoreidx);
1022     return;
1023   }
1024   else {
1025     // Expand only if one of the new bound is inside the interwall
1026     // We know here that br.low > borders[idx-1].upper
1027     if (br.upper < borders[idx].low) {
1028       // We have to insert at this pos
1029       for (int i = ignoreidx+1; i > idx; --i) {
1030         borders[i] = borders[i-1];
1031       }
1032       borders[idx] = br;
1033       ignoreidx += 1;
1034       checkIgnoreIdx(ignoreidx);
1035       return;
1036     }
1037     // Here we know, that we are overlapping
1038     if (br.low > borders[idx].low)
1039       br.low = borders[idx].low;
1040     // check what has to be concatenated
1041     int count = 0;
1042     for (int i = idx; i <= ignoreidx; i++) {
1043       if (br.upper >= borders[i].low) {
1044         count++;
1045         if (br.upper < borders[i].upper)
1046           br.upper = borders[i].upper;
1047       }
1048       else {
1049         break;
1050       }
1051     }
1052     // count should be >= 1 here
1053     borders[idx] = br;
1054     if (count > 1) {
1055       for (int i = idx + count; i <= ignoreidx; i++) {
1056         borders[i-count+1] = borders[i];
1057       }
1058       ignoreidx -= count - 1;
1059       return;
1060     }
1061   }
1062 }
1063
1064 void Intervall::handleOpenP(int i)
1065 {
1066   actualdeptindex++;
1067   depts[actualdeptindex] = i+1;
1068   closes[actualdeptindex] = -1;
1069   checkDepthIndex(actualdeptindex);
1070 }
1071
1072 void Intervall::handleCloseP(int i, bool closingAllowed)
1073 {
1074   if (actualdeptindex <= 0) {
1075     if (! closingAllowed)
1076       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should not happen, but the latex input may be wrong */
1077     // if we are at the very end
1078     addIntervall(i, i+1);
1079   }
1080   else {
1081     closes[actualdeptindex] = i+1;
1082     actualdeptindex--;
1083   }
1084 }
1085
1086 void Intervall::resetOpenedP(int openPos)
1087 {
1088   // Used as initializer for foreignlanguage entry
1089   actualdeptindex = 1;
1090   depts[1] = openPos+1;
1091   closes[1] = -1;
1092 }
1093
1094 #if 0
1095 int Intervall::previousNotIgnored(int start)
1096 {
1097     int idx = 0;                          /* int intervalls */
1098     for (idx = ignoreidx; idx >= 0; --idx) {
1099       if (start > borders[idx].upper)
1100         return start;
1101       if (start >= borders[idx].low)
1102         start = borders[idx].low-1;
1103     }
1104     return start;
1105 }
1106 #endif
1107
1108 int Intervall::nextNotIgnored(int start)
1109 {
1110     int idx = 0;                          /* int intervalls */
1111     for (idx = 0; idx <= ignoreidx; idx++) {
1112       if (start < borders[idx].low)
1113         return start;
1114       if (start < borders[idx].upper)
1115         start = borders[idx].upper;
1116     }
1117     return start;
1118 }
1119
1120 typedef map<string, KeyInfo> KeysMap;
1121 typedef vector< KeyInfo> Entries;
1122 static KeysMap keys = map<string, KeyInfo>();
1123
1124 class IgnoreFormats {
1125   static bool ignoreFamily;
1126   static bool ignoreSeries;
1127   static bool ignoreShape;
1128   static bool ignoreUnderline;
1129   static bool ignoreMarkUp;
1130   static bool ignoreStrikeOut;
1131   static bool ignoreSectioning;
1132   static bool ignoreFrontMatter;
1133   static bool ignoreColor;
1134   static bool ignoreLanguage;
1135  public:
1136   bool getFamily() { return ignoreFamily; };
1137   bool getSeries() { return ignoreSeries; };
1138   bool getShape() { return ignoreShape; };
1139   bool getUnderline() { return ignoreUnderline; };
1140   bool getMarkUp() { return ignoreMarkUp; };
1141   bool getStrikeOut() { return ignoreStrikeOut; };
1142   bool getSectioning() { return ignoreSectioning; };
1143   bool getFrontMatter() { return ignoreFrontMatter; };
1144   bool getColor() { return ignoreColor; };
1145   bool getLanguage() { return ignoreLanguage; };
1146
1147   void setIgnoreFormat(string type, bool value);
1148 };
1149
1150 bool IgnoreFormats::ignoreFamily     = false;
1151 bool IgnoreFormats::ignoreSeries     = false;
1152 bool IgnoreFormats::ignoreShape      = false;
1153 bool IgnoreFormats::ignoreUnderline  = false;
1154 bool IgnoreFormats::ignoreMarkUp     = false;
1155 bool IgnoreFormats::ignoreStrikeOut  = false;
1156 bool IgnoreFormats::ignoreSectioning = false;
1157 bool IgnoreFormats::ignoreFrontMatter= true;
1158 bool IgnoreFormats::ignoreColor      = false;
1159 bool IgnoreFormats::ignoreLanguage   = false;
1160
1161 void IgnoreFormats::setIgnoreFormat(string type, bool value)
1162 {
1163   if (type == "color") {
1164     ignoreColor = value;
1165   }
1166   else if (type == "language") {
1167     ignoreLanguage = value;
1168   }
1169   else if (type == "sectioning") {
1170     ignoreSectioning = value;
1171     ignoreFrontMatter = value;
1172   }
1173   else if (type == "font") {
1174     ignoreSeries = value;
1175     ignoreShape = value;
1176     ignoreFamily = value;
1177   }
1178   else if (type == "series") {
1179     ignoreSeries = value;
1180   }
1181   else if (type == "shape") {
1182     ignoreShape = value;
1183   }
1184   else if (type == "family") {
1185     ignoreFamily = value;
1186   }
1187   else if (type == "markup") {
1188     ignoreMarkUp = value;
1189   }
1190   else if (type == "underline") {
1191     ignoreUnderline = value;
1192   }
1193   else if (type == "strike") {
1194     ignoreStrikeOut = value;
1195   }
1196 }
1197 #pragma GCC diagnostic push
1198 #pragma GCC diagnostic ignored "-Wpragmas"
1199 #pragma GCC diagnostic ignored "-Wunused"
1200 #pragma GCC diagnostic ignored "-Wunused-function"
1201
1202 #ifdef __GNUC__
1203 #define SUPPRESS_NOT_USED_WARN __attribute__ ((unused))
1204 #else
1205 #define SUPPRESS_NOT_USED_WARN
1206 #endif
1207
1208 void SUPPRESS_NOT_USED_WARN setIgnoreFormat(string type, bool value)
1209 {
1210   IgnoreFormats().setIgnoreFormat(type, value);
1211 }
1212 #pragma GCC diagnostic pop
1213
1214 class LatexInfo {
1215  private:
1216   int entidx;
1217   Entries entries;
1218   Intervall interval;
1219   void buildKeys(bool);
1220   void buildEntries(bool);
1221   void makeKey(const string &, KeyInfo, bool isPatternString);
1222   void processRegion(int start, int region_end); /*  remove {} parts */
1223   void removeHead(KeyInfo&, int count=0);
1224   IgnoreFormats f;
1225
1226  public:
1227  LatexInfo(string par, bool isPatternString) : interval(isPatternString) {
1228     interval.par = par;
1229     buildKeys(isPatternString);
1230     entries = vector<KeyInfo>();
1231     buildEntries(isPatternString);
1232   };
1233   int getFirstKey() {
1234     entidx = 0;
1235     if (entries.empty()) {
1236       return (-1);
1237     }
1238     return 0;
1239   };
1240   int getNextKey() {
1241     entidx++;
1242     if (int(entries.size()) > entidx) {
1243       return entidx;
1244     }
1245     else {
1246       return (-1);
1247     }
1248   };
1249   bool setNextKey(int idx) {
1250     if ((idx == entidx) && (entidx >= 0)) {
1251       entidx--;
1252       return true;
1253     }
1254     else
1255       return false;
1256   };
1257   int process(ostringstream &os, KeyInfo &actual);
1258   int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
1259   // string show(int lastpos) { return interval.show(lastpos);};
1260   int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1261   KeyInfo &getKeyInfo(int keyinfo) {
1262     static KeyInfo invalidInfo = KeyInfo();
1263     if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1264       return invalidInfo;
1265     else
1266       return entries[keyinfo];
1267   };
1268   void setForDefaultLang(int upTo) {interval.setForDefaultLang(upTo);};
1269 };
1270
1271
1272 int Intervall::findclosing(int start, int end, char up = '{', char down = '}')
1273 {
1274   int skip = 0;
1275   int depth = 0;
1276   for (int i = start; i < end; i += 1 + skip) {
1277     char c;
1278     c = par[i];
1279     skip = 0;
1280     if (c == '\\') skip = 1;
1281     else if (c == up) {
1282       depth++;
1283     }
1284     else if (c == down) {
1285       if (depth == 0) return i;
1286       --depth;
1287     }
1288   }
1289   return end;
1290 }
1291
1292 class MathInfo {
1293   class MathEntry {
1294   public:
1295     string wait;
1296     size_t mathEnd;
1297     size_t mathStart;
1298     size_t mathSize;
1299   };
1300   size_t actualIdx;
1301   vector<MathEntry> entries;
1302  public:
1303   MathInfo() {
1304     actualIdx = 0;
1305   }
1306   void insert(string wait, size_t start, size_t end) {
1307     MathEntry m = MathEntry();
1308     m.wait = wait;
1309     m.mathStart = start;
1310     m.mathEnd = end;
1311     m.mathSize = end - start;
1312     entries.push_back(m);
1313   }
1314   bool evaluating(size_t pos) {
1315     while (actualIdx < entries.size()) {
1316       if (pos < entries[actualIdx].mathStart)
1317         return false;
1318       if (pos < entries[actualIdx].mathEnd)
1319         return true;
1320       actualIdx++;
1321     }
1322     return false;
1323   }
1324   bool empty() { return entries.empty(); };
1325   size_t getEndPos() {
1326     if (entries.empty() || (actualIdx >= entries.size())) {
1327       return 0;
1328     }
1329     return entries[actualIdx].mathEnd;
1330   }
1331   size_t getStartPos() {
1332     if (entries.empty() || (actualIdx >= entries.size())) {
1333       return 100000;                    /*  definitely enough? */
1334     }
1335     return entries[actualIdx].mathStart;
1336   }
1337   size_t getFirstPos() {
1338     actualIdx = 0;
1339     return getStartPos();
1340   }
1341   size_t getSize() {
1342     if (entries.empty() || (actualIdx >= entries.size())) {
1343       return size_t(0);
1344     }
1345     return entries[actualIdx].mathSize;
1346   }
1347   void incrEntry() { actualIdx++; };
1348 };
1349
1350 void LatexInfo::buildEntries(bool isPatternString)
1351 {
1352   static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multiline|align)\\*?)\\}");
1353   static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1354   static bool disableLanguageOverride = false;
1355   smatch sub, submath;
1356   bool evaluatingRegexp = false;
1357   MathInfo mi;
1358   bool evaluatingMath = false;
1359   KeyInfo found;
1360   bool math_end_waiting = false;
1361   size_t math_pos = 10000;
1362   string math_end;
1363
1364   for (sregex_iterator itmath(interval.par.begin(), interval.par.end(), rmath), end; itmath != end; ++itmath) {
1365     submath = *itmath;
1366     if (math_end_waiting) {
1367       size_t pos = submath.position(size_t(0));
1368       if (math_end == "$") {
1369         if ((submath.str(0) == "$") && (interval.par[pos-1] != '\\')) {
1370           mi.insert("$", math_pos, pos + 1);
1371           math_end_waiting = false;
1372         }
1373       }
1374       else if (math_end == "\\]") {
1375         if (submath.str(0) == "\\]") {
1376           mi.insert("\\]", math_pos, pos + 2);
1377           math_end_waiting = false;
1378         }
1379       }
1380       else if ((submath.str(1).compare("end") == 0) &&
1381           (submath.str(2).compare(math_end) == 0)) {
1382         mi.insert(math_end, math_pos, pos + submath.str(0).length());
1383         math_end_waiting = false;
1384       }
1385     }
1386     else {
1387       if (submath.str(1).compare("begin") == 0) {
1388         math_end_waiting = true;
1389         math_end = submath.str(2);
1390         math_pos = submath.position(size_t(0));
1391       }
1392       else if (submath.str(0).compare("\\[") == 0) {
1393         math_end_waiting = true;
1394         math_end = "\\]";
1395         math_pos = submath.position(size_t(0));
1396       }
1397       else if (submath.str(0) == "$") {
1398         size_t pos = submath.position(size_t(0));
1399         if ((pos == 0) || (interval.par[pos-1] != '\\')) {
1400           math_end_waiting = true;
1401           math_end = "$";
1402           math_pos = pos;
1403         }
1404       }
1405     }
1406   }
1407   // Ignore language if there is math somewhere in pattern-string
1408   if (isPatternString) {
1409     if (! mi.empty()) {
1410       // Disable language
1411       keys["foreignlanguage"].disabled = true;
1412       disableLanguageOverride = true;
1413     }
1414     else
1415       disableLanguageOverride = false;
1416   }
1417   else {
1418     if (disableLanguageOverride) {
1419       keys["foreignlanguage"].disabled = true;
1420     }
1421   }
1422   math_pos = mi.getFirstPos();
1423   for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1424     sub = *it;
1425     string key = sub.str(3);
1426     if (key == "") {
1427       if (sub.str(0)[0] == '\\')
1428         key = sub.str(0)[1];
1429       else
1430         key = sub.str(0);
1431     };
1432     if (evaluatingRegexp) {
1433       if (sub.str(1).compare("endregexp") == 0) {
1434         evaluatingRegexp = false;
1435         // found._tokenstart already set
1436         found._dataEnd = sub.position(size_t(0)) + 13;
1437         found._dataStart = found._dataEnd;
1438         found._tokensize = found._dataEnd - found._tokenstart;
1439         found.parenthesiscount = 0;
1440       }
1441     }
1442     else {
1443       if (evaluatingMath) {
1444         if (size_t(sub.position(size_t(0))) < mi.getEndPos())
1445           continue;
1446         evaluatingMath = false;
1447         mi.incrEntry();
1448         math_pos = mi.getStartPos();
1449       }
1450       if (keys.find(key) == keys.end()) {
1451         LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1452         continue;
1453       }
1454       found = keys[key];
1455       if (key.compare("regexp") == 0) {
1456         evaluatingRegexp = true;
1457         found._tokenstart = sub.position(size_t(0));
1458         found._tokensize = 0;
1459         continue;
1460       }
1461     }
1462     // Handle the other params of key
1463     if (found.keytype == KeyInfo::isIgnored)
1464       continue;
1465     else if (found.keytype == KeyInfo::isMath) {
1466       if (size_t(sub.position(size_t(0))) == math_pos) {
1467         found = keys[key];
1468         found._tokenstart = sub.position(size_t(0));
1469         found._tokensize = mi.getSize();
1470         found._dataEnd = found._tokenstart + found._tokensize;
1471         found._dataStart = found._dataEnd;
1472         found.parenthesiscount = 0;
1473         evaluatingMath = true;
1474       }
1475       else {
1476         // begin|end of unknown env, discard
1477         found = keys[key];
1478         // discard spaces before pos(0)
1479         int pos = sub.position(size_t(0));
1480         int count;
1481         for (count = 0; pos - count > 0; count++) {
1482           char c = interval.par[pos-count-1];
1483           if (c != ' ')
1484             break;
1485         }
1486         found.keytype = KeyInfo::doRemove;
1487         found._tokenstart = pos - count;
1488         if (sub.str(1).compare(0, 5, "begin") == 0) {
1489           size_t pos1 = pos + sub.str(0).length();
1490           if (interval.par[pos1] == '[') {
1491             pos1 = interval.findclosing(pos1+1, interval.par.length(), '[', ']')+1;
1492           }
1493           if (interval.par[pos1] == '{') {
1494             found._dataEnd = interval.findclosing(pos1+1, interval.par.length()) + 1;
1495           }
1496           else {
1497             found._dataEnd = pos1;
1498           }
1499           found._dataStart = found._dataEnd;
1500         }
1501         else {
1502           found._dataStart = pos + sub.str(0).length();
1503           found._dataEnd = found._dataStart;
1504         }
1505         found._tokensize = count + found._dataEnd - pos;
1506         found.parenthesiscount = 0;
1507         found.disabled = true;
1508       }
1509     }
1510     else if (found.keytype != KeyInfo::isRegex) {
1511       found._tokenstart = sub.position(size_t(0));
1512       if (found.parenthesiscount == 0) {
1513         // Probably to be discarded
1514         char following = interval.par[sub.position(size_t(0)) + sub.str(3).length() + 1];
1515         if (following == ' ')
1516           found.head = "\\" + sub.str(3) + " ";
1517         else if (following == '=') {
1518           // like \uldepth=1000pt
1519           found.head = sub.str(0);
1520         }
1521         else
1522           found.head = "\\" + key;
1523         found._tokensize = found.head.length();
1524         found._dataEnd = found._tokenstart + found._tokensize;
1525         found._dataStart = found._dataEnd;
1526       }
1527       else {
1528         if (found.parenthesiscount == 1) {
1529           found.head = "\\" + key + "{";
1530         }
1531         else if (found.parenthesiscount == 2) {
1532           found.head = sub.str(0) + "{";
1533         }
1534         found._tokensize = found.head.length();
1535         found._dataStart = found._tokenstart + found.head.length();
1536         size_t endpos = interval.findclosing(found._dataStart, interval.par.length());
1537         if ((endpos == interval.par.length()) &&
1538             (found.keytype == KeyInfo::doRemove)) {
1539           // Missing closing => error in latex-input?
1540           // therefore do not delete remaining data
1541           found._dataStart -= 1;
1542           found._dataEnd = found._dataStart;
1543         }
1544         else
1545           found._dataEnd = endpos;
1546         if (isPatternString) {
1547           keys[key].used = true;
1548         }
1549       }
1550     }
1551     entries.push_back(found);
1552   }
1553 }
1554
1555 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
1556 {
1557   stringstream s(keysstring);
1558   string key;
1559   const char delim = '|';
1560   while (getline(s, key, delim)) {
1561     KeyInfo keyII(keyI);
1562     if (isPatternString) {
1563       keyII.used = false;
1564     }
1565     else if ( !keys[key].used)
1566       keyII.disabled = true;
1567     keys[key] = keyII;
1568   }
1569 }
1570
1571 void LatexInfo::buildKeys(bool isPatternString)
1572 {
1573
1574   static bool keysBuilt = false;
1575   if (keysBuilt && !isPatternString) return;
1576
1577   // Know standard keys with 1 parameter.
1578   // Split is done, if not at start of region
1579   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, f.getFamily()), isPatternString);
1580   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, f.getSeries()), isPatternString);
1581   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, f.getShape()), isPatternString);
1582   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, f.getUnderline()), isPatternString);
1583   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, f.getMarkUp()), isPatternString);
1584   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, f.getStrikeOut()), isPatternString);
1585
1586   makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
1587           KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1588   makeKey("section*|subsection*|subsubsection*|paragraph*",
1589           KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1590   makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1591   makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isSectioning, 1, f.getFrontMatter()), isPatternString);
1592   // Regex
1593   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
1594
1595   // Split is done, if not at start of region
1596   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, f.getColor()), isPatternString);
1597
1598   // Split is done always.
1599   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, f.getLanguage()), isPatternString);
1600
1601   // Know charaters
1602   // No split
1603   makeKey("backslash|textbackslash|textasciicircum|textasciitilde|ldots", KeyInfo(KeyInfo::isChar, 1, false), isPatternString);
1604   // Found in fr/UserGuide.lyx
1605   makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
1606
1607   // Known macros to remove (including their parameter)
1608   // No split
1609   makeKey("inputencoding|shortcut|label|ref", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
1610
1611   // Macros to remove, but let the parameter survive
1612   // No split
1613   makeKey("url|href|menuitem|footnote|code|index", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1614
1615   // Same effect as previous, parameter will survive (because there is no one anyway)
1616   // No split
1617   makeKey("noindent", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
1618   // Remove table decorations
1619   makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
1620   // Discard shape-header
1621   makeKey("circlepar|diamondpar|heartpar|nutpar",  KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1622   makeKey("trianglerightpar|hexagonpar|starpar",   KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1623   makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1624   makeKey("triangleleftpar|shapepar|dropuppar",    KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1625   // like ('tiny{}' or '\tiny ' ... }
1626   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, true), isPatternString);
1627
1628   // Survives, like known character
1629   makeKey("lyx|latex|tex", KeyInfo(KeyInfo::isIgnored, 0, false), isPatternString);
1630   makeKey("item", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
1631
1632   makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1633   makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1634   makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1635
1636   makeKey("par|uldepth|ULdepth|protect", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
1637
1638   if (isPatternString) {
1639     // Allow the first searched string to rebuild the keys too
1640     keysBuilt = false;
1641   }
1642   else {
1643     // no need to rebuild again
1644     keysBuilt = true;
1645   }
1646 }
1647
1648 /*
1649  * Keep the list of actual opened parentheses actual
1650  * (e.g. depth == 4 means there are 4 '{' not processed yet)
1651  */
1652 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1653 {
1654   int skip = 0;
1655   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1656     char c;
1657     c = par[i];
1658     skip = 0;
1659     if (c == '\\') skip = 1;
1660     else if (c == '{') {
1661       handleOpenP(i);
1662     }
1663     else if (c == '}') {
1664       handleCloseP(i, closingAllowed);
1665     }
1666   }
1667 }
1668
1669 #if (0)
1670 string Intervall::show(int lastpos)
1671 {
1672   int idx = 0;                          /* int intervalls */
1673   int count = 0;
1674   string s;
1675   int i = 0;
1676   for (idx = 0; idx <= ignoreidx; idx++) {
1677     while (i < lastpos) {
1678       int printsize;
1679       if (i <= borders[idx].low) {
1680         if (borders[idx].low > lastpos)
1681           printsize = lastpos - i;
1682         else
1683           printsize = borders[idx].low - i;
1684         s += par.substr(i, printsize);
1685         i += printsize;
1686         if (i >= borders[idx].low)
1687           i = borders[idx].upper;
1688       }
1689       else {
1690         i = borders[idx].upper;
1691         break;
1692       }
1693     }
1694   }
1695   if (lastpos > i) {
1696     s += par.substr(i, lastpos-i);
1697   }
1698   return (s);
1699 }
1700 #endif
1701
1702 void Intervall::output(ostringstream &os, int lastpos)
1703 {
1704   // get number of chars to output
1705   int idx = 0;                          /* int intervalls */
1706   int i = 0;
1707   for (idx = 0; idx <= ignoreidx; idx++) {
1708     if (i < lastpos) {
1709       int printsize;
1710       if (i <= borders[idx].low) {
1711         if (borders[idx].low > lastpos)
1712           printsize = lastpos - i;
1713         else
1714           printsize = borders[idx].low - i;
1715         os << par.substr(i, printsize);
1716         i += printsize;
1717         handleParentheses(i, false);
1718         if (i >= borders[idx].low)
1719           i = borders[idx].upper;
1720       }
1721       else {
1722         i = borders[idx].upper;
1723       }
1724     }
1725     else
1726       break;
1727   }
1728   if (lastpos > i) {
1729     os << par.substr(i, lastpos-i);
1730   }
1731   handleParentheses(lastpos, false);
1732   for (int i = actualdeptindex; i > 0; --i) {
1733     os << "}";
1734   }
1735   if (! isPatternString)
1736     os << "\n";
1737   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1738 }
1739
1740 void LatexInfo::processRegion(int start, int region_end)
1741 {
1742   while (start < region_end) {          /* Let {[} and {]} survive */
1743     if ((interval.par[start] == '{') &&
1744         (interval.par[start+1] != ']') &&
1745         (interval.par[start+1] != '[')) {
1746       // Closing is allowed past the region
1747       int closing = interval.findclosing(start+1, interval.par.length());
1748       interval.addIntervall(start, start+1);
1749       interval.addIntervall(closing, closing+1);
1750     }
1751     start = interval.nextNotIgnored(start+1);
1752   }
1753 }
1754
1755 void LatexInfo::removeHead(KeyInfo &actual, int count)
1756 {
1757   if (actual.parenthesiscount == 0) {
1758     // "{\tiny{} ...}" ==> "{{} ...}"
1759     interval.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
1760   }
1761   else {
1762     // Remove header hull, that is "\url{abcd}" ==> "abcd"
1763     interval.addIntervall(actual._tokenstart, actual._dataStart);
1764     interval.addIntervall(actual._dataEnd, actual._dataEnd+1);
1765   }
1766 }
1767
1768 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
1769 {
1770   int nextKeyIdx = 0;
1771   switch (actual.keytype)
1772   {
1773     case KeyInfo::isChar: {
1774       nextKeyIdx = getNextKey();
1775       break;
1776     }
1777     case KeyInfo::isSize: {
1778       if (actual.disabled) {
1779         // Allways disabled
1780         processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
1781         interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1782         nextKeyIdx = getNextKey();
1783       } else {
1784         // Split on this key if not at start
1785         int start = interval.nextNotIgnored(previousStart);
1786         if (start < actual._tokenstart) {
1787           interval.output(os, actual._tokenstart);
1788           interval.addIntervall(start, actual._tokenstart);
1789         }
1790         // discard entry if at end of actual
1791         nextKeyIdx = process(os, actual);
1792       }
1793       break;
1794     }
1795     case KeyInfo::isStandard: {
1796       if (actual.disabled) {
1797         removeHead(actual);
1798         processRegion(actual._dataStart, actual._dataStart+1);
1799         nextKeyIdx = getNextKey();
1800       } else {
1801         // Split on this key if not at start
1802         int start = interval.nextNotIgnored(previousStart);
1803         if (start < actual._tokenstart) {
1804           interval.output(os, actual._tokenstart);
1805           interval.addIntervall(start, actual._tokenstart);
1806         }
1807         // discard entry if at end of actual
1808         nextKeyIdx = process(os, actual);
1809       }
1810       break;
1811     }
1812     case KeyInfo::doRemove: {
1813       // Remove the key with all parameters and following spaces
1814       size_t pos;
1815       for (pos = actual._dataEnd+1; pos < interval.par.length(); pos++) {
1816         if (interval.par[pos] != ' ')
1817           break;
1818       }
1819       interval.addIntervall(actual._tokenstart, pos);
1820       nextKeyIdx = getNextKey();
1821       break;
1822     }
1823     case KeyInfo::isList: {
1824       // Discard space before _tokenstart
1825       int count;
1826       for (count = 0; count < actual._tokenstart; count++) {
1827         if (interval.par[actual._tokenstart-count-1] != ' ')
1828           break;
1829       }
1830       if (actual.disabled) {
1831         interval.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
1832       }
1833       else {
1834         interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1835       }
1836       // Discard extra parentheses '[]'
1837       if (interval.par[actual._dataEnd+1] == '[') {
1838         int posdown = interval.findclosing(actual._dataEnd+2, interval.par.length(), '[', ']');
1839         if ((interval.par[actual._dataEnd+2] == '{') &&
1840             (interval.par[posdown-1] == '}')) {
1841           interval.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
1842           interval.addIntervall(posdown-1, posdown+1);
1843         }
1844         else {
1845           interval.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
1846           interval.addIntervall(posdown, posdown+1);
1847         }
1848         int blk = interval.nextNotIgnored(actual._dataEnd+1);
1849         if (blk > posdown) {
1850           // Discard at most 1 space after empty item
1851           int count;
1852           for (count = 0; count < 1; count++) {
1853             if (interval.par[blk+count] != ' ')
1854               break;
1855           }
1856           if (count > 0)
1857             interval.addIntervall(blk, blk+count);
1858         }
1859       }
1860       nextKeyIdx = getNextKey();
1861       break;
1862     }
1863     case KeyInfo::isSectioning: {
1864       // Discard spaces before _tokenstart
1865       int count;
1866       for (count = 0; count < actual._tokenstart; count++) {
1867         if (interval.par[actual._tokenstart-count-1] != ' ')
1868           break;
1869       }
1870       if (actual.disabled) {
1871         removeHead(actual, count);
1872         nextKeyIdx = getNextKey();
1873       } else {
1874         interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1875         nextKeyIdx = process(os, actual);
1876       }
1877       break;
1878     }
1879     case KeyInfo::isMath: {
1880       // Same as regex, use the content unchanged
1881       nextKeyIdx = getNextKey();
1882       break;
1883     }
1884     case KeyInfo::isRegex: {
1885       // DO NOT SPLIT ON REGEX
1886       // Do not disable
1887       nextKeyIdx = getNextKey();
1888       break;
1889     }
1890     case KeyInfo::isIgnored: {
1891       // Treat like a character for now
1892       nextKeyIdx = getNextKey();
1893       break;
1894     }
1895     case KeyInfo::isMain: {
1896       if (actual.disabled) {
1897         removeHead(actual);
1898         if ((interval.par.substr(actual._dataStart, 3) == " \\[") ||
1899             (interval.par.substr(actual._dataStart, 8) == " \\begin{")) {
1900           // Discard also the space before math-equation
1901           interval.addIntervall(actual._dataStart, actual._dataStart+1);
1902         }
1903         interval.resetOpenedP(actual._dataStart-1);
1904       }
1905       else {
1906         if (actual._tokenstart == 0) {
1907           // for the first (and maybe dummy) language
1908           interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1909         }
1910         interval.resetOpenedP(actual._dataStart-1);
1911       }
1912       break;
1913     }
1914     case KeyInfo::invalid:
1915       // This cannot happen, already handled
1916       // fall through
1917     default: {
1918       // LYXERR0("Unhandled keytype");
1919       nextKeyIdx = getNextKey();
1920       break;
1921     }
1922   }
1923   return nextKeyIdx;
1924 }
1925
1926 int LatexInfo::process(ostringstream &os, KeyInfo &actual )
1927 {
1928   int end = interval.nextNotIgnored(actual._dataEnd);
1929   int oldStart = actual._dataStart;
1930   int nextKeyIdx = getNextKey();
1931   while (true) {
1932     if ((nextKeyIdx < 0) ||
1933         (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1934         (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1935       if (oldStart <= end) {
1936         processRegion(oldStart, end);
1937         oldStart = end+1;
1938       }
1939       break;
1940     }
1941     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1942
1943     if (nextKey.keytype == KeyInfo::isMain) {
1944       (void) dispatch(os, actual._dataStart, nextKey);
1945       end = nextKey._tokenstart;
1946       break;
1947     }
1948     processRegion(oldStart, nextKey._tokenstart);
1949     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
1950
1951     oldStart = nextKey._dataEnd+1;
1952   }
1953   // now nextKey is either invalid or is outside of actual._dataEnd
1954   // output the remaining and discard myself
1955   if (oldStart <= end) {
1956     processRegion(oldStart, end);
1957   }
1958   if (interval.par[end] == '}') {
1959     end += 1;
1960     // This is the normal case.
1961     // But if using the firstlanguage, the closing may be missing
1962   }
1963   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
1964   int output_end;
1965   if (actual._dataEnd < end)
1966     output_end = interval.nextNotIgnored(actual._dataEnd);
1967   else
1968     output_end = interval.nextNotIgnored(end);
1969   if (interval.nextNotIgnored(actual._dataStart) < output_end)
1970     interval.output(os, output_end);
1971   interval.addIntervall(actual._tokenstart, end);
1972   return nextKeyIdx;
1973 }
1974
1975 string splitOnKnownMacros(string par, bool isPatternString) {
1976   ostringstream os;
1977   LatexInfo li(par, isPatternString);
1978   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
1979   DummyKey.head = "";
1980   DummyKey._tokensize = 0;
1981   DummyKey._tokenstart = 0;
1982   DummyKey._dataStart = 0;
1983   DummyKey._dataEnd = par.length();
1984   DummyKey.disabled = true;
1985   int firstkeyIdx = li.getFirstKey();
1986   string s;
1987   if (firstkeyIdx >= 0) {
1988     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
1989     int nextkeyIdx;
1990     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
1991       // Use dummy firstKey
1992       firstKey = DummyKey;
1993       (void) li.setNextKey(firstkeyIdx);
1994     }
1995     nextkeyIdx = li.process(os, firstKey);
1996     while (nextkeyIdx >= 0) {
1997       // Check for a possible gap between the last
1998       // entry and this one
1999       int datastart = li.nextNotIgnored(firstKey._dataStart);
2000       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2001       if ((nextKey._tokenstart > datastart)) {
2002         // Handle the gap
2003         firstKey._dataStart = datastart;
2004         firstKey._dataEnd = par.length();
2005         (void) li.setNextKey(nextkeyIdx);
2006         if (firstKey._tokensize > 0) {
2007           // Fake the last opened parenthesis
2008           li.setForDefaultLang(firstKey._tokensize);
2009         }
2010         nextkeyIdx = li.process(os, firstKey);
2011       }
2012       else {
2013         if (nextKey.keytype != KeyInfo::isMain) {
2014           firstKey._dataStart = datastart;
2015           firstKey._dataEnd = nextKey._dataEnd+1;
2016           (void) li.setNextKey(nextkeyIdx);
2017           if (firstKey._tokensize > 0)
2018             li.setForDefaultLang(firstKey._tokensize);
2019           nextkeyIdx = li.process(os, firstKey);
2020         }
2021         else {
2022           nextkeyIdx = li.process(os, nextKey);
2023         }
2024       }
2025     }
2026     // Handle the remaining
2027     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2028     firstKey._dataEnd = par.length();
2029     // Check if ! empty
2030     if ((firstKey._dataStart < firstKey._dataEnd) &&
2031         (par[firstKey._dataStart] != '}')) {
2032       if (firstKey._tokensize > 0)
2033         li.setForDefaultLang(firstKey._tokensize);
2034       (void) li.process(os, firstKey);
2035     }
2036     s = os.str();
2037     if (s.empty()) {
2038       // return string definitelly impossible to match
2039       s = "\\foreignlanguage{ignore}{ }";
2040     }
2041   }
2042   else
2043     s = par;                            /* no known macros found */
2044   return s;
2045 }
2046
2047 /*
2048  * Try to unify the language specs in the latexified text.
2049  * Resulting modified string is set to "", if
2050  * the searched tex does not contain all the features in the search pattern
2051  */
2052 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2053 {
2054         static Features regex_f;
2055         static int missed = 0;
2056         static bool regex_with_format = false;
2057
2058         int parlen = par.length();
2059
2060         while ((parlen > 0) && (par[parlen-1] == '\n')) {
2061                 parlen--;
2062         }
2063         string result;
2064         if (withformat) {
2065                 // Split the latex input into pieces which
2066                 // can be digested by our search engine
2067                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2068                 result = splitOnKnownMacros(par, isPatternString);
2069                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2070         }
2071         else
2072                 result = par.substr(0, parlen);
2073         if (isPatternString) {
2074                 missed = 0;
2075                 if (withformat) {
2076                         regex_f = identifyFeatures(result);
2077                         string features = "";
2078                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2079                                 string a = it->first;
2080                                 regex_with_format = true;
2081                                 features += " " + a;
2082                                 // LYXERR0("Identified regex format:" << a);
2083                         }
2084                         LYXERR(Debug::FIND, "Identified Features" << features);
2085
2086                 }
2087         } else if (regex_with_format) {
2088                 Features info = identifyFeatures(result);
2089                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2090                         string a = it->first;
2091                         bool b = it->second;
2092                         if (b && ! info[a]) {
2093                                 missed++;
2094                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2095                                 return("");
2096                         }
2097                 }
2098         }
2099         else {
2100                 // LYXERR0("No regex formats");
2101         }
2102         return(result);
2103 }
2104
2105
2106 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2107 static int identifyClosing(string & t)
2108 {
2109         int open_braces = 0;
2110         do {
2111                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2112                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
2113                         continue;
2114                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
2115                         continue;
2116                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
2117                         continue;
2118                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
2119                         ++open_braces;
2120                         continue;
2121                 }
2122                 break;
2123         } while (true);
2124         return open_braces;
2125 }
2126
2127
2128 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2129         : p_buf(&buf), p_first_buf(&buf), opt(opt)
2130 {
2131         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2132         docstring const & ds = stringifySearchBuffer(find_buf, opt);
2133         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2134         // When using regexp, braces are hacked already by escape_for_regex()
2135         par_as_string = normalize(ds, !use_regexp);
2136         open_braces = 0;
2137         close_wildcards = 0;
2138
2139         size_t lead_size = 0;
2140         // correct the language settings
2141         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2142         if (opt.ignoreformat) {
2143                 if (!use_regexp) {
2144                         // if par_as_string_nolead were emty,
2145                         // the following call to findAux will always *find* the string
2146                         // in the checked data, and thus always using the slow
2147                         // examining of the current text part.
2148                         par_as_string_nolead = par_as_string;
2149                 }
2150         } else {
2151                 lead_size = identifyLeading(par_as_string);
2152                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2153                 lead_as_string = par_as_string.substr(0, lead_size);
2154                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2155         }
2156
2157         if (!use_regexp) {
2158                 open_braces = identifyClosing(par_as_string);
2159                 identifyClosing(par_as_string_nolead);
2160                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2161                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2162         } else {
2163                 string lead_as_regexp;
2164                 if (lead_size > 0) {
2165                         // @todo No need to search for \regexp{} insets in leading material
2166                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2167                         par_as_string = par_as_string_nolead;
2168                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2169                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2170                 }
2171                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2172                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2173                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2174                 if (
2175                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2176                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2177                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2178                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2179                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2180                         || regex_replace(par_as_string, par_as_string,
2181                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2182                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2183                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2184                         ) {
2185                         ++close_wildcards;
2186                 }
2187                 if (!opt.ignoreformat) {
2188                         // Remove extra '\}' at end
2189                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
2190                                 open_braces++;
2191                         }
2192                         /*
2193                         // save '\.'
2194                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2195                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2196                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2197                         // replace '[^...]' with '[^...\}\{\\]'
2198                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2199                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2200                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2201                         // restore '\.'
2202                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2203                         */
2204                 }
2205                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2206                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2207                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
2208                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2209
2210                 // If entered regexp must match at begin of searched string buffer
2211                 // Kornel: Added parentheses to use $1 for size of the leading string
2212                 string regexp_str;
2213                 string regexp2_str;
2214                 {
2215                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2216                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
2217                         // so the convert has no effect in that case
2218                         for (int i = 8; i > 0; --i) {
2219                                 string orig = "\\\\" + std::to_string(i);
2220                                 string dest = "\\" + std::to_string(i+1);
2221                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
2222                         }
2223                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2224                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
2225                 }
2226                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2227                 regexp = lyx::regex(regexp_str);
2228
2229                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2230                 regexp2 = lyx::regex(regexp2_str);
2231         }
2232 }
2233
2234
2235 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2236 {
2237         if (at_begin &&
2238                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2239                 return 0;
2240
2241         docstring docstr = stringifyFromForSearch(opt, cur, len);
2242         string str = normalize(docstr, true);
2243         if (!opt.ignoreformat) {
2244                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
2245         }
2246         if (str.empty()) return(-1);
2247         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
2248         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
2249
2250         if (use_regexp) {
2251                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
2252                 regex const *p_regexp;
2253                 regex_constants::match_flag_type flags;
2254                 if (at_begin) {
2255                         flags = regex_constants::match_continuous;
2256                         p_regexp = &regexp;
2257                 } else {
2258                         flags = regex_constants::match_default;
2259                         p_regexp = &regexp2;
2260                 }
2261                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
2262                 if (re_it == sregex_iterator())
2263                         return 0;
2264                 match_results<string::const_iterator> const & m = *re_it;
2265
2266                 if (0) { // Kornel Benko: DO NOT CHECKK
2267                         // Check braces on the segment that matched the entire regexp expression,
2268                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
2269                         if (!braces_match(m[0].first, m[0].second, open_braces))
2270                                 return 0;
2271                 }
2272
2273                 // Check braces on segments that matched all (.*?) subexpressions,
2274                 // except the last "padding" one inserted by lyx.
2275                 for (size_t i = 1; i < m.size() - 1; ++i)
2276                         if (!braces_match(m[i].first, m[i].second, open_braces))
2277                                 return 0;
2278
2279                 // Exclude from the returned match length any length
2280                 // due to close wildcards added at end of regexp
2281                 // and also the length of the leading (e.g. '\emph{')
2282                 //
2283                 // Whole found string, including the leading: m[0].second - m[0].first
2284                 // Size of the leading string: m[1].second - m[1].first
2285                 int leadingsize = 0;
2286                 if (m.size() > 1)
2287                         leadingsize = m[1].second - m[1].first;
2288                 int result;
2289                 for (size_t i = 0; i < m.size(); i++) {
2290                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2291                 }
2292                 if (close_wildcards == 0)
2293                         result = m[0].second - m[0].first;
2294
2295                 else
2296                         result =  m[m.size() - close_wildcards].first - m[0].first;
2297
2298                 if (result > leadingsize)
2299                         result -= leadingsize;
2300                 else
2301                         result = 0;
2302                 return(result);
2303         }
2304
2305         // else !use_regexp: but all code paths above return
2306         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2307                                  << par_as_string << "', str='" << str << "'");
2308         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2309                                  << lead_as_string << "', par_as_string_nolead='"
2310                                  << par_as_string_nolead << "'");
2311
2312         if (at_begin) {
2313                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2314                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2315                 if (str.substr(0, par_as_string.size()) == par_as_string)
2316                         return par_as_string.size();
2317         } else {
2318                 size_t pos = str.find(par_as_string_nolead);
2319                 if (pos != string::npos)
2320                         return par_as_string.size();
2321         }
2322         return 0;
2323 }
2324
2325
2326 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
2327 {
2328         int res = findAux(cur, len, at_begin);
2329         LYXERR(Debug::FIND,
2330                "res=" << res << ", at_begin=" << at_begin
2331                << ", matchword=" << opt.matchword
2332                << ", inTexted=" << cur.inTexted());
2333         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
2334                 return res;
2335         Paragraph const & par = cur.paragraph();
2336         bool ws_left = (cur.pos() > 0)
2337                 ? par.isWordSeparator(cur.pos() - 1)
2338                 : true;
2339         bool ws_right = (cur.pos() + res < par.size())
2340                 ? par.isWordSeparator(cur.pos() + res)
2341                 : true;
2342         LYXERR(Debug::FIND,
2343                "cur.pos()=" << cur.pos() << ", res=" << res
2344                << ", separ: " << ws_left << ", " << ws_right
2345                << endl);
2346         if (ws_left && ws_right)
2347                 return res;
2348         return 0;
2349 }
2350
2351
2352 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
2353 {
2354         string t;
2355         if (! opt.casesensitive)
2356                 t = lyx::to_utf8(lowercase(s));
2357         else
2358                 t = lyx::to_utf8(s);
2359         // Remove \n at begin
2360         while (!t.empty() && t[0] == '\n')
2361                 t = t.substr(1);
2362         // Remove \n at end
2363         while (!t.empty() && t[t.size() - 1] == '\n')
2364                 t = t.substr(0, t.size() - 1);
2365         size_t pos;
2366         // Replace all other \n with spaces
2367         while ((pos = t.find("\n")) != string::npos)
2368                 t.replace(pos, 1, " ");
2369         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
2370         // Kornel: Added textsl, textsf, textit, texttt and noun
2371         // + allow to seach for colored text too
2372         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
2373         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
2374                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2375         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
2376                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2377
2378         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
2379         // FIXME - check what preceeds the brace
2380         if (hack_braces) {
2381                 if (opt.ignoreformat)
2382                         while (regex_replace(t, t, "\\{", "_x_<")
2383                                || regex_replace(t, t, "\\}", "_x_>"))
2384                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2385                 else
2386                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
2387                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
2388                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2389         }
2390
2391         return t;
2392 }
2393
2394
2395 docstring stringifyFromCursor(DocIterator const & cur, int len)
2396 {
2397         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2398         if (cur.inTexted()) {
2399                 Paragraph const & par = cur.paragraph();
2400                 // TODO what about searching beyond/across paragraph breaks ?
2401                 // TODO Try adding a AS_STR_INSERTS as last arg
2402                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2403                         int(par.size()) : cur.pos() + len;
2404                 OutputParams runparams(&cur.buffer()->params().encoding());
2405                 runparams.nice = true;
2406                 runparams.flavor = OutputParams::LATEX;
2407                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2408                 // No side effect of file copying and image conversion
2409                 runparams.dryrun = true;
2410                 LYXERR(Debug::FIND, "Stringifying with cur: "
2411                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
2412                 return par.asString(cur.pos(), end,
2413                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2414                         &runparams);
2415         } else if (cur.inMathed()) {
2416                 CursorSlice cs = cur.top();
2417                 MathData md = cs.cell();
2418                 MathData::const_iterator it_end =
2419                         (( len == -1 || cs.pos() + len > int(md.size()))
2420                          ? md.end()
2421                          : md.begin() + cs.pos() + len );
2422                 MathData md2;
2423                 for (MathData::const_iterator it = md.begin() + cs.pos();
2424                      it != it_end; ++it)
2425                         md2.push_back(*it);
2426                 docstring s = asString(md2);
2427                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2428                 return s;
2429         }
2430         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2431         return docstring();
2432 }
2433
2434
2435 /** Computes the LaTeX export of buf starting from cur and ending len positions
2436  * after cur, if len is positive, or at the paragraph or innermost inset end
2437  * if len is -1.
2438  */
2439 docstring latexifyFromCursor(DocIterator const & cur, int len)
2440 {
2441         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2442         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2443                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2444         Buffer const & buf = *cur.buffer();
2445
2446         odocstringstream ods;
2447         otexstream os(ods);
2448         OutputParams runparams(&buf.params().encoding());
2449         runparams.nice = false;
2450         runparams.flavor = OutputParams::LATEX;
2451         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2452         // No side effect of file copying and image conversion
2453         runparams.dryrun = true;
2454         runparams.for_search = true;
2455
2456         if (cur.inTexted()) {
2457                 // @TODO what about searching beyond/across paragraph breaks ?
2458                 pos_type endpos = cur.paragraph().size();
2459                 if (len != -1 && endpos > cur.pos() + len)
2460                         endpos = cur.pos() + len;
2461                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2462                           string(), cur.pos(), endpos);
2463                 string s = lyx::to_utf8(ods.str());
2464                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2465                 return(lyx::from_utf8(s));
2466         } else if (cur.inMathed()) {
2467                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2468                 for (int s = cur.depth() - 1; s >= 0; --s) {
2469                         CursorSlice const & cs = cur[s];
2470                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2471                                 WriteStream ws(os);
2472                                 cs.asInsetMath()->asHullInset()->header_write(ws);
2473                                 break;
2474                         }
2475                 }
2476
2477                 CursorSlice const & cs = cur.top();
2478                 MathData md = cs.cell();
2479                 MathData::const_iterator it_end =
2480                         ((len == -1 || cs.pos() + len > int(md.size()))
2481                          ? md.end()
2482                          : md.begin() + cs.pos() + len);
2483                 MathData md2;
2484                 for (MathData::const_iterator it = md.begin() + cs.pos();
2485                      it != it_end; ++it)
2486                         md2.push_back(*it);
2487
2488                 ods << asString(md2);
2489                 // Retrieve the math environment type, and add '$' or '$]'
2490                 // or others (\end{equation}) accordingly
2491                 for (int s = cur.depth() - 1; s >= 0; --s) {
2492                         CursorSlice const & cs2 = cur[s];
2493                         InsetMath * inset = cs2.asInsetMath();
2494                         if (inset && inset->asHullInset()) {
2495                                 WriteStream ws(os);
2496                                 inset->asHullInset()->footer_write(ws);
2497                                 break;
2498                         }
2499                 }
2500                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2501         } else {
2502                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2503         }
2504         return ods.str();
2505 }
2506
2507
2508 /** Finalize an advanced find operation, advancing the cursor to the innermost
2509  ** position that matches, plus computing the length of the matching text to
2510  ** be selected
2511  **/
2512 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2513 {
2514         // Search the foremost position that matches (avoids find of entire math
2515         // inset when match at start of it)
2516         size_t d;
2517         DocIterator old_cur(cur.buffer());
2518         do {
2519                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2520                 d = cur.depth();
2521                 old_cur = cur;
2522                 cur.forwardPos();
2523         } while (cur && cur.depth() > d && match(cur) > 0);
2524         cur = old_cur;
2525         if (match(cur) <= 0) return 0;
2526         LYXERR(Debug::FIND, "Ok");
2527
2528         // Compute the match length
2529         int len = 1;
2530         if (cur.pos() + len > cur.lastpos())
2531                 return 0;
2532         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2533         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2534                 ++len;
2535                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2536         }
2537         // Length of matched text (different from len param)
2538         int old_match = match(cur, len);
2539         if (old_match < 0)
2540                 old_match = 0;
2541         int prev_old_match = old_match;
2542         int old_len = len;
2543         int step = 20;
2544         int new_match;
2545         while (step == 20) {
2546                 if (cur.pos() + len + step >= cur.lastpos()) {
2547                         step = 1;
2548                         len = old_len;
2549                         old_match = prev_old_match;
2550                 }
2551                 else {
2552                         new_match = match(cur, len + step);
2553                         if (new_match > old_match) {
2554                                 prev_old_match = old_match;
2555                                 old_match = new_match;
2556                                 old_len = len;
2557                                 len += step;
2558                         }
2559                         else {
2560                                 step = 1;
2561                                 len = old_len;
2562                                 old_match = prev_old_match;
2563                         }
2564                 }
2565         }
2566         // Greedy behaviour while matching regexps
2567         bool examining = true;
2568         while (examining) {
2569                 examining = false;
2570                 // Kornel: The loop is needed, since it looks like
2571                 // incrementing 'cur.pos()' does not always lead to the following
2572                 // char which we could then match.
2573                 for (int count = 1; count < 5; ++count) {
2574                         if (cur.pos() + len + count > cur.lastpos()) {
2575                                 break;
2576                         }
2577                         new_match = match(cur, len + count);
2578                         if (new_match > old_match) {
2579                                 len += count;
2580                                 old_match = new_match;
2581                                 examining = true;
2582                                 break;
2583                         }
2584                 }
2585         }
2586         return len;
2587 }
2588
2589
2590 /// Finds forward
2591 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2592 {
2593         if (!cur)
2594                 return 0;
2595         while (!theApp()->longOperationCancelled() && cur) {
2596                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2597                 int match_len = match(cur, -1, false);
2598                 LYXERR(Debug::FIND, "match_len: " << match_len);
2599                 if (match_len > 0) {
2600                         int match_len_zero_count = 0;
2601                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2602                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2603                                 int match_len2 = match(cur);
2604                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2605                                 if (match_len2 > 0) {
2606                                         // Sometimes in finalize we understand it wasn't a match
2607                                         // and we need to continue the outest loop
2608                                         int len = findAdvFinalize(cur, match);
2609                                         if (len > 0) {
2610                                                 return len;
2611                                         }
2612                                 }
2613                                 if (match_len2 >= 0) {
2614                                         if (match_len2 == 0)
2615                                                 match_len_zero_count++;
2616                                         else
2617                                                 match_len_zero_count = 0;
2618                                 }
2619                                 else {
2620                                         if (++match_len_zero_count > 3) {
2621                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2622                                                 match_len_zero_count = 0;
2623                                         }
2624                                         break;
2625                                 }
2626                         }
2627                         if (!cur)
2628                                 return 0;
2629                 }
2630                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2631                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2632                         cur.forwardPar();
2633                 } else {
2634                         // This should exit nested insets, if any, or otherwise undefine the currsor.
2635                         cur.pos() = cur.lastpos();
2636                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2637                         cur.forwardPos();
2638                 }
2639         }
2640         return 0;
2641 }
2642
2643
2644 /// Find the most backward consecutive match within same paragraph while searching backwards.
2645 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2646 {
2647         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2648         DocIterator tmp_cur = cur;
2649         int len = findAdvFinalize(tmp_cur, match);
2650         Inset & inset = cur.inset();
2651         for (; cur != cur_begin; cur.backwardPos()) {
2652                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2653                 DocIterator new_cur = cur;
2654                 new_cur.backwardPos();
2655                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2656                         break;
2657                 int new_len = findAdvFinalize(new_cur, match);
2658                 if (new_len == len)
2659                         break;
2660                 len = new_len;
2661         }
2662         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2663         return len;
2664 }
2665
2666
2667 /// Finds backwards
2668 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2669 {
2670         if (! cur)
2671                 return 0;
2672         // Backup of original position
2673         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2674         if (cur == cur_begin)
2675                 return 0;
2676         cur.backwardPos();
2677         DocIterator cur_orig(cur);
2678         bool pit_changed = false;
2679         do {
2680                 cur.pos() = 0;
2681                 bool found_match = match(cur, -1, false);
2682
2683                 if (found_match) {
2684                         if (pit_changed)
2685                                 cur.pos() = cur.lastpos();
2686                         else
2687                                 cur.pos() = cur_orig.pos();
2688                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2689                         DocIterator cur_prev_iter;
2690                         do {
2691                                 found_match = match(cur);
2692                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2693                                        << found_match << ", cur: " << cur);
2694                                 if (found_match)
2695                                         return findMostBackwards(cur, match);
2696
2697                                 // Stop if begin of document reached
2698                                 if (cur == cur_begin)
2699                                         break;
2700                                 cur_prev_iter = cur;
2701                                 cur.backwardPos();
2702                         } while (true);
2703                 }
2704                 if (cur == cur_begin)
2705                         break;
2706                 if (cur.pit() > 0)
2707                         --cur.pit();
2708                 else
2709                         cur.backwardPos();
2710                 pit_changed = true;
2711         } while (!theApp()->longOperationCancelled());
2712         return 0;
2713 }
2714
2715
2716 } // namespace
2717
2718
2719 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2720                                  DocIterator const & cur, int len)
2721 {
2722         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2723                 return docstring();
2724         if (!opt.ignoreformat)
2725                 return latexifyFromCursor(cur, len);
2726         else
2727                 return stringifyFromCursor(cur, len);
2728 }
2729
2730
2731 FindAndReplaceOptions::FindAndReplaceOptions(
2732         docstring const & find_buf_name, bool casesensitive,
2733         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2734         docstring const & repl_buf_name, bool keep_case,
2735         SearchScope scope, SearchRestriction restr)
2736         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2737           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2738           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2739 {
2740 }
2741
2742
2743 namespace {
2744
2745
2746 /** Check if 'len' letters following cursor are all non-lowercase */
2747 static bool allNonLowercase(Cursor const & cur, int len)
2748 {
2749         pos_type beg_pos = cur.selectionBegin().pos();
2750         pos_type end_pos = cur.selectionBegin().pos() + len;
2751         if (len > cur.lastpos() + 1 - beg_pos) {
2752                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2753                 len = cur.lastpos() + 1 - beg_pos;
2754                 end_pos = beg_pos + len;
2755         }
2756         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2757                 if (isLowerCase(cur.paragraph().getChar(pos)))
2758                         return false;
2759         return true;
2760 }
2761
2762
2763 /** Check if first letter is upper case and second one is lower case */
2764 static bool firstUppercase(Cursor const & cur)
2765 {
2766         char_type ch1, ch2;
2767         pos_type pos = cur.selectionBegin().pos();
2768         if (pos >= cur.lastpos() - 1) {
2769                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2770                 return false;
2771         }
2772         ch1 = cur.paragraph().getChar(pos);
2773         ch2 = cur.paragraph().getChar(pos + 1);
2774         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2775         LYXERR(Debug::FIND, "firstUppercase(): "
2776                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2777                << ch2 << "(" << char(ch2) << ")"
2778                << ", result=" << result << ", cur=" << cur);
2779         return result;
2780 }
2781
2782
2783 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2784  **
2785  ** \fixme What to do with possible further paragraphs in replace buffer ?
2786  **/
2787 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2788 {
2789         ParagraphList::iterator pit = buffer.paragraphs().begin();
2790         LASSERT(pit->size() >= 1, /**/);
2791         pos_type right = pos_type(1);
2792         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2793         right = pit->size();
2794         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2795 }
2796
2797 } // namespace
2798
2799 ///
2800 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2801 {
2802         Cursor & cur = bv->cursor();
2803         if (opt.repl_buf_name == docstring()
2804             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2805             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2806                 return;
2807
2808         DocIterator sel_beg = cur.selectionBegin();
2809         DocIterator sel_end = cur.selectionEnd();
2810         if (&sel_beg.inset() != &sel_end.inset()
2811             || sel_beg.pit() != sel_end.pit()
2812             || sel_beg.idx() != sel_end.idx())
2813                 return;
2814         int sel_len = sel_end.pos() - sel_beg.pos();
2815         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2816                << ", sel_len: " << sel_len << endl);
2817         if (sel_len == 0)
2818                 return;
2819         LASSERT(sel_len > 0, return);
2820
2821         if (!matchAdv(sel_beg, sel_len))
2822                 return;
2823
2824         // Build a copy of the replace buffer, adapted to the KeepCase option
2825         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2826         ostringstream oss;
2827         repl_buffer_orig.write(oss);
2828         string lyx = oss.str();
2829         Buffer repl_buffer("", false);
2830         repl_buffer.setUnnamed(true);
2831         LASSERT(repl_buffer.readString(lyx), return);
2832         if (opt.keep_case && sel_len >= 2) {
2833                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2834                 if (cur.inTexted()) {
2835                         if (firstUppercase(cur))
2836                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2837                         else if (allNonLowercase(cur, sel_len))
2838                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2839                 }
2840         }
2841         cap::cutSelection(cur, false);
2842         if (cur.inTexted()) {
2843                 repl_buffer.changeLanguage(
2844                         repl_buffer.language(),
2845                         cur.getFont().language());
2846                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2847                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2848                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2849                                         repl_buffer.params().documentClassPtr(),
2850                                         bv->buffer().errorList("Paste"));
2851                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2852                 sel_len = repl_buffer.paragraphs().begin()->size();
2853         } else if (cur.inMathed()) {
2854                 odocstringstream ods;
2855                 otexstream os(ods);
2856                 OutputParams runparams(&repl_buffer.params().encoding());
2857                 runparams.nice = false;
2858                 runparams.flavor = OutputParams::LATEX;
2859                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2860                 runparams.dryrun = true;
2861                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2862                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2863                 docstring repl_latex = ods.str();
2864                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2865                 string s;
2866                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2867                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2868                 repl_latex = from_utf8(s);
2869                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2870                 MathData ar(cur.buffer());
2871                 asArray(repl_latex, ar, Parse::NORMAL);
2872                 cur.insert(ar);
2873                 sel_len = ar.size();
2874                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2875         }
2876         if (cur.pos() >= sel_len)
2877                 cur.pos() -= sel_len;
2878         else
2879                 cur.pos() = 0;
2880         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2881         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2882         bv->processUpdateFlags(Update::Force);
2883 }
2884
2885
2886 /// Perform a FindAdv operation.
2887 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2888 {
2889         DocIterator cur;
2890         int match_len = 0;
2891
2892         // e.g., when invoking word-findadv from mini-buffer wither with
2893         //       wrong options syntax or before ever opening advanced F&R pane
2894         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2895                 return false;
2896
2897         try {
2898                 MatchStringAdv matchAdv(bv->buffer(), opt);
2899                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2900                 if (length > 0)
2901                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2902                 findAdvReplace(bv, opt, matchAdv);
2903                 cur = bv->cursor();
2904                 if (opt.forward)
2905                         match_len = findForwardAdv(cur, matchAdv);
2906                 else
2907                         match_len = findBackwardsAdv(cur, matchAdv);
2908         } catch (...) {
2909                 // This may only be raised by lyx::regex()
2910                 bv->message(_("Invalid regular expression!"));
2911                 return false;
2912         }
2913
2914         if (match_len == 0) {
2915                 bv->message(_("Match not found!"));
2916                 return false;
2917         }
2918
2919         bv->message(_("Match found!"));
2920
2921         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2922         bv->putSelectionAt(cur, match_len, !opt.forward);
2923
2924         return true;
2925 }
2926
2927
2928 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2929 {
2930         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2931            << opt.casesensitive << ' '
2932            << opt.matchword << ' '
2933            << opt.forward << ' '
2934            << opt.expandmacros << ' '
2935            << opt.ignoreformat << ' '
2936            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2937            << opt.keep_case << ' '
2938            << int(opt.scope) << ' '
2939            << int(opt.restr);
2940
2941         LYXERR(Debug::FIND, "built: " << os.str());
2942
2943         return os;
2944 }
2945
2946
2947 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2948 {
2949         LYXERR(Debug::FIND, "parsing");
2950         string s;
2951         string line;
2952         getline(is, line);
2953         while (line != "EOSS") {
2954                 if (! s.empty())
2955                         s = s + "\n";
2956                 s = s + line;
2957                 if (is.eof())   // Tolerate malformed request
2958                         break;
2959                 getline(is, line);
2960         }
2961         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2962         opt.find_buf_name = from_utf8(s);
2963         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2964         is.get();       // Waste space before replace string
2965         s = "";
2966         getline(is, line);
2967         while (line != "EOSS") {
2968                 if (! s.empty())
2969                         s = s + "\n";
2970                 s = s + line;
2971                 if (is.eof())   // Tolerate malformed request
2972                         break;
2973                 getline(is, line);
2974         }
2975         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2976         opt.repl_buf_name = from_utf8(s);
2977         is >> opt.keep_case;
2978         int i;
2979         is >> i;
2980         opt.scope = FindAndReplaceOptions::SearchScope(i);
2981         is >> i;
2982         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2983
2984         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2985                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2986                << opt.scope << ' ' << opt.restr);
2987         return is;
2988 }
2989
2990 } // namespace lyx