]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
97202c46872d547f6d77643ad70a767ce02b91c9
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
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         }
601         return escape_map;
602 }
603
604 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
605  ** the found occurrence were escaped.
606  **/
607 string apply_escapes(string s, Escapes const & escape_map)
608 {
609         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
610         Escapes::const_iterator it;
611         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
612 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
613                 unsigned int pos = 0;
614                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
615                         s.replace(pos, it->first.length(), it->second);
616                         LYXERR(Debug::FIND, "After escape: " << s);
617                         pos += it->second.length();
618 //                      LYXERR(Debug::FIND, "pos: " << pos);
619                 }
620         }
621         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
622         return s;
623 }
624
625
626 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
627 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
628 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
629 string escape_for_regex(string s, bool match_latex)
630 {
631         size_t pos = 0;
632         while (pos < s.size()) {
633                 size_t new_pos = s.find("\\regexp{", pos);
634                 if (new_pos == string::npos)
635                         new_pos = s.size();
636                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
637                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
638                 LYXERR(Debug::FIND, "t [lyx]: " << t);
639                 t = apply_escapes(t, get_regexp_escapes());
640                 LYXERR(Debug::FIND, "t [rxp]: " << t);
641                 s.replace(pos, new_pos - pos, t);
642                 new_pos = pos + t.size();
643                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
644                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
645                 if (new_pos == s.size())
646                         break;
647                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
648                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
649                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
650                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
651                 LYXERR(Debug::FIND, "t in regexp      : " << t);
652                 t = apply_escapes(t, get_lyx_unescapes());
653                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
654                 if (match_latex) {
655                         t = apply_escapes(t, get_regexp_latex_escapes());
656                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
657                 }
658                 if (end_pos == s.size()) {
659                         s.replace(new_pos, end_pos - new_pos, t);
660                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
661                         break;
662                 }
663                 s.replace(new_pos, end_pos + 13 - new_pos, t);
664                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
665                 pos = new_pos + t.size();
666                 LYXERR(Debug::FIND, "pos: " << pos);
667         }
668         return s;
669 }
670
671
672 /// Wrapper for lyx::regex_replace with simpler interface
673 bool regex_replace(string const & s, string & t, string const & searchstr,
674                    string const & replacestr)
675 {
676         lyx::regex e(searchstr, regex_constants::ECMAScript);
677         ostringstream oss;
678         ostream_iterator<char, char> it(oss);
679         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
680         // tolerate t and s be references to the same variable
681         bool rv = (s != oss.str());
682         t = oss.str();
683         return rv;
684 }
685
686
687 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
688  **
689  ** Verify that closed braces exactly match open braces. This avoids that, for example,
690  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
691  **
692  ** @param unmatched
693  ** Number of open braces that must remain open at the end for the verification to succeed.
694  **/
695 bool braces_match(string::const_iterator const & beg,
696                   string::const_iterator const & end,
697                   int unmatched = 0)
698 {
699         int open_pars = 0;
700         string::const_iterator it = beg;
701         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
702         for (; it != end; ++it) {
703                 // Skip escaped braces in the count
704                 if (*it == '\\') {
705                         ++it;
706                         if (it == end)
707                                 break;
708                 } else if (*it == '{') {
709                         ++open_pars;
710                 } else if (*it == '}') {
711                         if (open_pars == 0) {
712                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
713                                 return false;
714                         } else
715                                 --open_pars;
716                 }
717         }
718         if (open_pars != unmatched) {
719                 LYXERR(Debug::FIND, "Found " << open_pars
720                        << " instead of " << unmatched
721                        << " unmatched open braces at the end of count");
722                 return false;
723         }
724         LYXERR(Debug::FIND, "Braces match as expected");
725         return true;
726 }
727
728
729 /** The class performing a match between a position in the document and the FindAdvOptions.
730  **/
731 class MatchStringAdv {
732 public:
733         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
734
735         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
736          ** constructor as opt.search, under the opt.* options settings.
737          **
738          ** @param at_begin
739          **     If set, then match is searched only against beginning of text starting at cur.
740          **     If unset, then match is searched anywhere in text starting at cur.
741          **
742          ** @return
743          ** The length of the matching text, or zero if no match was found.
744          **/
745         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
746
747 public:
748         /// buffer
749         lyx::Buffer * p_buf;
750         /// first buffer on which search was started
751         lyx::Buffer * const p_first_buf;
752         /// options
753         FindAndReplaceOptions const & opt;
754
755 private:
756         /// Auxiliary find method (does not account for opt.matchword)
757         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
758
759         /** Normalize a stringified or latexified LyX paragraph.
760          **
761          ** Normalize means:
762          ** <ul>
763          **   <li>if search is not casesensitive, then lowercase the string;
764          **   <li>remove any newline at begin or end of the string;
765          **   <li>replace any newline in the middle of the string with a simple space;
766          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
767          ** </ul>
768          **
769          ** @todo Normalization should also expand macros, if the corresponding
770          ** search option was checked.
771          **/
772         string normalize(docstring const & s, bool hack_braces) const;
773         // normalized string to search
774         string par_as_string;
775         // regular expression to use for searching
776         lyx::regex regexp;
777         // same as regexp, but prefixed with a ".*"
778         lyx::regex regexp2;
779         // leading format material as string
780         string lead_as_string;
781         // par_as_string after removal of lead_as_string
782         string par_as_string_nolead;
783         // unmatched open braces in the search string/regexp
784         int open_braces;
785         // number of (.*?) subexpressions added at end of search regexp for closing
786         // environments, math mode, styles, etc...
787         int close_wildcards;
788         // Are we searching with regular expressions ?
789         bool use_regexp;
790 };
791
792
793 static docstring buffer_to_latex(Buffer & buffer)
794 {
795         OutputParams runparams(&buffer.params().encoding());
796         odocstringstream ods;
797         otexstream os(ods);
798         runparams.nice = true;
799         runparams.flavor = OutputParams::LATEX;
800         runparams.linelen = 80; //lyxrc.plaintext_linelen;
801         // No side effect of file copying and image conversion
802         runparams.dryrun = true;
803         runparams.for_search = true;
804         pit_type const endpit = buffer.paragraphs().size();
805         for (pit_type pit = 0; pit != endpit; ++pit) {
806                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
807                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
808         }
809         return ods.str();
810 }
811
812
813 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
814 {
815         docstring str;
816         if (!opt.ignoreformat) {
817                 str = buffer_to_latex(buffer);
818         } else {
819                 OutputParams runparams(&buffer.params().encoding());
820                 runparams.nice = true;
821                 runparams.flavor = OutputParams::LATEX;
822                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
823                 runparams.dryrun = true;
824                 runparams.for_search = true;
825                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
826                         Paragraph const & par = buffer.paragraphs().at(pit);
827                         LYXERR(Debug::FIND, "Adding to search string: '"
828                                << par.asString(pos_type(0), par.size(),
829                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
830                                                &runparams)
831                                << "'");
832                         str += par.asString(pos_type(0), par.size(),
833                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
834                                             &runparams);
835                 }
836         }
837         return str;
838 }
839
840
841 /// Return separation pos between the leading material and the rest
842 static size_t identifyLeading(string const & s)
843 {
844         string t = s;
845         // @TODO Support \item[text]
846         // Kornel: Added textsl, textsf, textit, texttt and noun
847         // + allow to seach for colored text too
848         while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)\\{", "")
849                || regex_replace(t, t, REGEX_BOS "\\$", "")
850                || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
851                || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
852                || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
853                ;
854         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
855         return s.find(t);
856 }
857
858 /*
859  * Given a latexified string, retrieve some handled features
860  * The features of the regex will later be compared with the features
861  * of the searched text. If the regex features are not a
862  * subset of the analized, then, in not format ignoring search
863  * we can early stop the search in the relevant inset.
864  */
865 typedef map<string, bool> Features;
866
867 static Features identifyFeatures(string const & s)
868 {
869         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
870         static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage)\\{[a-z]+\\})|item |(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)$");
871         smatch sub;
872         bool displ = true;
873         Features info;
874
875         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
876                 sub = *it;
877                 if (displ) {
878                         if (sub.str(1).compare("regexp") == 0) {
879                                 displ = false;
880                                 continue;
881                         }
882                         string token = sub.str(1);
883                         smatch sub2;
884                         if (regex_match(token, sub2, valid)) {
885                                 info[token] = true;
886                         }
887                         else {
888                                 // ignore
889                         }
890                 }
891                 else {
892                         if (sub.str(1).compare("endregexp") == 0) {
893                                 displ = true;
894                                 continue;
895                         }
896                 }
897         }
898         return(info);
899 }
900
901 /*
902  * Faster search for the related closing parenthesis
903  */
904  static int findclosing(string p, int start, int end)
905 {
906         int skip = 0;
907         int depth = 0;
908         int lastunclosed = start-1;
909         for (int i = start; i < end; i += 1 + skip) {
910                 char c;
911                 c = p[i];
912                 skip = 0;
913                 if (c == '\\') skip = 1;
914                 else if (c == '{') {
915                   depth++;
916                   lastunclosed = i;
917                 }
918                 else if (c == '}') {
919                         if (depth == 0) return(i);
920                         --depth;
921                 }
922         }
923         return(0 - lastunclosed);
924 }
925
926 /*
927  * defines values features of a key "\\[a-z]+{"
928  */
929 class KeyInfo {
930  public:
931   enum KeyType {
932     isChar,
933     isSectioning,
934     isMain,                             /* for \\foreignlanguage */
935     isRegex,
936     isMath,
937     isStandard,
938     isSize,
939     invalid,
940     doRemove,
941     isIgnored                           /* to be ignored by creating infos */
942   };
943  KeyInfo()
944    : keytype(invalid),
945     head(""),
946     parenthesiscount(1),
947     disabled(false)
948   {};
949  KeyInfo(KeyType type, int parcount, bool disable)
950    : keytype(type),
951     parenthesiscount(parcount),
952     disabled(disable) {};
953   KeyType keytype;
954   string head;
955   int _tokensize;
956   int _tokenstart;
957   int _dataStart;
958   int _dataEnd;
959   int parenthesiscount;
960   bool disabled;
961 };
962
963 class Border {
964  public:
965  Border(int l=0, int u=0) : low(l), upper(u) {};
966   int low;
967   int upper;
968 };
969
970 #define MAXOPENED 30
971 class Intervall {
972  public:
973  Intervall() : ignoreidx(-1), actualdeptindex(0) {};
974   string par;
975   int ignoreidx;
976   int depts[MAXOPENED];
977   int closes[MAXOPENED];
978   int actualdeptindex;
979   Border borders[2*MAXOPENED];
980   // int previousNotIgnored(int);
981   int nextNotIgnored(int);
982   void handleOpenP(int i);
983   void handleCloseP(int i, bool closingAllowed);
984   void resetOpenedP(int openPos);
985   void addIntervall(int upper);
986   void addIntervall(int low, int upper); /* if explicit */
987   void setForDefaultLang(int upTo);
988   int findclosing(int start, int end);
989   void handleParentheses(int lastpos, bool closingAllowed);
990   void output(ostringstream &os, int lastpos);
991   // string show(int lastpos);
992 };
993
994 void Intervall::setForDefaultLang(int upTo)
995 {
996   // Enable the use of first token again
997   if (ignoreidx >= 0) {
998     if (borders[0].low < upTo)
999       borders[0].low = upTo;
1000     if (borders[0].upper < upTo)
1001       borders[0].upper = upTo;
1002   }
1003 }
1004
1005 static void checkDepthIndex(int val)
1006 {
1007   static int maxdepthidx = MAXOPENED-2;
1008   if (val > maxdepthidx) {
1009     maxdepthidx = val;
1010     LYXERR0("maxdepthidx now " << val);
1011   }
1012 }
1013
1014 static void checkIgnoreIdx(int val)
1015 {
1016   static int maxignoreidx = 2*MAXOPENED - 4;
1017   if (val > maxignoreidx) {
1018     maxignoreidx = val;
1019     LYXERR0("maxignoreidx now " << val);
1020   }
1021 }
1022
1023 /*
1024  * Expand the region of ignored parts of the input latex string
1025  * The region is only relevant in output()
1026  */
1027 void Intervall::addIntervall(int low, int upper)
1028 {
1029   int idx;
1030   if (low == upper) return;
1031   for (idx = ignoreidx+1; idx > 0; --idx) {
1032     if (low > borders[idx-1].upper) {
1033       break;
1034     }
1035   }
1036   Border br(low, upper);
1037   if (idx > ignoreidx) {
1038     borders[idx] = br;
1039     ignoreidx = idx;
1040     checkIgnoreIdx(ignoreidx);
1041     return;
1042   }
1043   else {
1044     // Expand only if one of the new bound is inside the interwall
1045     // We know here that br.low > borders[idx-1].upper
1046     if (br.upper < borders[idx].low) {
1047       // We have to insert at this pos
1048       for (int i = ignoreidx+1; i > idx; --i) {
1049         borders[i] = borders[i-1];
1050       }
1051       borders[idx] = br;
1052       ignoreidx += 1;
1053       checkIgnoreIdx(ignoreidx);
1054       return;
1055     }
1056     // Here we know, that we are overlapping
1057     if (br.low > borders[idx].low)
1058       br.low = borders[idx].low;
1059     // check what has to be concatenated
1060     int count = 0;
1061     for (int i = idx; i <= ignoreidx; i++) {
1062       if (br.upper >= borders[i].low) {
1063         count++;
1064         if (br.upper < borders[i].upper)
1065           br.upper = borders[i].upper;
1066       }
1067       else {
1068         break;
1069       }
1070     }
1071     // count should be >= 1 here
1072     borders[idx] = br;
1073     if (count > 1) {
1074       for (int i = idx + count; i <= ignoreidx; i++) {
1075         borders[i-count+1] = borders[i];
1076       }
1077       ignoreidx -= count - 1;
1078       return;
1079     }
1080   }
1081 }
1082
1083 void Intervall::handleOpenP(int i)
1084 {
1085   actualdeptindex++;
1086   depts[actualdeptindex] = i+1;
1087   closes[actualdeptindex] = -1;
1088   checkDepthIndex(actualdeptindex);
1089 }
1090
1091 void Intervall::handleCloseP(int i, bool closingAllowed)
1092 {
1093   if (actualdeptindex <= 0) {
1094     if (! closingAllowed)
1095       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should not happen, but the latex input may be wrong */
1096     // if we are at the very end
1097     addIntervall(i, i+1);
1098   }
1099   else {
1100     closes[actualdeptindex] = i+1;
1101     actualdeptindex--;
1102   }
1103 }
1104
1105 void Intervall::resetOpenedP(int openPos)
1106 {
1107   // Used as initializer for foreignlanguage entry
1108   actualdeptindex = 1;
1109   depts[1] = openPos+1;
1110   closes[1] = -1;
1111 }
1112
1113 #if 0
1114 int Intervall::previousNotIgnored(int start)
1115 {
1116     int idx = 0;                          /* int intervalls */
1117     for (idx = ignoreidx; idx >= 0; --idx) {
1118       if (start > borders[idx].upper)
1119         return(start);
1120       if (start >= borders[idx].low)
1121         start = borders[idx].low-1;
1122     }
1123     return start;
1124 }
1125 #endif
1126
1127 int Intervall::nextNotIgnored(int start)
1128 {
1129     int idx = 0;                          /* int intervalls */
1130     for (idx = 0; idx <= ignoreidx; idx++) {
1131       if (start < borders[idx].low)
1132         return(start);
1133       if (start < borders[idx].upper)
1134         start = borders[idx].upper;
1135     }
1136     return start;
1137 }
1138
1139 typedef map<string, KeyInfo> KeysMap;
1140 typedef vector< KeyInfo> Entries;
1141 static KeysMap keys = map<string, KeyInfo>();
1142
1143 class LatexInfo {
1144  private:
1145   int entidx;
1146   Entries entries;
1147   KeyInfo analyze(string key);
1148   Intervall interval;
1149   void buildKeys();
1150   void buildEntries();
1151   void makeKey(const string &, KeyInfo);
1152   void processRegion(int start, int region_end); /*  remove {} parts */
1153   void removeHead(KeyInfo&, int count=0);
1154  public:
1155  LatexInfo(string par) {
1156     interval.par = par;
1157     buildKeys();
1158     entries = vector<KeyInfo>();
1159     buildEntries();
1160   };
1161   int getFirstKey() {
1162     entidx = 0;
1163     if (entries.empty()) {
1164       return (-1);
1165     }
1166     return 0;
1167   };
1168   int getNextKey() {
1169     entidx++;
1170     if (int(entries.size()) > entidx) {
1171       return entidx;
1172     }
1173     else {
1174       return (-1);
1175     }
1176   };
1177   bool setNextKey(int idx) {
1178     if ((idx == entidx) && (entidx >= 0)) {
1179       entidx--;
1180       return true;
1181     }
1182     else
1183       return(false);
1184   };
1185   int process(ostringstream &os, KeyInfo &actual);
1186   int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
1187   // string show(int lastpos) { return interval.show(lastpos);};
1188   int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1189   KeyInfo &getKeyInfo(int keyinfo) {
1190     static KeyInfo invalidInfo = KeyInfo();
1191     if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1192       return invalidInfo;
1193     else
1194       return entries[keyinfo];
1195   };
1196   void setForDefaultLang(int upTo) {interval.setForDefaultLang(upTo);};
1197
1198 };
1199
1200
1201 int Intervall::findclosing(int start, int end)
1202 {
1203   int skip = 0;
1204   int depth = 0;
1205   for (int i = start; i < end; i += 1 + skip) {
1206     char c;
1207     c = par[i];
1208     skip = 0;
1209     if (c == '\\') skip = 1;
1210     else if (c == '{') {
1211       depth++;
1212     }
1213     else if (c == '}') {
1214       if (depth == 0) return(i);
1215       --depth;
1216     }
1217   }
1218   return(end);
1219 }
1220
1221 void LatexInfo::buildEntries()
1222 {
1223   static regex const rmath("\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multiline|align)\\*?)\\}");
1224   static regex const rkeys("\\\\((([a-z]+\\*?)(\\{([a-z]+)\\})?))([\\{ ])");
1225   smatch sub, submath;
1226   bool evaluatingRegexp = false;
1227   KeyInfo found;
1228   bool math_end_waiting = false;
1229   size_t math_pos = 10000;
1230   int math_size = 0;
1231   int math_end_pos = -1;
1232   string math_end;
1233
1234   for (sregex_iterator itmath(interval.par.begin(), interval.par.end(), rmath), end; itmath != end; ++itmath) {
1235     submath = *itmath;
1236     if (math_end_waiting) {
1237       if ((submath.str(1).compare("end") == 0) &&
1238           (submath.str(2).compare(math_end) == 0)) {
1239         math_size = submath.position(0) + submath.str(0).length() - math_pos;
1240         math_end_waiting = false;
1241       }
1242     }
1243     else {
1244       if (submath.str(1).compare("begin") == 0) {
1245         math_end_waiting = true;
1246         math_end = submath.str(2);
1247         math_pos = submath.position(0);
1248       }
1249     }
1250   }
1251   for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1252     sub = *it;
1253     if (evaluatingRegexp) {
1254       if (sub.str(1).compare("endregexp") == 0) {
1255         evaluatingRegexp = false;
1256         // found._tokenstart already set
1257         found._dataEnd = sub.position(0) + 13;
1258         found._dataStart = found._dataEnd;
1259         found._tokensize = found._dataEnd - found._tokenstart;
1260         found.parenthesiscount = 0;
1261       }
1262     }
1263     else {
1264       if (keys.find(sub.str(3)) == keys.end()) {
1265         LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1266         continue;
1267       }
1268       found = keys[sub.str(3)];
1269       if (sub.str(3).compare("regexp") == 0) {
1270         evaluatingRegexp = true;
1271         found._tokenstart = sub.position(0);
1272         found._tokensize = 0;
1273         continue;
1274       }
1275     }
1276     // Handle the other params of key
1277     if (found.keytype == KeyInfo::isIgnored)
1278       continue;
1279     else if (found.keytype == KeyInfo::isMath) {
1280       if (size_t(sub.position(0)) == math_pos) {
1281         found = keys[sub.str(3)];
1282         found._tokenstart = sub.position(0);
1283         found._tokensize = math_size;
1284         found._dataEnd = found._tokenstart + found._tokensize;
1285         found._dataStart = found._dataEnd;
1286         found.parenthesiscount = 0;
1287         math_end_pos = found._dataEnd;
1288       }
1289       else
1290         continue;
1291     }
1292     else if (found.keytype != KeyInfo::isRegex) {
1293       found._tokenstart = sub.position(0);
1294       if (found._tokenstart < math_end_pos) {
1295         // Ignore if we are inside math equation
1296         continue;
1297       }
1298       if (found.parenthesiscount == 0) {
1299         // Probably to be discarded
1300         if (interval.par[sub.position(0) + sub.str(3).length()] == ' ')
1301           found.head = "\\" + sub.str(3) + " ";
1302         else
1303           found.head = "\\" + sub.str(3);
1304         found._tokensize = found.head.length();
1305         found._dataEnd = found._tokenstart + found._tokensize;
1306         found._dataStart = found._dataEnd;
1307       }
1308       else {
1309         if (found.parenthesiscount == 1) {
1310           found.head = "\\" + sub.str(3) + "{";
1311         }
1312         else if (found.parenthesiscount == 2) {
1313           found.head = sub.str(0);
1314           found._tokensize = found.head.length();
1315         }
1316         found._tokensize = found.head.length();
1317         found._dataStart = found._tokenstart + found.head.length();
1318         found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1319       }
1320     }
1321     entries.push_back(found);
1322   }
1323 }
1324
1325 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI)
1326 {
1327   stringstream s(keysstring);
1328   string key;
1329   KeyInfo keyII(keyI);
1330   const char delim = '|';
1331   while (getline(s, key, delim)) {
1332     keys[key] = keyII;
1333   }
1334 }
1335
1336 void LatexInfo::buildKeys()
1337 {
1338   static bool keysBuilt        = false;
1339   static bool ignoreFamily     = false;
1340   static bool ignoreSeries     = false;
1341   static bool ignoreShape      = false;
1342   static bool ignoreUnderline  = false;
1343   static bool ignoreMarkUp     = false;
1344   static bool ignoreStrikeOut  = false;
1345   static bool ignoreSectioning = false;
1346   static bool ignoreColor      = false;
1347   static bool ignoreLanguage   = false;
1348
1349   if (keysBuilt) return;
1350
1351   // Know statdard keys with 1 parameter.
1352   // Split is done, if not at start of region
1353   makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFamily));
1354   makeKey("textbf",               KeyInfo(KeyInfo::isStandard, 1, ignoreSeries));
1355   makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreShape));
1356   makeKey("uuline|uline|uwave",   KeyInfo(KeyInfo::isStandard, 1, ignoreUnderline));
1357   makeKey("emph|noun",            KeyInfo(KeyInfo::isStandard, 1, ignoreMarkUp));
1358   makeKey("sout|xout",            KeyInfo(KeyInfo::isStandard, 1, ignoreStrikeOut));
1359
1360
1361   makeKey("section|subsection|subsubsection|paragraph|subparagraph",
1362           KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1363   makeKey("section*|subsection*|subsubsection*",
1364           KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1365   makeKey("title|part|part*", KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1366
1367   // Regex
1368   makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false));
1369
1370   // Split is done, if not at start of region
1371   makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreColor));
1372
1373   // Split is done always.
1374   makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreLanguage));
1375
1376   // Know charaters
1377   // No split
1378   makeKey("backslash|textbackslash", KeyInfo(KeyInfo::isChar, 1, false));
1379
1380   // Known macros to remove (including their parameter)
1381   // No split
1382   makeKey("inputencoding|shortcut", KeyInfo(KeyInfo::doRemove, 1, false));
1383
1384   // Macros to remove, but let the parameter survive
1385   // No split
1386   makeKey("url|href|menuitem|footnote|code", KeyInfo(KeyInfo::isStandard, 1, true));
1387
1388   // Same effect as previous, parameter will survive (because there is no one anyway)
1389   // No split
1390   makeKey("noindent", KeyInfo(KeyInfo::isStandard, 0, true));
1391   // like (tiny{} ... }
1392   makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, true));
1393
1394   // Survives, like known character
1395   makeKey("lyx", KeyInfo(KeyInfo::isIgnored, 0, false));
1396
1397   makeKey("begin", KeyInfo(KeyInfo::isMath, 1, false));
1398
1399   keysBuilt = true;
1400 }
1401
1402 /*
1403  * Keep the list of actual opened parentheses actual
1404  * (e.g. depth == 4 means there are 4 '{' not processed yet)
1405  */
1406 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1407 {
1408   int skip = 0;
1409   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1410     char c;
1411     c = par[i];
1412     skip = 0;
1413     if (c == '\\') skip = 1;
1414     else if (c == '{') {
1415       handleOpenP(i);
1416     }
1417     else if (c == '}') {
1418       handleCloseP(i, closingAllowed);
1419     }
1420   }
1421 }
1422
1423 #if (0)
1424 string Intervall::show(int lastpos)
1425 {
1426   int idx = 0;                          /* int intervalls */
1427   int count = 0;
1428   string s;
1429   int i = 0;
1430   for (idx = 0; idx <= ignoreidx; idx++) {
1431     while (i < lastpos) {
1432       int printsize;
1433       if (i <= borders[idx].low) {
1434         if (borders[idx].low > lastpos)
1435           printsize = lastpos - i;
1436         else
1437           printsize = borders[idx].low - i;
1438         s += par.substr(i, printsize);
1439         i += printsize;
1440         if (i >= borders[idx].low)
1441           i = borders[idx].upper;
1442       }
1443       else {
1444         i = borders[idx].upper;
1445         break;
1446       }
1447     }
1448   }
1449   if (lastpos > i) {
1450     s += par.substr(i, lastpos-i);
1451   }
1452   return (s);
1453 }
1454 #endif
1455
1456 void Intervall::output(ostringstream &os, int lastpos)
1457 {
1458   // get number of chars to output
1459   int idx = 0;                          /* int intervalls */
1460   int i = 0;
1461   for (idx = 0; idx <= ignoreidx; idx++) {
1462     if (i < lastpos) {
1463       int printsize;
1464       if (i <= borders[idx].low) {
1465         if (borders[idx].low > lastpos)
1466           printsize = lastpos - i;
1467         else
1468           printsize = borders[idx].low - i;
1469         os << par.substr(i, printsize);
1470         i += printsize;
1471         handleParentheses(i, false);
1472         if (i >= borders[idx].low)
1473           i = borders[idx].upper;
1474       }
1475       else {
1476         i = borders[idx].upper;
1477       }
1478     }
1479     else
1480       break;
1481   }
1482   if (lastpos > i) {
1483     os << par.substr(i, lastpos-i);
1484   }
1485   handleParentheses(lastpos, false);
1486   for (int i = actualdeptindex; i > 0; --i) {
1487     os << "}";
1488   }
1489   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1490 }
1491
1492 void LatexInfo::processRegion(int start, int region_end)
1493 {
1494   while (start < region_end) {
1495     if (interval.par[start] == '{') {
1496       int closing = interval.findclosing(start+1, region_end);
1497       interval.addIntervall(start, start+1);
1498       interval.addIntervall(closing, closing+1);
1499     }
1500     start = interval.nextNotIgnored(start+1);
1501   }
1502 }
1503
1504 void LatexInfo::removeHead(KeyInfo &actual, int count)
1505 {
1506   if (actual.parenthesiscount == 0) {
1507     // "{\tiny{} ...}" ==> "{{} ...}"
1508     interval.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
1509   }
1510   else {
1511     // Remove header hull, that is "\url{abcd}" ==> "abcd"
1512     interval.addIntervall(actual._tokenstart, actual._dataStart);
1513     interval.addIntervall(actual._dataEnd, actual._dataEnd+1);
1514   }
1515 }
1516
1517 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
1518 {
1519   int nextKeyIdx;
1520   switch (actual.keytype)
1521     {
1522     case KeyInfo::isChar: {
1523       nextKeyIdx = getNextKey();
1524       break;
1525     }
1526     case KeyInfo::isSize: {
1527       if (actual.disabled) {
1528         // Allways disabled
1529         processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
1530         interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1531         nextKeyIdx = getNextKey();
1532       } else {
1533         // Split on this key if not at start
1534         int start = interval.nextNotIgnored(previousStart);
1535         if (start < actual._tokenstart) {
1536           interval.output(os, actual._tokenstart);
1537           interval.addIntervall(start, actual._tokenstart);
1538         }
1539         // discard entry if at end of actual
1540         nextKeyIdx = process(os, actual);
1541       }
1542       break;
1543     }
1544     case KeyInfo::isStandard: {
1545       if (actual.disabled) {
1546         removeHead(actual);
1547         processRegion(actual._dataStart, actual._dataStart+1);
1548         nextKeyIdx = getNextKey();
1549       } else {
1550         // Split on this key if not at start
1551         int start = interval.nextNotIgnored(previousStart);
1552         if (start < actual._tokenstart) {
1553           interval.output(os, actual._tokenstart);
1554           interval.addIntervall(start, actual._tokenstart);
1555         }
1556         // discard entry if at end of actual
1557         nextKeyIdx = process(os, actual);
1558       }
1559       break;
1560     }
1561     case KeyInfo::doRemove: {
1562       // Remove the key with all parameters
1563       interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1564       nextKeyIdx = getNextKey();
1565       break;
1566     }
1567     case KeyInfo::isSectioning: {
1568       // Discard space before _tokenstart
1569       int count;
1570       for (count = 0; count < actual._tokenstart; count++) {
1571         if (interval.par[actual._tokenstart-count-1] != ' ')
1572           break;
1573       }
1574       if (actual.disabled) {
1575         removeHead(actual, count);
1576         nextKeyIdx = getNextKey();
1577       } else {
1578         interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1579         nextKeyIdx = process(os, actual);
1580       }
1581       break;
1582     }
1583     case KeyInfo::isMath: {
1584       // Same as regex, use the content unchanged
1585       nextKeyIdx = getNextKey();
1586       break;
1587     }
1588     case KeyInfo::isRegex: {
1589       // DO NOT SPLIT ON REGEX
1590       // Do not disable
1591       nextKeyIdx = getNextKey();
1592       break;
1593     }
1594     case KeyInfo::isIgnored: {
1595       // Treat like a character for now
1596       nextKeyIdx = getNextKey();
1597       break;
1598     }
1599     case KeyInfo::isMain: {
1600       if (actual.disabled) {
1601         removeHead(actual);
1602         interval.resetOpenedP(actual._dataStart-1);
1603       }
1604       else {
1605         if (actual._tokenstart == 0) {
1606           // for the first (and maybe dummy) language
1607           interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1608         }
1609         interval.resetOpenedP(actual._dataStart-1);
1610       }
1611       break;
1612     }
1613     case KeyInfo::invalid:
1614       // This cannot happen, already handled
1615       // fall through
1616     default: {
1617       // LYXERR0("Unhandled keytype");
1618       nextKeyIdx = getNextKey();
1619       break;
1620     }
1621     }
1622   return(nextKeyIdx);
1623 }
1624
1625 int LatexInfo::process(ostringstream &os, KeyInfo &actual )
1626 {
1627   int end = interval.nextNotIgnored(actual._dataEnd);
1628   int oldStart = actual._dataStart;
1629   int nextKeyIdx = getNextKey();
1630   while (true) {
1631     if ((nextKeyIdx < 0) ||
1632         (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1633         (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1634       if (oldStart <= end) {
1635         processRegion(oldStart, end);
1636         oldStart = end+1;
1637       }
1638       break;
1639     }
1640     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1641
1642     if (nextKey.keytype == KeyInfo::isMain) {
1643       (void) dispatch(os, actual._dataStart, nextKey);
1644       end = nextKey._tokenstart;
1645       break;
1646     }
1647     processRegion(oldStart, nextKey._tokenstart);
1648     nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
1649
1650     oldStart = nextKey._dataEnd+1;
1651   }
1652   // now nextKey is either invalid or is outside of actual._dataEnd
1653   // output the remaining and discard myself
1654   if (oldStart <= end) {
1655     processRegion(oldStart, end);
1656   }
1657   if (interval.par[end] == '}') {
1658     end += 1;
1659     // This is the normal case.
1660     // But if using the firstlanguage, the closing may be missing
1661   }
1662   // get minimum of 'end' and  'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
1663   int output_end;
1664   if (actual._dataEnd < end)
1665     output_end = interval.nextNotIgnored(actual._dataEnd);
1666   else
1667     output_end = interval.nextNotIgnored(end);
1668   if (interval.nextNotIgnored(actual._dataStart) < output_end)
1669     interval.output(os, output_end);
1670   interval.addIntervall(actual._tokenstart, end);
1671   return nextKeyIdx;
1672 }
1673
1674 string splitOnKnownMacros(string par) {
1675   ostringstream os;
1676   LatexInfo li(par);
1677   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
1678   DummyKey.head="";
1679   DummyKey._tokensize = 0;
1680   DummyKey._tokenstart = 0;
1681   DummyKey._dataStart = 0;
1682   DummyKey._dataEnd = par.length();
1683   DummyKey.disabled = true;
1684   int firstkeyIdx = li.getFirstKey();
1685   string s;
1686   if (firstkeyIdx >= 0) {
1687     KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
1688     int nextkeyIdx;
1689     if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
1690       // Create dummy firstKey
1691       firstKey = DummyKey;
1692       (void) li.setNextKey(firstkeyIdx);
1693     }
1694     nextkeyIdx = li.process(os, firstKey);
1695     while (nextkeyIdx >= 0) {
1696       // Check for a possible gap between the last
1697       // entry and this one
1698       int datastart = li.nextNotIgnored(firstKey._dataStart);
1699       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1700       if ((nextKey._tokenstart > datastart)) {
1701         // Handle the gap
1702         firstKey._dataStart = datastart;
1703         firstKey._dataEnd = par.length();
1704         (void) li.setNextKey(nextkeyIdx);
1705         if (firstKey._tokensize > 0)
1706           li.setForDefaultLang(firstKey._tokensize);
1707         // Fake the last opened parenthesis
1708         nextkeyIdx = li.process(os, firstKey);
1709       }
1710       else {
1711         if (nextKey.keytype != KeyInfo::isMain) {
1712           firstKey._dataStart = datastart;
1713           firstKey._dataEnd = nextKey._dataEnd+1;
1714           (void) li.setNextKey(nextkeyIdx);
1715           if (firstKey._tokensize > 0)
1716             li.setForDefaultLang(firstKey._tokensize);
1717           nextkeyIdx = li.process(os, firstKey);
1718         }
1719         else {
1720           nextkeyIdx = li.process(os, nextKey);
1721         }
1722       }
1723     }
1724     // Handle the remaining
1725     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1726     firstKey._dataEnd = par.length();
1727     if (firstKey._dataStart < firstKey._dataEnd)
1728       (void) li.process(os, firstKey);
1729     s = os.str();
1730   }
1731   else
1732     s = "";                        /* found end */
1733   return s;
1734 }
1735
1736 /*
1737  * Try to unify the language specs in the latexified text.
1738  * Resulting modified string is set to "", if
1739  * the searched tex does not contain all the features in the search pattern
1740  */
1741 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1742 {
1743         static Features regex_f;
1744         static int missed = 0;
1745         static bool regex_with_format = false;
1746
1747         int parlen = par.length();
1748
1749         while ((parlen > 0) && (par[parlen-1] == '\n')) {
1750                 parlen--;
1751         }
1752         string result;
1753         if (withformat) {
1754                 // Split the latex input into pieces which
1755                 // can be digested by our search engine
1756                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1757                 result = splitOnKnownMacros(par);
1758                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1759         }
1760         else
1761                 result = par.substr(0, parlen);
1762         bool handle_colors = false;
1763         if (from_regex) {
1764                 missed = 0;
1765                 if (withformat) {
1766                         regex_f = identifyFeatures(result);
1767                         string features = "";
1768                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1769                                 string a = it->first;
1770                                 regex_with_format = true;
1771                                 if (a.compare(0,10,"textcolor{") == 0)
1772                                   handle_colors = true;
1773                                 features += " " + a;
1774                                 // LYXERR0("Identified regex format:" << a);
1775                         }
1776                         LYXERR(Debug::FIND, "Identified Features" << features);
1777
1778                 }
1779         } else if (regex_with_format) {
1780                 Features info = identifyFeatures(result);
1781                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1782                         string a = it->first;
1783                         bool b = it->second;
1784                         if (b && ! info[a]) {
1785                                 missed++;
1786                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1787                                 return("");
1788                         }
1789                         else if (a.compare(0,10,"textcolor{") == 0)
1790                                 handle_colors = true;
1791                 }
1792         }
1793         else {
1794                 // LYXERR0("No regex formats");
1795         }
1796         // remove possible disturbing macros
1797         while (regex_replace(result, result, "\\\\(noindent )", ""))
1798                 ;
1799         // Either not found language spec,or is single and closed spec or empty
1800         // to be removed
1801         // [a-z+]par
1802         static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1803
1804         list <string> pars;
1805         smatch sub;
1806         for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1807                 sub = *it;
1808                 string token = sub.str(1);
1809                 pars.push_back(token);
1810         }
1811         for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1812                 string token = *li;
1813                 int ti = result.find(token);
1814                 int tokensize = token.size() + 1;
1815                 if (ti >= 0) {
1816                         int tc = findclosing(result, ti + tokensize, result.size());
1817                         if (tc > 0)
1818                                 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1819
1820                 }
1821         }
1822         if (handle_colors) {
1823           while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1824           while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1825         }
1826         return(result);
1827 }
1828
1829
1830 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1831 static int identifyClosing(string & t)
1832 {
1833         int open_braces = 0;
1834         do {
1835                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1836                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1837                         continue;
1838                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1839                         continue;
1840                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1841                         continue;
1842                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1843                         ++open_braces;
1844                         continue;
1845                 }
1846                 break;
1847         } while (true);
1848         return open_braces;
1849 }
1850
1851
1852 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1853         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1854 {
1855         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1856         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1857         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1858         // When using regexp, braces are hacked already by escape_for_regex()
1859         par_as_string = normalize(ds, !use_regexp);
1860         open_braces = 0;
1861         close_wildcards = 0;
1862
1863         size_t lead_size = 0;
1864         // correct the language settings
1865         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1866         if (opt.ignoreformat) {
1867                 if (!use_regexp) {
1868                         // if par_as_string_nolead were emty,
1869                         // the following call to findAux will always *find* the string
1870                         // in the checked data, and thus always using the slow
1871                         // examining of the current text part.
1872                         par_as_string_nolead = par_as_string;
1873                 }
1874         } else {
1875                 lead_size = identifyLeading(par_as_string);
1876                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1877                 lead_as_string = par_as_string.substr(0, lead_size);
1878                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1879         }
1880
1881         if (!use_regexp) {
1882                 open_braces = identifyClosing(par_as_string);
1883                 identifyClosing(par_as_string_nolead);
1884                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1885                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1886         } else {
1887                 string lead_as_regexp;
1888                 if (lead_size > 0) {
1889                         // @todo No need to search for \regexp{} insets in leading material
1890                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1891                         par_as_string = par_as_string_nolead;
1892                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1893                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1894                 }
1895                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1896                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1897                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1898                 if (
1899                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1900                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1901                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1902                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1903                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1904                         || regex_replace(par_as_string, par_as_string,
1905                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1906                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1907                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1908                         ) {
1909                         ++close_wildcards;
1910                 }
1911                 if (!opt.ignoreformat) {
1912                         // Remove extra '\}' at end
1913                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1914                                 open_braces++;
1915                         }
1916                         // save '\.'
1917                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1918                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1919                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1920                         // replace '[^...]' with '[^...\}\{\\]'
1921                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1922                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1923                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1924                         // restore '\.'
1925                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1926                 }
1927                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1928                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1929                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
1930                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1931
1932                 // If entered regexp must match at begin of searched string buffer
1933                 // Kornel: Added parentheses to use $1 for size of the leading string
1934                 string regexp_str;
1935                 string regexp2_str;
1936                 {
1937                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1938                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
1939                         // so the convert has no effect in that case
1940                         for (int i = 8; i > 0; --i) {
1941                                 string orig = "\\\\" + std::to_string(i);
1942                                 string dest = "\\" + std::to_string(i+1);
1943                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
1944                         }
1945                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1946                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1947                 }
1948                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1949                 regexp = lyx::regex(regexp_str);
1950
1951                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1952                 regexp2 = lyx::regex(regexp2_str);
1953         }
1954 }
1955
1956
1957 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1958 {
1959         if (at_begin &&
1960                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1961                 return 0;
1962
1963         docstring docstr = stringifyFromForSearch(opt, cur, len);
1964         string str = normalize(docstr, true);
1965         if (!opt.ignoreformat) {
1966                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
1967         }
1968         if (str.empty()) return(-1);
1969         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
1970         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1971
1972         if (use_regexp) {
1973                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1974                 regex const *p_regexp;
1975                 regex_constants::match_flag_type flags;
1976                 if (at_begin) {
1977                         flags = regex_constants::match_continuous;
1978                         p_regexp = &regexp;
1979                 } else {
1980                         flags = regex_constants::match_default;
1981                         p_regexp = &regexp2;
1982                 }
1983                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1984                 if (re_it == sregex_iterator())
1985                         return 0;
1986                 match_results<string::const_iterator> const & m = *re_it;
1987
1988                 if (0) { // Kornel Benko: DO NOT CHECKK
1989                         // Check braces on the segment that matched the entire regexp expression,
1990                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
1991                         if (!braces_match(m[0].first, m[0].second, open_braces))
1992                                 return 0;
1993                 }
1994
1995                 // Check braces on segments that matched all (.*?) subexpressions,
1996                 // except the last "padding" one inserted by lyx.
1997                 for (size_t i = 1; i < m.size() - 1; ++i)
1998                         if (!braces_match(m[i].first, m[i].second, open_braces))
1999                                 return 0;
2000
2001                 // Exclude from the returned match length any length
2002                 // due to close wildcards added at end of regexp
2003                 // and also the length of the leading (e.g. '\emph{')
2004                 //
2005                 // Whole found string, including the leading: m[0].second - m[0].first
2006                 // Size of the leading string: m[1].second - m[1].first
2007                 int leadingsize = 0;
2008                 if (m.size() > 1)
2009                         leadingsize = m[1].second - m[1].first;
2010                 int result;
2011                 for (size_t i = 0; i < m.size(); i++) {
2012                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2013                 }
2014                 if (close_wildcards == 0)
2015                         result = m[0].second - m[0].first;
2016
2017                 else
2018                         result =  m[m.size() - close_wildcards].first - m[0].first;
2019
2020                 if (result > leadingsize)
2021                         result -= leadingsize;
2022                 else
2023                         result = 0;
2024                 return(result);
2025         }
2026
2027         // else !use_regexp: but all code paths above return
2028         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2029                                  << par_as_string << "', str='" << str << "'");
2030         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2031                                  << lead_as_string << "', par_as_string_nolead='"
2032                                  << par_as_string_nolead << "'");
2033
2034         if (at_begin) {
2035                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2036                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2037                 if (str.substr(0, par_as_string.size()) == par_as_string)
2038                         return par_as_string.size();
2039         } else {
2040                 size_t pos = str.find(par_as_string_nolead);
2041                 if (pos != string::npos)
2042                         return par_as_string.size();
2043         }
2044         return 0;
2045 }
2046
2047
2048 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
2049 {
2050         int res = findAux(cur, len, at_begin);
2051         LYXERR(Debug::FIND,
2052                "res=" << res << ", at_begin=" << at_begin
2053                << ", matchword=" << opt.matchword
2054                << ", inTexted=" << cur.inTexted());
2055         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
2056                 return res;
2057         Paragraph const & par = cur.paragraph();
2058         bool ws_left = (cur.pos() > 0)
2059                 ? par.isWordSeparator(cur.pos() - 1)
2060                 : true;
2061         bool ws_right = (cur.pos() + res < par.size())
2062                 ? par.isWordSeparator(cur.pos() + res)
2063                 : true;
2064         LYXERR(Debug::FIND,
2065                "cur.pos()=" << cur.pos() << ", res=" << res
2066                << ", separ: " << ws_left << ", " << ws_right
2067                << endl);
2068         if (ws_left && ws_right)
2069                 return res;
2070         return 0;
2071 }
2072
2073
2074 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
2075 {
2076         string t;
2077         if (! opt.casesensitive)
2078                 t = lyx::to_utf8(lowercase(s));
2079         else
2080                 t = lyx::to_utf8(s);
2081         // Remove \n at begin
2082         while (!t.empty() && t[0] == '\n')
2083                 t = t.substr(1);
2084         // Remove \n at end
2085         while (!t.empty() && t[t.size() - 1] == '\n')
2086                 t = t.substr(0, t.size() - 1);
2087         size_t pos;
2088         // Replace all other \n with spaces
2089         while ((pos = t.find("\n")) != string::npos)
2090                 t.replace(pos, 1, " ");
2091         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
2092         // Kornel: Added textsl, textsf, textit, texttt and noun
2093         // + allow to seach for colored text too
2094         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
2095         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
2096                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2097         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
2098                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2099
2100         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
2101         // FIXME - check what preceeds the brace
2102         if (hack_braces) {
2103                 if (opt.ignoreformat)
2104                         while (regex_replace(t, t, "\\{", "_x_<")
2105                                || regex_replace(t, t, "\\}", "_x_>"))
2106                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2107                 else
2108                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
2109                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
2110                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2111         }
2112
2113         return t;
2114 }
2115
2116
2117 docstring stringifyFromCursor(DocIterator const & cur, int len)
2118 {
2119         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2120         if (cur.inTexted()) {
2121                 Paragraph const & par = cur.paragraph();
2122                 // TODO what about searching beyond/across paragraph breaks ?
2123                 // TODO Try adding a AS_STR_INSERTS as last arg
2124                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2125                         int(par.size()) : cur.pos() + len;
2126                 OutputParams runparams(&cur.buffer()->params().encoding());
2127                 runparams.nice = true;
2128                 runparams.flavor = OutputParams::LATEX;
2129                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2130                 // No side effect of file copying and image conversion
2131                 runparams.dryrun = true;
2132                 LYXERR(Debug::FIND, "Stringifying with cur: "
2133                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
2134                 return par.asString(cur.pos(), end,
2135                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2136                         &runparams);
2137         } else if (cur.inMathed()) {
2138                 docstring s;
2139                 CursorSlice cs = cur.top();
2140                 MathData md = cs.cell();
2141                 MathData::const_iterator it_end =
2142                         (( len == -1 || cs.pos() + len > int(md.size()))
2143                          ? md.end()
2144                          : md.begin() + cs.pos() + len );
2145                 for (MathData::const_iterator it = md.begin() + cs.pos();
2146                      it != it_end; ++it)
2147                         s = s + asString(*it);
2148                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2149                 return s;
2150         }
2151         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2152         return docstring();
2153 }
2154
2155
2156 /** Computes the LaTeX export of buf starting from cur and ending len positions
2157  * after cur, if len is positive, or at the paragraph or innermost inset end
2158  * if len is -1.
2159  */
2160 docstring latexifyFromCursor(DocIterator const & cur, int len)
2161 {
2162         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2163         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2164                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2165         Buffer const & buf = *cur.buffer();
2166
2167         odocstringstream ods;
2168         otexstream os(ods);
2169         OutputParams runparams(&buf.params().encoding());
2170         runparams.nice = false;
2171         runparams.flavor = OutputParams::LATEX;
2172         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2173         // No side effect of file copying and image conversion
2174         runparams.dryrun = true;
2175         runparams.for_search = true;
2176
2177         if (cur.inTexted()) {
2178                 // @TODO what about searching beyond/across paragraph breaks ?
2179                 pos_type endpos = cur.paragraph().size();
2180                 if (len != -1 && endpos > cur.pos() + len)
2181                         endpos = cur.pos() + len;
2182                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2183                           string(), cur.pos(), endpos);
2184                 string s = lyx::to_utf8(ods.str());
2185                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2186                 return(lyx::from_utf8(s));
2187         } else if (cur.inMathed()) {
2188                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2189                 for (int s = cur.depth() - 1; s >= 0; --s) {
2190                         CursorSlice const & cs = cur[s];
2191                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2192                                 WriteStream ws(os);
2193                                 cs.asInsetMath()->asHullInset()->header_write(ws);
2194                                 break;
2195                         }
2196                 }
2197
2198                 CursorSlice const & cs = cur.top();
2199                 MathData md = cs.cell();
2200                 MathData::const_iterator it_end =
2201                         ((len == -1 || cs.pos() + len > int(md.size()))
2202                          ? md.end()
2203                          : md.begin() + cs.pos() + len);
2204                 for (MathData::const_iterator it = md.begin() + cs.pos();
2205                      it != it_end; ++it)
2206                         ods << asString(*it);
2207
2208                 // Retrieve the math environment type, and add '$' or '$]'
2209                 // or others (\end{equation}) accordingly
2210                 for (int s = cur.depth() - 1; s >= 0; --s) {
2211                         CursorSlice const & cs2 = cur[s];
2212                         InsetMath * inset = cs2.asInsetMath();
2213                         if (inset && inset->asHullInset()) {
2214                                 WriteStream ws(os);
2215                                 inset->asHullInset()->footer_write(ws);
2216                                 break;
2217                         }
2218                 }
2219                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2220         } else {
2221                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2222         }
2223         return ods.str();
2224 }
2225
2226
2227 /** Finalize an advanced find operation, advancing the cursor to the innermost
2228  ** position that matches, plus computing the length of the matching text to
2229  ** be selected
2230  **/
2231 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2232 {
2233         // Search the foremost position that matches (avoids find of entire math
2234         // inset when match at start of it)
2235         size_t d;
2236         DocIterator old_cur(cur.buffer());
2237         do {
2238                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2239                 d = cur.depth();
2240                 old_cur = cur;
2241                 cur.forwardPos();
2242         } while (cur && cur.depth() > d && match(cur) > 0);
2243         cur = old_cur;
2244         if (match(cur) <= 0) return 0;
2245         LYXERR(Debug::FIND, "Ok");
2246
2247         // Compute the match length
2248         int len = 1;
2249         if (cur.pos() + len > cur.lastpos())
2250                 return 0;
2251         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2252         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2253                 ++len;
2254                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2255         }
2256         // Length of matched text (different from len param)
2257         int old_len = match(cur, len);
2258         if (old_len < 0) old_len = 0;
2259         int new_len;
2260         // Greedy behaviour while matching regexps
2261         while ((new_len = match(cur, len + 1)) > old_len) {
2262                 ++len;
2263                 old_len = new_len;
2264                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
2265         }
2266         return len;
2267 }
2268
2269
2270 /// Finds forward
2271 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2272 {
2273         if (!cur)
2274                 return 0;
2275         while (!theApp()->longOperationCancelled() && cur) {
2276                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2277                 int match_len = match(cur, -1, false);
2278                 LYXERR(Debug::FIND, "match_len: " << match_len);
2279                 if (match_len > 0) {
2280                         int match_len_zero_count = 0;
2281                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2282                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2283                                 int match_len2 = match(cur);
2284                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2285                                 if (match_len2 > 0) {
2286                                         // Sometimes in finalize we understand it wasn't a match
2287                                         // and we need to continue the outest loop
2288                                         int len = findAdvFinalize(cur, match);
2289                                         if (len > 0) {
2290                                                 return len;
2291                                         }
2292                                 }
2293                                 if (match_len2 >= 0) {
2294                                         if (match_len2 == 0)
2295                                                 match_len_zero_count++;
2296                                         else
2297                                                 match_len_zero_count = 0;
2298                                 }
2299                                 else {
2300                                         if (++match_len_zero_count > 3) {
2301                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2302                                                 match_len_zero_count = 0;
2303                                         }
2304                                         break;
2305                                 }
2306                         }
2307                         if (!cur)
2308                                 return 0;
2309                 }
2310                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2311                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2312                         cur.forwardPar();
2313                 } else {
2314                         // This should exit nested insets, if any, or otherwise undefine the currsor.
2315                         cur.pos() = cur.lastpos();
2316                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2317                         cur.forwardPos();
2318                 }
2319         }
2320         return 0;
2321 }
2322
2323
2324 /// Find the most backward consecutive match within same paragraph while searching backwards.
2325 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2326 {
2327         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2328         DocIterator tmp_cur = cur;
2329         int len = findAdvFinalize(tmp_cur, match);
2330         Inset & inset = cur.inset();
2331         for (; cur != cur_begin; cur.backwardPos()) {
2332                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2333                 DocIterator new_cur = cur;
2334                 new_cur.backwardPos();
2335                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2336                         break;
2337                 int new_len = findAdvFinalize(new_cur, match);
2338                 if (new_len == len)
2339                         break;
2340                 len = new_len;
2341         }
2342         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2343         return len;
2344 }
2345
2346
2347 /// Finds backwards
2348 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2349 {
2350         if (! cur)
2351                 return 0;
2352         // Backup of original position
2353         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2354         if (cur == cur_begin)
2355                 return 0;
2356         cur.backwardPos();
2357         DocIterator cur_orig(cur);
2358         bool pit_changed = false;
2359         do {
2360                 cur.pos() = 0;
2361                 bool found_match = match(cur, -1, false);
2362
2363                 if (found_match) {
2364                         if (pit_changed)
2365                                 cur.pos() = cur.lastpos();
2366                         else
2367                                 cur.pos() = cur_orig.pos();
2368                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2369                         DocIterator cur_prev_iter;
2370                         do {
2371                                 found_match = match(cur);
2372                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2373                                        << found_match << ", cur: " << cur);
2374                                 if (found_match)
2375                                         return findMostBackwards(cur, match);
2376
2377                                 // Stop if begin of document reached
2378                                 if (cur == cur_begin)
2379                                         break;
2380                                 cur_prev_iter = cur;
2381                                 cur.backwardPos();
2382                         } while (true);
2383                 }
2384                 if (cur == cur_begin)
2385                         break;
2386                 if (cur.pit() > 0)
2387                         --cur.pit();
2388                 else
2389                         cur.backwardPos();
2390                 pit_changed = true;
2391         } while (!theApp()->longOperationCancelled());
2392         return 0;
2393 }
2394
2395
2396 } // namespace
2397
2398
2399 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2400                                  DocIterator const & cur, int len)
2401 {
2402         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2403                 return docstring();
2404         if (!opt.ignoreformat)
2405                 return latexifyFromCursor(cur, len);
2406         else
2407                 return stringifyFromCursor(cur, len);
2408 }
2409
2410
2411 FindAndReplaceOptions::FindAndReplaceOptions(
2412         docstring const & find_buf_name, bool casesensitive,
2413         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2414         docstring const & repl_buf_name, bool keep_case,
2415         SearchScope scope, SearchRestriction restr)
2416         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2417           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2418           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2419 {
2420 }
2421
2422
2423 namespace {
2424
2425
2426 /** Check if 'len' letters following cursor are all non-lowercase */
2427 static bool allNonLowercase(Cursor const & cur, int len)
2428 {
2429         pos_type beg_pos = cur.selectionBegin().pos();
2430         pos_type end_pos = cur.selectionBegin().pos() + len;
2431         if (len > cur.lastpos() + 1 - beg_pos) {
2432                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2433                 len = cur.lastpos() + 1 - beg_pos;
2434                 end_pos = beg_pos + len;
2435         }
2436         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2437                 if (isLowerCase(cur.paragraph().getChar(pos)))
2438                         return false;
2439         return true;
2440 }
2441
2442
2443 /** Check if first letter is upper case and second one is lower case */
2444 static bool firstUppercase(Cursor const & cur)
2445 {
2446         char_type ch1, ch2;
2447         pos_type pos = cur.selectionBegin().pos();
2448         if (pos >= cur.lastpos() - 1) {
2449                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2450                 return false;
2451         }
2452         ch1 = cur.paragraph().getChar(pos);
2453         ch2 = cur.paragraph().getChar(pos + 1);
2454         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2455         LYXERR(Debug::FIND, "firstUppercase(): "
2456                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2457                << ch2 << "(" << char(ch2) << ")"
2458                << ", result=" << result << ", cur=" << cur);
2459         return result;
2460 }
2461
2462
2463 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2464  **
2465  ** \fixme What to do with possible further paragraphs in replace buffer ?
2466  **/
2467 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2468 {
2469         ParagraphList::iterator pit = buffer.paragraphs().begin();
2470         LASSERT(pit->size() >= 1, /**/);
2471         pos_type right = pos_type(1);
2472         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2473         right = pit->size();
2474         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2475 }
2476
2477 } // namespace
2478
2479 ///
2480 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2481 {
2482         Cursor & cur = bv->cursor();
2483         if (opt.repl_buf_name == docstring()
2484             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2485             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2486                 return;
2487
2488         DocIterator sel_beg = cur.selectionBegin();
2489         DocIterator sel_end = cur.selectionEnd();
2490         if (&sel_beg.inset() != &sel_end.inset()
2491             || sel_beg.pit() != sel_end.pit()
2492             || sel_beg.idx() != sel_end.idx())
2493                 return;
2494         int sel_len = sel_end.pos() - sel_beg.pos();
2495         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2496                << ", sel_len: " << sel_len << endl);
2497         if (sel_len == 0)
2498                 return;
2499         LASSERT(sel_len > 0, return);
2500
2501         if (!matchAdv(sel_beg, sel_len))
2502                 return;
2503
2504         // Build a copy of the replace buffer, adapted to the KeepCase option
2505         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2506         ostringstream oss;
2507         repl_buffer_orig.write(oss);
2508         string lyx = oss.str();
2509         Buffer repl_buffer("", false);
2510         repl_buffer.setUnnamed(true);
2511         LASSERT(repl_buffer.readString(lyx), return);
2512         if (opt.keep_case && sel_len >= 2) {
2513                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2514                 if (cur.inTexted()) {
2515                         if (firstUppercase(cur))
2516                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2517                         else if (allNonLowercase(cur, sel_len))
2518                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2519                 }
2520         }
2521         cap::cutSelection(cur, false);
2522         if (cur.inTexted()) {
2523                 repl_buffer.changeLanguage(
2524                         repl_buffer.language(),
2525                         cur.getFont().language());
2526                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2527                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2528                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2529                                         repl_buffer.params().documentClassPtr(),
2530                                         bv->buffer().errorList("Paste"));
2531                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2532                 sel_len = repl_buffer.paragraphs().begin()->size();
2533         } else if (cur.inMathed()) {
2534                 odocstringstream ods;
2535                 otexstream os(ods);
2536                 OutputParams runparams(&repl_buffer.params().encoding());
2537                 runparams.nice = false;
2538                 runparams.flavor = OutputParams::LATEX;
2539                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2540                 runparams.dryrun = true;
2541                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2542                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2543                 docstring repl_latex = ods.str();
2544                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2545                 string s;
2546                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2547                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2548                 repl_latex = from_utf8(s);
2549                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2550                 MathData ar(cur.buffer());
2551                 asArray(repl_latex, ar, Parse::NORMAL);
2552                 cur.insert(ar);
2553                 sel_len = ar.size();
2554                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2555         }
2556         if (cur.pos() >= sel_len)
2557                 cur.pos() -= sel_len;
2558         else
2559                 cur.pos() = 0;
2560         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2561         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2562         bv->processUpdateFlags(Update::Force);
2563 }
2564
2565
2566 /// Perform a FindAdv operation.
2567 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2568 {
2569         DocIterator cur;
2570         int match_len = 0;
2571
2572         // e.g., when invoking word-findadv from mini-buffer wither with
2573         //       wrong options syntax or before ever opening advanced F&R pane
2574         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2575                 return false;
2576
2577         try {
2578                 MatchStringAdv matchAdv(bv->buffer(), opt);
2579                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2580                 if (length > 0)
2581                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2582                 findAdvReplace(bv, opt, matchAdv);
2583                 cur = bv->cursor();
2584                 if (opt.forward)
2585                         match_len = findForwardAdv(cur, matchAdv);
2586                 else
2587                         match_len = findBackwardsAdv(cur, matchAdv);
2588         } catch (...) {
2589                 // This may only be raised by lyx::regex()
2590                 bv->message(_("Invalid regular expression!"));
2591                 return false;
2592         }
2593
2594         if (match_len == 0) {
2595                 bv->message(_("Match not found!"));
2596                 return false;
2597         }
2598
2599         bv->message(_("Match found!"));
2600
2601         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2602         bv->putSelectionAt(cur, match_len, !opt.forward);
2603
2604         return true;
2605 }
2606
2607
2608 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2609 {
2610         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2611            << opt.casesensitive << ' '
2612            << opt.matchword << ' '
2613            << opt.forward << ' '
2614            << opt.expandmacros << ' '
2615            << opt.ignoreformat << ' '
2616            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2617            << opt.keep_case << ' '
2618            << int(opt.scope) << ' '
2619            << int(opt.restr);
2620
2621         LYXERR(Debug::FIND, "built: " << os.str());
2622
2623         return os;
2624 }
2625
2626
2627 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2628 {
2629         LYXERR(Debug::FIND, "parsing");
2630         string s;
2631         string line;
2632         getline(is, line);
2633         while (line != "EOSS") {
2634                 if (! s.empty())
2635                         s = s + "\n";
2636                 s = s + line;
2637                 if (is.eof())   // Tolerate malformed request
2638                         break;
2639                 getline(is, line);
2640         }
2641         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2642         opt.find_buf_name = from_utf8(s);
2643         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2644         is.get();       // Waste space before replace string
2645         s = "";
2646         getline(is, line);
2647         while (line != "EOSS") {
2648                 if (! s.empty())
2649                         s = s + "\n";
2650                 s = s + line;
2651                 if (is.eof())   // Tolerate malformed request
2652                         break;
2653                 getline(is, line);
2654         }
2655         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2656         opt.repl_buf_name = from_utf8(s);
2657         is >> opt.keep_case;
2658         int i;
2659         is >> i;
2660         opt.scope = FindAndReplaceOptions::SearchScope(i);
2661         is >> i;
2662         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2663
2664         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2665                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2666                << opt.scope << ' ' << opt.restr);
2667         return is;
2668 }
2669
2670 } // namespace lyx