]> git.lyx.org Git - features.git/blob - src/lyxfind.cpp
Commented out an unused function to please a picky compiler
[features.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
53
54 #include "support/regex.h"
55 #include <map>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 namespace lyx {
61
62 namespace {
63
64 bool parse_bool(docstring & howto)
65 {
66         if (howto.empty())
67                 return false;
68         docstring var;
69         howto = split(howto, var, ' ');
70         return var == "1";
71 }
72
73
74 class MatchString : public binary_function<Paragraph, pos_type, int>
75 {
76 public:
77         MatchString(docstring const & str, bool cs, bool mw)
78                 : str(str), case_sens(cs), whole_words(mw)
79         {}
80
81         // returns true if the specified string is at the specified position
82         // del specifies whether deleted strings in ct mode will be considered
83         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
84         {
85                 return par.find(str, case_sens, whole_words, pos, del);
86         }
87
88 private:
89         // search string
90         docstring str;
91         // case sensitive
92         bool case_sens;
93         // match whole words only
94         bool whole_words;
95 };
96
97
98 int findForward(DocIterator & cur, MatchString const & match,
99                 bool find_del = true)
100 {
101         for (; cur; cur.forwardChar())
102                 if (cur.inTexted()) {
103                         int len = match(cur.paragraph(), cur.pos(), find_del);
104                         if (len > 0)
105                                 return len;
106                 }
107         return 0;
108 }
109
110
111 int findBackwards(DocIterator & cur, MatchString const & match,
112                   bool find_del = true)
113 {
114         while (cur) {
115                 cur.backwardChar();
116                 if (cur.inTexted()) {
117                         int len = match(cur.paragraph(), cur.pos(), find_del);
118                         if (len > 0)
119                                 return len;
120                 }
121         }
122         return 0;
123 }
124
125
126 bool searchAllowed(docstring const & str)
127 {
128         if (str.empty()) {
129                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
130                 return false;
131         }
132         return true;
133 }
134
135
136 bool findOne(BufferView * bv, docstring const & searchstr,
137              bool case_sens, bool whole, bool forward,
138              bool find_del = true, bool check_wrap = false)
139 {
140         if (!searchAllowed(searchstr))
141                 return false;
142
143         DocIterator cur = forward
144                 ? bv->cursor().selectionEnd()
145                 : bv->cursor().selectionBegin();
146
147         MatchString const match(searchstr, case_sens, whole);
148
149         int match_len = forward
150                 ? findForward(cur, match, find_del)
151                 : findBackwards(cur, match, find_del);
152
153         if (match_len > 0)
154                 bv->putSelectionAt(cur, match_len, !forward);
155         else if (check_wrap) {
156                 DocIterator cur_orig(bv->cursor());
157                 docstring q;
158                 if (forward)
159                         q = _("End of file reached while searching forward.\n"
160                           "Continue searching from the beginning?");
161                 else
162                         q = _("Beginning of file reached while searching backward.\n"
163                           "Continue searching from the end?");
164                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
165                         q, 0, 1, _("&Yes"), _("&No"));
166                 if (wrap_answer == 0) {
167                         if (forward) {
168                                 bv->cursor().clear();
169                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
170                         } else {
171                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
172                                 bv->cursor().backwardPos();
173                         }
174                         bv->clearSelection();
175                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
176                                 return true;
177                 }
178                 bv->cursor().setCursor(cur_orig);
179                 return false;
180         }
181
182         return match_len > 0;
183 }
184
185
186 int replaceAll(BufferView * bv,
187                docstring const & searchstr, docstring const & replacestr,
188                bool case_sens, bool whole)
189 {
190         Buffer & buf = bv->buffer();
191
192         if (!searchAllowed(searchstr) || buf.isReadonly())
193                 return 0;
194
195         DocIterator cur_orig(bv->cursor());
196
197         MatchString const match(searchstr, case_sens, whole);
198         int num = 0;
199
200         int const rsize = replacestr.size();
201         int const ssize = searchstr.size();
202
203         Cursor cur(*bv);
204         cur.setCursor(doc_iterator_begin(&buf));
205         int match_len = findForward(cur, match, false);
206         while (match_len > 0) {
207                 // Backup current cursor position and font.
208                 pos_type const pos = cur.pos();
209                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
210                 cur.recordUndo();
211                 int striked = ssize -
212                         cur.paragraph().eraseChars(pos, pos + match_len,
213                                                    buf.params().track_changes);
214                 cur.paragraph().insert(pos, replacestr, font,
215                                        Change(buf.params().track_changes
216                                               ? Change::INSERTED
217                                               : Change::UNCHANGED));
218                 for (int i = 0; i < rsize + striked; ++i)
219                         cur.forwardChar();
220                 ++num;
221                 match_len = findForward(cur, match, false);
222         }
223
224         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
225
226         cur_orig.fixIfBroken();
227         bv->setCursor(cur_orig);
228
229         return num;
230 }
231
232
233 // the idea here is that we are going to replace the string that
234 // is selected IF it is the search string.
235 // if there is a selection, but it is not the search string, then
236 // we basically ignore it. (FIXME We ought to replace only within
237 // the selection.)
238 // if there is no selection, then:
239 //  (i) if some search string has been provided, then we find it.
240 //      (think of how the dialog works when you hit "replace" the
241 //      first time.)
242 // (ii) if no search string has been provided, then we treat the
243 //      word the cursor is in as the search string. (why? i have no
244 //      idea.) but this only works in text?
245 //
246 // returns the number of replacements made (one, if any) and
247 // whether anything at all was done.
248 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
249                            docstring const & replacestr, bool case_sens,
250                            bool whole, bool forward, bool findnext)
251 {
252         Cursor & cur = bv->cursor();
253         bool found = false;
254         if (!cur.selection()) {
255                 // no selection, non-empty search string: find it
256                 if (!searchstr.empty()) {
257                         found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
258                         return make_pair(found, 0);
259                 }
260                 // empty search string
261                 if (!cur.inTexted())
262                         // bail in math
263                         return make_pair(false, 0);
264                 // select current word and treat it as the search string.
265                 // This causes a minor bug as undo will restore this selection,
266                 // which the user did not create (#8986).
267                 cur.innerText()->selectWord(cur, WHOLE_WORD);
268                 searchstr = cur.selectionAsString(false);
269         }
270
271         // if we still don't have a search string, report the error
272         // and abort.
273         if (!searchAllowed(searchstr))
274                 return make_pair(false, 0);
275
276         bool have_selection = cur.selection();
277         docstring const selected = cur.selectionAsString(false);
278         bool match =
279                 case_sens
280                 ? searchstr == selected
281                 : compare_no_case(searchstr, selected) == 0;
282
283         // no selection or current selection is not search word:
284         // just find the search word
285         if (!have_selection || !match) {
286                 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
287                 return make_pair(found, 0);
288         }
289
290         // we're now actually ready to replace. if the buffer is
291         // read-only, we can't, though.
292         if (bv->buffer().isReadonly())
293                 return make_pair(false, 0);
294
295         cap::replaceSelectionWithString(cur, replacestr);
296         if (forward) {
297                 cur.pos() += replacestr.length();
298                 LASSERT(cur.pos() <= cur.lastpos(),
299                         cur.pos() = cur.lastpos());
300         }
301         if (findnext)
302                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
303
304         return make_pair(true, 1);
305 }
306
307 } // namespace
308
309
310 docstring const find2string(docstring const & search,
311                             bool casesensitive, bool matchword, bool forward)
312 {
313         odocstringstream ss;
314         ss << search << '\n'
315            << int(casesensitive) << ' '
316            << int(matchword) << ' '
317            << int(forward);
318         return ss.str();
319 }
320
321
322 docstring const replace2string(docstring const & replace,
323                                docstring const & search,
324                                bool casesensitive, bool matchword,
325                                bool all, bool forward, bool findnext)
326 {
327         odocstringstream ss;
328         ss << replace << '\n'
329            << search << '\n'
330            << int(casesensitive) << ' '
331            << int(matchword) << ' '
332            << int(all) << ' '
333            << int(forward) << ' '
334            << int(findnext);
335         return ss.str();
336 }
337
338
339 bool lyxfind(BufferView * bv, FuncRequest const & ev)
340 {
341         if (!bv || ev.action() != LFUN_WORD_FIND)
342                 return false;
343
344         //lyxerr << "find called, cmd: " << ev << endl;
345
346         // data is of the form
347         // "<search>
348         //  <casesensitive> <matchword> <forward>"
349         docstring search;
350         docstring howto = split(ev.argument(), search, '\n');
351
352         bool casesensitive = parse_bool(howto);
353         bool matchword     = parse_bool(howto);
354         bool forward       = parse_bool(howto);
355
356         return findOne(bv, search, casesensitive, matchword, forward, true, true);
357 }
358
359
360 bool lyxreplace(BufferView * bv,
361                 FuncRequest const & ev, bool has_deleted)
362 {
363         if (!bv || ev.action() != LFUN_WORD_REPLACE)
364                 return false;
365
366         // data is of the form
367         // "<search>
368         //  <replace>
369         //  <casesensitive> <matchword> <all> <forward> <findnext>"
370         docstring search;
371         docstring rplc;
372         docstring howto = split(ev.argument(), rplc, '\n');
373         howto = split(howto, search, '\n');
374
375         bool casesensitive = parse_bool(howto);
376         bool matchword     = parse_bool(howto);
377         bool all           = parse_bool(howto);
378         bool forward       = parse_bool(howto);
379         bool findnext      = howto.empty() ? true : parse_bool(howto);
380
381         bool update = false;
382
383         if (!has_deleted) {
384                 int replace_count = 0;
385                 if (all) {
386                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
387                         update = replace_count > 0;
388                 } else {
389                         pair<bool, int> rv =
390                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
391                         update = rv.first;
392                         replace_count = rv.second;
393                 }
394
395                 Buffer const & buf = bv->buffer();
396                 if (!update) {
397                         // emit message signal.
398                         buf.message(_("String not found."));
399                 } else {
400                         if (replace_count == 0) {
401                                 buf.message(_("String found."));
402                         } else if (replace_count == 1) {
403                                 buf.message(_("String has been replaced."));
404                         } else {
405                                 docstring const str =
406                                         bformat(_("%1$d strings have been replaced."), replace_count);
407                                 buf.message(str);
408                         }
409                 }
410         } else if (findnext) {
411                 // if we have deleted characters, we do not replace at all, but
412                 // rather search for the next occurence
413                 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
414                         update = true;
415                 else
416                         bv->message(_("String not found."));
417         }
418         return update;
419 }
420
421
422 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
423 {
424         for (; cur; cur.forwardPos())
425                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
426                         return true;
427
428         if (check_wrap) {
429                 DocIterator cur_orig(bv->cursor());
430                 docstring q = _("End of file reached while searching forward.\n"
431                           "Continue searching from the beginning?");
432                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
433                         q, 0, 1, _("&Yes"), _("&No"));
434                 if (wrap_answer == 0) {
435                         bv->cursor().clear();
436                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
437                         bv->clearSelection();
438                         cur.setCursor(bv->cursor().selectionBegin());
439                         if (findNextChange(bv, cur, false))
440                                 return true;
441                 }
442                 bv->cursor().setCursor(cur_orig);
443         }
444
445         return false;
446 }
447
448
449 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
450 {
451         for (cur.backwardPos(); cur; cur.backwardPos()) {
452                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
453                         return true;
454         }
455
456         if (check_wrap) {
457                 DocIterator cur_orig(bv->cursor());
458                 docstring q = _("Beginning of file reached while searching backward.\n"
459                           "Continue searching from the end?");
460                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
461                         q, 0, 1, _("&Yes"), _("&No"));
462                 if (wrap_answer == 0) {
463                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
464                         bv->cursor().backwardPos();
465                         bv->clearSelection();
466                         cur.setCursor(bv->cursor().selectionBegin());
467                         if (findPreviousChange(bv, cur, false))
468                                 return true;
469                 }
470                 bv->cursor().setCursor(cur_orig);
471         }
472
473         return false;
474 }
475
476
477 bool selectChange(Cursor & cur, bool forward)
478 {
479         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
480                 return false;
481         Change ch = cur.paragraph().lookupChange(cur.pos());
482
483         CursorSlice tip1 = cur.top();
484         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
485                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
486                 if (!ch2.isSimilarTo(ch))
487                         break;
488         }
489         CursorSlice tip2 = cur.top();
490         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
491                 tip2.backwardPos();
492                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
493                 if (!ch2.isSimilarTo(ch)) {
494                         // take a step forward to correctly set the selection
495                         tip2.forwardPos();
496                         break;
497                 }
498         }
499         if (forward)
500                 swap(tip1, tip2);
501         cur.top() = tip1;
502         cur.bv().mouseSetCursor(cur, false);
503         cur.top() = tip2;
504         cur.bv().mouseSetCursor(cur, true);
505         return true;
506 }
507
508
509 namespace {
510
511
512 bool findChange(BufferView * bv, bool forward)
513 {
514         Cursor cur(*bv);
515         cur.setCursor(forward ? bv->cursor().selectionEnd()
516                       : bv->cursor().selectionBegin());
517         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
518         return selectChange(cur, forward);
519 }
520
521 } // namespace
522
523 bool findNextChange(BufferView * bv)
524 {
525         return findChange(bv, true);
526 }
527
528
529 bool findPreviousChange(BufferView * bv)
530 {
531         return findChange(bv, false);
532 }
533
534
535
536 namespace {
537
538 typedef vector<pair<string, string> > Escapes;
539
540 /// A map of symbols and their escaped equivalent needed within a regex.
541 /// @note Beware of order
542 Escapes const & get_regexp_escapes()
543 {
544         typedef std::pair<std::string, std::string> P;
545
546         static Escapes escape_map;
547         if (escape_map.empty()) {
548                 escape_map.push_back(P("$", "_x_$"));
549                 escape_map.push_back(P("{", "_x_{"));
550                 escape_map.push_back(P("}", "_x_}"));
551                 escape_map.push_back(P("[", "_x_["));
552                 escape_map.push_back(P("]", "_x_]"));
553                 escape_map.push_back(P("(", "_x_("));
554                 escape_map.push_back(P(")", "_x_)"));
555                 escape_map.push_back(P("+", "_x_+"));
556                 escape_map.push_back(P("*", "_x_*"));
557                 escape_map.push_back(P(".", "_x_."));
558                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
559                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
560                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
561                 escape_map.push_back(P("_x_", "\\"));
562         }
563         return escape_map;
564 }
565
566 /// A map of lyx escaped strings and their unescaped equivalent.
567 Escapes const & get_lyx_unescapes()
568 {
569         typedef std::pair<std::string, std::string> P;
570
571         static Escapes escape_map;
572         if (escape_map.empty()) {
573                 escape_map.push_back(P("\\%", "%"));
574                 escape_map.push_back(P("\\mathcircumflex ", "^"));
575                 escape_map.push_back(P("\\mathcircumflex", "^"));
576                 escape_map.push_back(P("\\backslash ", "\\"));
577                 escape_map.push_back(P("\\backslash", "\\"));
578                 escape_map.push_back(P("\\\\{", "_x_<"));
579                 escape_map.push_back(P("\\\\}", "_x_>"));
580                 escape_map.push_back(P("\\sim ", "~"));
581                 escape_map.push_back(P("\\sim", "~"));
582         }
583         return escape_map;
584 }
585
586 /// A map of escapes turning a regexp matching text to one matching latex.
587 Escapes const & get_regexp_latex_escapes()
588 {
589         typedef std::pair<std::string, std::string> P;
590
591         static Escapes escape_map;
592         if (escape_map.empty()) {
593                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
594                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
595                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
596                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
597                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
598                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
599                 escape_map.push_back(P("%", "\\\\\\%"));
600         }
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  * Discard any info for char sizes for now.
928  */
929 static string removefontinfo(string par)
930 {
931         // Remove fontsizes, inputencoding
932         smatch sub;
933         list <string> fpars;
934         static regex const sizescodings("(\\\\(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|inputencoding\\{[^\\}]*})(\b|(\\{(\\{\\})?\\})?(%\\n)?))");
935         for (sregex_iterator it(par.begin(), par.end(), sizescodings), end; it != end; ++it) {
936                 sub = *it;
937                 string token = sub.str(1);
938                 fpars.push_back(token);
939         }
940         for (list<string>::const_iterator li = fpars.begin(); li != fpars.end(); ++li) {
941                 string token = *li;
942                 int f;
943                 int firstpos = 0;
944                 int ic; // Position of closing part e.g. '}'
945                 while ((f = par.find(token, firstpos)) >= 0) {
946                         size_t ssize = token.length();
947                         int parcount = 0;       // how many '{}' can be removed
948                         if (f == 0)
949                                 ic = -1;
950                         else {
951                                 if (par[f-1] != '{')
952                                         ic = -1;
953                                 else {
954                                         // here '{' preceedes
955                                         ic = findclosing(par, f + ssize, par.length());
956                                         if (f == 1)
957                                                 parcount = 1;
958                                         else if ((f == 2) && (par[f-2] == '{')) {
959                                                 if ((ic < 0) || (par[ic+1] == '}'))
960                                                         parcount = 2;
961                                                 else
962                                                         parcount = 1;
963                                         } else while (f > parcount + 1) {
964                                                 if (par[f-2-parcount] != '{')
965                                                         break;
966                                                 parcount++;
967                                                 if ((ic > 0) && (par[ic+parcount] != '}'))
968                                                         break;
969                                         }
970                                 }
971                         }
972                         firstpos = f;
973
974                         if (ic < 0)
975                                 ic = par.length() - parcount;
976                         par = par.substr(0, f-parcount) + par.substr(f+ssize, ic+parcount-f-ssize) + par.substr(ic+parcount);
977                 }
978         }
979         return(par);
980 }
981
982
983 /*
984  * defines values features of a key "\\[a-z]+{"
985  */
986 class KeyInfo {
987  public:
988   enum KeyType {
989     isChar,
990     isMain,                             /* for \\foreignlanguage */
991     isRegex,
992     isStandard,
993     invalid,
994     doRemove,
995     leadRemove,
996     isIgnored                           /* to be ignored by creating infos */
997   };
998  KeyInfo(string key) : head(key) {};
999  KeyInfo()
1000    : keytype(invalid),
1001     head(""),
1002     parenthesiscount(1)
1003   {};
1004  KeyInfo(KeyType type, int parcount)
1005    : keytype(type),
1006     parenthesiscount(parcount) {};
1007   KeyType keytype;
1008   string head;
1009   int _tokensize;
1010   int _tokenstart;
1011   int _dataStart;
1012   int _dataEnd;
1013   int parenthesiscount;
1014 };
1015
1016 #define MAXOPENED 30
1017 class Intervall {
1018  public:
1019  Intervall() : ignoreidx(-1), actualdeptindex(0) {};
1020   string par;
1021   int ignoreidx;
1022   int depts[MAXOPENED];
1023   int closes[MAXOPENED];
1024   int actualdeptindex;
1025   int ignoreIntervalls[2*MAXOPENED][2];
1026   // int previousNotIgnored(int);
1027   int nextNotIgnored(int);
1028   void handleOpenP(int i);
1029   void handleCloseP(int i, bool closingAllowed);
1030   void resetOpenedP(int openPos);
1031   void addIntervall(int upper);
1032   void addIntervall(int low, int upper); /* if explicit */
1033   void setForDefaultLang(int upTo);
1034   int findclosing(int start, int end);
1035   void handleParentheses(int lastpos, bool closingAllowed);
1036   void output(ostringstream &os, int lastpos);
1037   // string show(int lastpos);
1038 };
1039
1040 void Intervall::setForDefaultLang(int upTo)
1041 {
1042   // Enable the use of first token again
1043   if (ignoreidx >= 0) {
1044     if (ignoreIntervalls[0][0] < upTo)
1045       ignoreIntervalls[0][0] = upTo;
1046     if (ignoreIntervalls[0][1] < upTo)
1047       ignoreIntervalls[0][1] = upTo;
1048   }
1049 }
1050
1051 static void checkDepthIndex(int val)
1052 {
1053   static int maxdepthidx = MAXOPENED-2;
1054   if (val > maxdepthidx) {
1055     maxdepthidx = val;
1056     LYXERR0("maxdepthidx now " << val);
1057   }
1058 }
1059
1060 static void checkIgnoreIdx(int val)
1061 {
1062   static int maxignoreidx = 2*MAXOPENED - 4;
1063   if (val > maxignoreidx) {
1064     maxignoreidx = val;
1065     LYXERR0("maxignoreidx now " << val);
1066   }
1067 }
1068
1069 /*
1070  * Expand the region of ignored parts of the input latex string
1071  * The region is only relevant in output()
1072  */
1073 void Intervall::addIntervall(int low, int upper)
1074 {
1075   int idx;
1076   if (low == upper) return;
1077   for (idx = ignoreidx+1; idx > 0; --idx) {
1078     if (low > ignoreIntervalls[idx-1][1]) {
1079       break;
1080     }
1081   }
1082   if (idx > ignoreidx) {
1083     ignoreIntervalls[idx][0] = low;
1084     ignoreIntervalls[idx][1] = upper;
1085     ignoreidx = idx;
1086     checkIgnoreIdx(ignoreidx);
1087     return;
1088   }
1089   else {
1090     // Expand only if one of the new bound is inside the interwall
1091     // We know here that low > ignoreIntervalls[idx-1][1]
1092     if (upper < ignoreIntervalls[idx][0]) {
1093       // We have to insert at this pos
1094       for (int i = ignoreidx+1; i > idx; --i) {
1095         ignoreIntervalls[i][1] = ignoreIntervalls[i-1][1];
1096         ignoreIntervalls[i][0] = ignoreIntervalls[i-1][0];
1097       }
1098       ignoreIntervalls[idx][0] = low;
1099       ignoreIntervalls[idx][1] = upper;
1100       ignoreidx += 1;
1101       checkIgnoreIdx(ignoreidx);
1102       return;
1103     }
1104     // Here we know, that we are overlapping
1105     if (low > ignoreIntervalls[idx][0])
1106       low = ignoreIntervalls[idx][0];
1107     // check what has to be concatenated
1108     int count = 0;
1109     for (int i = idx; i <= ignoreidx; i++) {
1110       if (upper >= ignoreIntervalls[i][0]) {
1111         count++;
1112         if (upper < ignoreIntervalls[i][1])
1113           upper = ignoreIntervalls[i][1];
1114       }
1115       else {
1116         break;
1117       }
1118     }
1119     // count should be >= 1 here
1120     ignoreIntervalls[idx][0] = low;
1121     ignoreIntervalls[idx][1] = upper;
1122     if (count > 1) {
1123       for (int i = idx + count; i <= ignoreidx; i++) {
1124         ignoreIntervalls[i-count+1][0] = ignoreIntervalls[i][0];
1125         ignoreIntervalls[i-count+1][1] = ignoreIntervalls[i][1];
1126       }
1127       ignoreidx -= count - 1;
1128       return;
1129     }
1130   }
1131 }
1132
1133 void Intervall::handleOpenP(int i)
1134 {
1135   actualdeptindex++;
1136   depts[actualdeptindex] = i+1;
1137   closes[actualdeptindex] = -1;
1138   checkDepthIndex(actualdeptindex);
1139 }
1140
1141 void Intervall::handleCloseP(int i, bool closingAllowed)
1142 {
1143   if (actualdeptindex <= 0) {
1144     if (closingAllowed) {
1145       // if we are at the very end
1146       addIntervall(i, i+1);
1147     }
1148     else {
1149       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should never happen! */
1150     }
1151   }
1152   else {
1153     closes[actualdeptindex] = i+1;
1154     actualdeptindex--;
1155   }
1156 }
1157
1158 void Intervall::resetOpenedP(int openPos)
1159 {
1160   actualdeptindex = 1;
1161   depts[1] = openPos+1;
1162   closes[1] = -1;
1163 }
1164
1165 #if 0
1166 int Intervall::previousNotIgnored(int start)
1167 {
1168     int idx = 0;                          /* int intervalls */
1169     for (idx = ignoreidx; idx >= 0; --idx) {
1170       if (start > ignoreIntervalls[idx][1])
1171         return(start);
1172       if (start >= ignoreIntervalls[idx][0])
1173         start = ignoreIntervalls[idx][0]-1;
1174     }
1175     return start;
1176 }
1177 #endif
1178
1179 int Intervall::nextNotIgnored(int start)
1180 {
1181     int idx = 0;                          /* int intervalls */
1182     for (idx = 0; idx <= ignoreidx; idx++) {
1183       if (start < ignoreIntervalls[idx][0])
1184         return(start);
1185       if (start < ignoreIntervalls[idx][1])
1186         start = ignoreIntervalls[idx][1];
1187     }
1188     return start;
1189 }
1190
1191 typedef map<string, KeyInfo> KeysMap;
1192 typedef vector< KeyInfo> Entries;
1193 static KeysMap keys = map<string, KeyInfo>();
1194
1195 class LatexInfo {
1196  private:
1197   int entidx;
1198   Entries entries;
1199   KeyInfo analyze(string key);
1200   Intervall interval;
1201   void buildKeys();
1202   void buildEntries();
1203   void makeKey(string, KeyInfo);
1204   void processRegion(ostringstream &os, int start, int region_end);
1205  public:
1206  LatexInfo(string par) {
1207     interval.par = par;
1208     buildKeys();
1209     entries = vector<KeyInfo>();
1210     buildEntries();
1211   };
1212   int getFirstKey() {
1213     entidx = 0;
1214     if (entries.empty()) {
1215       return (-1);
1216     }
1217     return 0;
1218   };
1219   int getNextKey() {
1220     entidx++;
1221     if (int(entries.size()) > entidx) {
1222       return entidx;
1223     }
1224     else {
1225       return (-1);
1226     }
1227   };
1228   bool setNextKey(int idx) {
1229     if ((idx == entidx) && (entidx > 0)) {
1230       entidx--;
1231       return true;
1232     }
1233     else
1234       return(false);
1235   };
1236   int process(ostringstream &os, int actual, bool faking);
1237   // string show(int lastpos) { return interval.show(lastpos);};
1238   int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1239   KeyInfo &getKeyInfo(int keyinfo) {
1240     static KeyInfo invalidInfo = KeyInfo();
1241     if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1242       return invalidInfo;
1243     else
1244       return entries[keyinfo];
1245   };
1246 };
1247
1248
1249 int Intervall::findclosing(int start, int end)
1250 {
1251   int skip = 0;
1252   int depth = 0;
1253   for (int i = start; i < end; i += 1 + skip) {
1254     char c;
1255     c = par[i];
1256     skip = 0;
1257     if (c == '\\') skip = 1;
1258     else if (c == '{') {
1259       depth++;
1260     }
1261     else if (c == '}') {
1262       if (depth == 0) return(i);
1263       --depth;
1264     }
1265   }
1266   return(end);
1267 }
1268
1269 void LatexInfo::buildEntries()
1270 {
1271   static regex const rkeys("\\\\((([a-z]+)(\\{([a-z]+)\\}|\\*)?))([\\{ ])");
1272   smatch sub;
1273   bool evaluatingRegexp = false;
1274   KeyInfo found;
1275   for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1276     sub = *it;
1277     if (evaluatingRegexp) {
1278       if (sub.str(1).compare("endregexp") == 0) {
1279         evaluatingRegexp = false;
1280         // found._tokenstart already set
1281         found._dataEnd = sub.position(0) + 12;
1282         found._dataStart = found._tokenstart;
1283       }
1284     }
1285     else {
1286       if (keys.find(sub.str(3)) == keys.end()) {
1287         LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1288         continue;
1289       }
1290       found = keys[sub.str(3)];
1291       if (sub.str(3).compare("regexp") == 0) {
1292         evaluatingRegexp = true;
1293         found._tokenstart = sub.position(0);
1294         found._tokensize = 0;
1295         continue;
1296       }
1297     }
1298     // Handle the other params of key
1299     if (found.keytype == KeyInfo::isIgnored)
1300       continue;
1301     else if (found.keytype == KeyInfo::isRegex) {
1302     }
1303     else {
1304       found._tokenstart = sub.position(0);
1305       if (found.parenthesiscount == 0) {
1306         // Probably to be discarded
1307         found.head = sub.str(0);
1308         if (sub.str(6)[0] == ' ') {
1309           // Probably to be discarded
1310           found._dataEnd = sub.position(6);
1311         }
1312         else {
1313           found._dataEnd = sub.position(6)+1;
1314         }
1315         found._tokensize = found.head.length() - 1;
1316         found._dataStart = found._dataEnd;
1317       }
1318       else if (sub.str(6)[0] != '{')
1319         continue;
1320       else {
1321         if (found.parenthesiscount == 1)
1322           found.head = "\\" + sub.str(3) + "{";
1323         else if (found.parenthesiscount == 2) {
1324           found.head = sub.str(0);
1325           found._tokensize = found.head.length();
1326         }
1327         found._dataStart = found._tokenstart + found.head.length();
1328         found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1329       }
1330     }
1331     entries.push_back(found);
1332   }
1333 }
1334
1335 void LatexInfo::makeKey(string key, KeyInfo keyI)
1336 {
1337   KeyInfo keyII(keyI);
1338   keys[key] = keyII;
1339 }
1340
1341 void LatexInfo::buildKeys()
1342 {
1343   static bool keysBuilt = false;
1344
1345   if (keysBuilt) return;
1346   KeyInfo foreign = KeyInfo(KeyInfo::isMain,     2);
1347   KeyInfo standard = KeyInfo(KeyInfo::isStandard,1);
1348   KeyInfo regex = KeyInfo(KeyInfo::isRegex,      1);
1349   KeyInfo color = KeyInfo(KeyInfo::isStandard,   2);
1350   KeyInfo character = KeyInfo(KeyInfo::isChar,   1);
1351   KeyInfo toremove = KeyInfo(KeyInfo::doRemove,  1);
1352   KeyInfo leadremove = KeyInfo(KeyInfo::leadRemove,1);
1353   KeyInfo ignoreMe = KeyInfo(KeyInfo::isIgnored, 0);
1354
1355   makeKey("textsf",standard);
1356   makeKey("texttt",standard);
1357   makeKey("textbf",standard);
1358   makeKey("textit",standard);
1359   makeKey("emph",standard);
1360   makeKey("noun",standard);
1361   makeKey("uuline",standard);
1362   makeKey("uline",standard);
1363   makeKey("sout",standard);
1364   makeKey("xout",standard);
1365   makeKey("uwave",standard);
1366   makeKey("regexp",regex);
1367   makeKey("textcolor",color);
1368   makeKey("foreignlanguage",foreign);
1369   makeKey("backslash",character);
1370   makeKey("textbackslash",character);
1371   makeKey("inputencoding", toremove);
1372   makeKey("shortcut", toremove);
1373   toremove.parenthesiscount = 0;
1374   makeKey("noindent", toremove);
1375   makeKey("url", leadremove);
1376   makeKey("href", leadremove);
1377   makeKey("menuitem", leadremove);
1378   makeKey("footnote", leadremove);
1379   makeKey("code", leadremove);
1380   makeKey("lyx", ignoreMe);
1381   keysBuilt = true;
1382 }
1383
1384 /*
1385  * Keep the list of actual opened parentheses actual
1386  * (e.g. depth == 4 means there are 4 '{' not processed yet)
1387  */
1388 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1389 {
1390   int skip = 0;
1391   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1392     char c;
1393     c = par[i];
1394     skip = 0;
1395     if (c == '\\') skip = 1;
1396     else if (c == '{') {
1397       handleOpenP(i);
1398     }
1399     else if (c == '}') {
1400       handleCloseP(i, closingAllowed);
1401     }
1402   }
1403 }
1404
1405 #if (0)
1406 string Intervall::show(int lastpos)
1407 {
1408   int idx = 0;                          /* int intervalls */
1409   int count = 0;
1410   string s;
1411   int i = 0;
1412   for (idx = 0; idx <= ignoreidx; idx++) {
1413     while (i < lastpos) {
1414       int printsize;
1415       if (i <= ignoreIntervalls[idx][0]) {
1416         if (ignoreIntervalls[idx][0] > lastpos)
1417           printsize = lastpos - i;
1418         else
1419           printsize = ignoreIntervalls[idx][0] - i;
1420         s += par.substr(i, printsize);
1421         i += printsize;
1422         if (i >= ignoreIntervalls[idx][0])
1423           i = ignoreIntervalls[idx][1];
1424       }
1425       else {
1426         i = ignoreIntervalls[idx][1];
1427         break;
1428       }
1429     }
1430   }
1431   if (lastpos > i) {
1432     s += par.substr(i, lastpos-i);
1433   }
1434   return (s);
1435 }
1436 #endif
1437
1438 void Intervall::output(ostringstream &os, int lastpos)
1439 {
1440   // get number of chars to output
1441   int idx = 0;                          /* int intervalls */
1442   int i = 0;
1443   for (idx = 0; idx <= ignoreidx; idx++) {
1444     if (i < lastpos) {
1445       int printsize;
1446       if (i <= ignoreIntervalls[idx][0]) {
1447         if (ignoreIntervalls[idx][0] > lastpos)
1448           printsize = lastpos - i;
1449         else
1450           printsize = ignoreIntervalls[idx][0] - i;
1451         os << par.substr(i, printsize);
1452         i += printsize;
1453         handleParentheses(i, false);
1454         if (i >= ignoreIntervalls[idx][0])
1455           i = ignoreIntervalls[idx][1];
1456       }
1457       else {
1458         i = ignoreIntervalls[idx][1];
1459       }
1460     }
1461     else
1462       break;
1463   }
1464   if (lastpos > i) {
1465     os << par.substr(i, lastpos-i);
1466   }
1467   handleParentheses(lastpos, false);
1468   for (int i = actualdeptindex; i > 0; --i) {
1469     os << "}";
1470   }
1471   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1472 }
1473
1474 void LatexInfo::processRegion(ostringstream &os, int start, int region_end)
1475 {
1476   int old_start = start;
1477   while (start < region_end) {
1478     if (interval.par[start] == '{') {
1479       int closing = interval.findclosing(start+1, region_end);
1480       interval.addIntervall(start, start+1);
1481       interval.addIntervall(closing, closing+1);
1482     }
1483     start = interval.nextNotIgnored(start+1);
1484   }
1485   start = interval.nextNotIgnored(old_start);
1486   if (start < region_end) {
1487     interval.output(os, region_end);
1488     interval.addIntervall(start, region_end);
1489   }
1490 }
1491
1492 int LatexInfo::process(ostringstream &os, int actualidx, bool faking)
1493 {
1494   KeyInfo &actual = getKeyInfo(actualidx);
1495   int nextKeyIdx = getNextKey();
1496   int start, old_start;
1497   int end = interval.nextNotIgnored(actual._dataEnd);
1498   old_start = interval.nextNotIgnored(actual._dataStart);
1499   if (faking) {
1500     // Adapt for start of first open parenthesis
1501     interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1502   }
1503   if (actual.keytype == KeyInfo::isMain) {
1504     // Fake for opened braces
1505     interval.resetOpenedP(actual._dataStart-1);
1506   }
1507   while (true) {
1508     if ((nextKeyIdx < 0) ||
1509         (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1510         (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1511       processRegion(os, old_start, end);
1512       old_start = end+1;
1513       break;
1514     }
1515     if (entries[nextKeyIdx].keytype == KeyInfo::isMain) {
1516       end = entries[nextKeyIdx]._tokenstart;
1517       break;
1518     }
1519     if (entries[nextKeyIdx].keytype == KeyInfo::isChar) {
1520       old_start = entries[nextKeyIdx]._dataEnd+1;
1521       nextKeyIdx = getNextKey();
1522     }
1523     else if (entries[nextKeyIdx].keytype == KeyInfo::isStandard) {
1524       processRegion(os, old_start, entries[nextKeyIdx]._tokenstart);
1525       old_start = entries[nextKeyIdx]._dataEnd+1;
1526       nextKeyIdx = process(os, nextKeyIdx, false);
1527     }
1528     else if (entries[nextKeyIdx].keytype == KeyInfo::doRemove) {
1529       interval.addIntervall(entries[nextKeyIdx]._tokenstart, entries[nextKeyIdx]._dataEnd+1);
1530       nextKeyIdx = getNextKey();
1531     }
1532     else if (entries[nextKeyIdx].keytype == KeyInfo::leadRemove) {
1533       // Remove headerthe hull, that is "\url{abcd}" ==> "abcd"
1534       interval.addIntervall(entries[nextKeyIdx]._tokenstart,entries[nextKeyIdx]._dataStart);
1535       interval.addIntervall(entries[nextKeyIdx]._dataEnd, entries[nextKeyIdx]._dataEnd+1);
1536       nextKeyIdx = getNextKey();
1537     }
1538     else if (entries[nextKeyIdx].keytype == KeyInfo::isRegex) {
1539       // Copy regexp part as is
1540       processRegion(os, old_start, entries[nextKeyIdx]._tokenstart);
1541       interval.output(os, entries[nextKeyIdx]._dataEnd+1);
1542       old_start = entries[nextKeyIdx]._dataEnd+1;
1543       interval.addIntervall(entries[nextKeyIdx]._tokenstart, entries[nextKeyIdx]._dataEnd+1);
1544       nextKeyIdx = getNextKey();
1545     }
1546     else {
1547       // LYXERR0("Unhandled keytype");
1548       nextKeyIdx = getNextKey();
1549     }
1550   }
1551   // now nextKey is either invalid or is outside of actual._dataEnd
1552   // output the remaing and discard myself
1553   start = interval.nextNotIgnored(actual._dataStart);
1554   processRegion(os, start, end);
1555   if (interval.par[end] == '}') {
1556     end += 1;
1557     // This is the normal case.
1558     // But if using the firstlanguage, the closing may be missing
1559   }
1560   interval.addIntervall(actual._tokenstart, end);
1561   if (faking) {
1562     // Adapt for start of first open parenthesis
1563   }
1564   return nextKeyIdx;
1565 }
1566
1567 string splitForColors(string par) {
1568   ostringstream os;
1569   LatexInfo li(par);
1570   int firstkeyIdx = li.getFirstKey();
1571   string s;
1572   if (firstkeyIdx >= 0) {
1573     int nextkeyIdx = li.process(os, firstkeyIdx, true);
1574     KeyInfo &firstKey = li.getKeyInfo(firstkeyIdx);
1575     while (nextkeyIdx >= 0) {
1576       // Check for a possible gap between the last
1577       // entry and this one
1578       int datastart = li.nextNotIgnored(firstKey._dataStart);
1579       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1580       if (nextKey._tokenstart > datastart) {
1581         // Handle the gap
1582         firstKey._dataStart = datastart;
1583         firstKey._dataEnd = nextKey._tokenstart;
1584         (void) li.setNextKey(nextkeyIdx);
1585         // Fake the last opened parenthesis
1586         int testkey = li.process(os, firstkeyIdx, true); /* The returned key should be the same */
1587         if (testkey != nextkeyIdx) {
1588           LYXERR(Debug::FIND,"Something wrong");
1589         }
1590       }
1591       else {
1592         if (nextKey.keytype != KeyInfo::isMain) {
1593           firstKey._dataStart = datastart;
1594           firstKey._dataEnd = nextKey._dataEnd+1;
1595           (void) li.setNextKey(nextkeyIdx);
1596           nextkeyIdx = li.process(os, firstkeyIdx, true);
1597         }
1598         else {
1599           nextkeyIdx = li.process(os, nextkeyIdx, false);
1600         }
1601       }
1602     }
1603     // Handle the remaining
1604     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1605     firstKey._dataEnd = par.length();
1606     if (firstKey._dataStart +1 < firstKey._dataEnd)
1607       (void) li.process(os, firstkeyIdx, true);
1608     s = os.str();
1609   }
1610   else
1611     s = "";                        /* found end */
1612   return s;
1613 }
1614
1615 /*
1616  * Try to unify the language specs in the latexified text.
1617  * Resulting modified string is set to "", if
1618  * the searched tex does not contain all the features in the search pattern
1619  */
1620 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1621 {
1622         static Features regex_f;
1623         static int missed = 0;
1624         static bool regex_with_format = false;
1625
1626         int parlen = par.length();
1627
1628         while ((parlen > 0) && (par[parlen-1] == '\n')) {
1629                 parlen--;
1630         }
1631         string result;
1632         if (withformat) {
1633                 // Split the latex input into pieces which
1634                 // can be digested by our search engine
1635                 result = removefontinfo(par.substr(0, parlen));
1636                 LYXERR(Debug::FIND, "input: \"" << result << "\"");
1637                 result = splitForColors(result);
1638                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1639         }
1640         else
1641                 result = par.substr(0, parlen);
1642         bool handle_colors = false;
1643         if (from_regex) {
1644                 missed = 0;
1645                 if (withformat) {
1646                         regex_f = identifyFeatures(result);
1647                         string features = "";
1648                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1649                                 string a = it->first;
1650                                 regex_with_format = true;
1651                                 if (a.compare(0,10,"textcolor{") == 0)
1652                                   handle_colors = true;
1653                                 features += " " + a;
1654                                 // LYXERR0("Identified regex format:" << a);
1655                         }
1656                         LYXERR(Debug::FIND, "Identified Features" << features);
1657
1658                 }
1659         } else if (regex_with_format) {
1660                 Features info = identifyFeatures(result);
1661                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1662                         string a = it->first;
1663                         bool b = it->second;
1664                         if (b && ! info[a]) {
1665                                 missed++;
1666                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1667                                 return("");
1668                         }
1669                         else if (a.compare(0,10,"textcolor{") == 0)
1670                                 handle_colors = true;
1671                 }
1672         }
1673         else {
1674                 // LYXERR0("No regex formats");
1675         }
1676         // remove possible disturbing macros
1677         while (regex_replace(result, result, "\\\\(noindent )", ""))
1678                 ;
1679         // Either not found language spec,or is single and closed spec or empty
1680         // to be removed
1681         // [a-z+]par
1682         static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1683
1684         list <string> pars;
1685         smatch sub;
1686         for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1687                 sub = *it;
1688                 string token = sub.str(1);
1689                 pars.push_back(token);
1690         }
1691         for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1692                 string token = *li;
1693                 int ti = result.find(token);
1694                 int tokensize = token.size() + 1;
1695                 if (ti >= 0) {
1696                         int tc = findclosing(result, ti + tokensize, result.size());
1697                         if (tc > 0)
1698                                 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1699
1700                 }
1701         }
1702         if (handle_colors) {
1703           while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1704           while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1705         }
1706         return(result);
1707 }
1708
1709
1710 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1711 static int identifyClosing(string & t)
1712 {
1713         int open_braces = 0;
1714         do {
1715                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1716                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1717                         continue;
1718                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1719                         continue;
1720                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1721                         continue;
1722                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1723                         ++open_braces;
1724                         continue;
1725                 }
1726                 break;
1727         } while (true);
1728         return open_braces;
1729 }
1730
1731
1732 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1733         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1734 {
1735         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1736         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1737         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1738         // When using regexp, braces are hacked already by escape_for_regex()
1739         par_as_string = normalize(ds, !use_regexp);
1740         open_braces = 0;
1741         close_wildcards = 0;
1742
1743         size_t lead_size = 0;
1744         // correct the language settings
1745         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1746         if (opt.ignoreformat) {
1747                 if (!use_regexp) {
1748                         // if par_as_string_nolead were emty,
1749                         // the following call to findAux will always *find* the string
1750                         // in the checked data, and thus always using the slow
1751                         // examining of the current text part.
1752                         par_as_string_nolead = par_as_string;
1753                 }
1754         } else {
1755                 lead_size = identifyLeading(par_as_string);
1756                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1757                 lead_as_string = par_as_string.substr(0, lead_size);
1758                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1759         }
1760
1761         if (!use_regexp) {
1762                 open_braces = identifyClosing(par_as_string);
1763                 identifyClosing(par_as_string_nolead);
1764                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1765                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1766         } else {
1767                 string lead_as_regexp;
1768                 if (lead_size > 0) {
1769                         // @todo No need to search for \regexp{} insets in leading material
1770                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1771                         par_as_string = par_as_string_nolead;
1772                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1773                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1774                 }
1775                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1776                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1777                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1778                 if (
1779                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1780                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1781                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1782                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1783                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1784                         || regex_replace(par_as_string, par_as_string,
1785                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1786                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1787                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1788                         ) {
1789                         ++close_wildcards;
1790                 }
1791                 if (!opt.ignoreformat) {
1792                         // Remove extra '\}' at end
1793                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1794                                 open_braces++;
1795                         }
1796                         // save '\.'
1797                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1798                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1799                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1800                         // replace '[^...]' with '[^...\}\{\\]'
1801                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1802                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1803                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1804                         // restore '\.'
1805                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1806                 }
1807                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1808                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1809                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
1810                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1811
1812                 // If entered regexp must match at begin of searched string buffer
1813                 // Kornel: Added parentheses to use $1 for size of the leading string
1814                 string regexp_str;
1815                 string regexp2_str;
1816                 {
1817                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1818                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
1819                         // so the convert has no effect in that case
1820                         for (int i = 8; i > 0; --i) {
1821                                 string orig = "\\\\" + std::to_string(i);
1822                                 string dest = "\\" + std::to_string(i+1);
1823                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
1824                         }
1825                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1826                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1827                 }
1828                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1829                 regexp = lyx::regex(regexp_str);
1830
1831                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1832                 regexp2 = lyx::regex(regexp2_str);
1833         }
1834 }
1835
1836
1837 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1838 {
1839         if (at_begin &&
1840                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1841                 return 0;
1842
1843         docstring docstr = stringifyFromForSearch(opt, cur, len);
1844         string str = normalize(docstr, true);
1845         if (!opt.ignoreformat) {
1846                 str = removefontinfo(str);
1847                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
1848         }
1849         if (str.empty()) return(-1);
1850         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
1851         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1852
1853         if (use_regexp) {
1854                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1855                 regex const *p_regexp;
1856                 regex_constants::match_flag_type flags;
1857                 if (at_begin) {
1858                         flags = regex_constants::match_continuous;
1859                         p_regexp = &regexp;
1860                 } else {
1861                         flags = regex_constants::match_default;
1862                         p_regexp = &regexp2;
1863                 }
1864                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1865                 if (re_it == sregex_iterator())
1866                         return 0;
1867                 match_results<string::const_iterator> const & m = *re_it;
1868
1869                 if (0) { // Kornel Benko: DO NOT CHECKK
1870                         // Check braces on the segment that matched the entire regexp expression,
1871                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
1872                         if (!braces_match(m[0].first, m[0].second, open_braces))
1873                                 return 0;
1874                 }
1875
1876                 // Check braces on segments that matched all (.*?) subexpressions,
1877                 // except the last "padding" one inserted by lyx.
1878                 for (size_t i = 1; i < m.size() - 1; ++i)
1879                         if (!braces_match(m[i].first, m[i].second, open_braces))
1880                                 return 0;
1881
1882                 // Exclude from the returned match length any length
1883                 // due to close wildcards added at end of regexp
1884                 // and also the length of the leading (e.g. '\emph{')
1885                 //
1886                 // Whole found string, including the leading: m[0].second - m[0].first
1887                 // Size of the leading string: m[1].second - m[1].first
1888                 int leadingsize = 0;
1889                 if (m.size() > 1)
1890                         leadingsize = m[1].second - m[1].first;
1891                 int result;
1892                 for (size_t i = 0; i < m.size(); i++) {
1893                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
1894                 }
1895                 if (close_wildcards == 0)
1896                         result = m[0].second - m[0].first;
1897
1898                 else
1899                         result =  m[m.size() - close_wildcards].first - m[0].first;
1900
1901                 if (result > leadingsize)
1902                         result -= leadingsize;
1903                 else
1904                         result = 0;
1905                 return(result);
1906         }
1907
1908         // else !use_regexp: but all code paths above return
1909         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1910                                  << par_as_string << "', str='" << str << "'");
1911         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1912                                  << lead_as_string << "', par_as_string_nolead='"
1913                                  << par_as_string_nolead << "'");
1914
1915         if (at_begin) {
1916                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1917                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1918                 if (str.substr(0, par_as_string.size()) == par_as_string)
1919                         return par_as_string.size();
1920         } else {
1921                 size_t pos = str.find(par_as_string_nolead);
1922                 if (pos != string::npos)
1923                         return par_as_string.size();
1924         }
1925         return 0;
1926 }
1927
1928
1929 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1930 {
1931         int res = findAux(cur, len, at_begin);
1932         LYXERR(Debug::FIND,
1933                "res=" << res << ", at_begin=" << at_begin
1934                << ", matchword=" << opt.matchword
1935                << ", inTexted=" << cur.inTexted());
1936         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1937                 return res;
1938         Paragraph const & par = cur.paragraph();
1939         bool ws_left = (cur.pos() > 0)
1940                 ? par.isWordSeparator(cur.pos() - 1)
1941                 : true;
1942         bool ws_right = (cur.pos() + res < par.size())
1943                 ? par.isWordSeparator(cur.pos() + res)
1944                 : true;
1945         LYXERR(Debug::FIND,
1946                "cur.pos()=" << cur.pos() << ", res=" << res
1947                << ", separ: " << ws_left << ", " << ws_right
1948                << endl);
1949         if (ws_left && ws_right)
1950                 return res;
1951         return 0;
1952 }
1953
1954
1955 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1956 {
1957         string t;
1958         if (! opt.casesensitive)
1959                 t = lyx::to_utf8(lowercase(s));
1960         else
1961                 t = lyx::to_utf8(s);
1962         // Remove \n at begin
1963         while (!t.empty() && t[0] == '\n')
1964                 t = t.substr(1);
1965         // Remove \n at end
1966         while (!t.empty() && t[t.size() - 1] == '\n')
1967                 t = t.substr(0, t.size() - 1);
1968         size_t pos;
1969         // Replace all other \n with spaces
1970         while ((pos = t.find("\n")) != string::npos)
1971                 t.replace(pos, 1, " ");
1972         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1973         // Kornel: Added textsl, textsf, textit, texttt and noun
1974         // + allow to seach for colored text too
1975         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1976         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
1977                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1978         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
1979                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1980
1981         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
1982         // FIXME - check what preceeds the brace
1983         if (hack_braces) {
1984                 if (opt.ignoreformat)
1985                         while (regex_replace(t, t, "\\{", "_x_<")
1986                                || regex_replace(t, t, "\\}", "_x_>"))
1987                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1988                 else
1989                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1990                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1991                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1992         }
1993
1994         return t;
1995 }
1996
1997
1998 docstring stringifyFromCursor(DocIterator const & cur, int len)
1999 {
2000         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2001         if (cur.inTexted()) {
2002                 Paragraph const & par = cur.paragraph();
2003                 // TODO what about searching beyond/across paragraph breaks ?
2004                 // TODO Try adding a AS_STR_INSERTS as last arg
2005                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2006                         int(par.size()) : cur.pos() + len;
2007                 OutputParams runparams(&cur.buffer()->params().encoding());
2008                 runparams.nice = true;
2009                 runparams.flavor = OutputParams::LATEX;
2010                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2011                 // No side effect of file copying and image conversion
2012                 runparams.dryrun = true;
2013                 LYXERR(Debug::FIND, "Stringifying with cur: "
2014                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
2015                 return par.asString(cur.pos(), end,
2016                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2017                         &runparams);
2018         } else if (cur.inMathed()) {
2019                 docstring s;
2020                 CursorSlice cs = cur.top();
2021                 MathData md = cs.cell();
2022                 MathData::const_iterator it_end =
2023                         (( len == -1 || cs.pos() + len > int(md.size()))
2024                          ? md.end()
2025                          : md.begin() + cs.pos() + len );
2026                 for (MathData::const_iterator it = md.begin() + cs.pos();
2027                      it != it_end; ++it)
2028                         s = s + asString(*it);
2029                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2030                 return s;
2031         }
2032         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2033         return docstring();
2034 }
2035
2036
2037 /** Computes the LaTeX export of buf starting from cur and ending len positions
2038  * after cur, if len is positive, or at the paragraph or innermost inset end
2039  * if len is -1.
2040  */
2041 docstring latexifyFromCursor(DocIterator const & cur, int len)
2042 {
2043         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2044         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2045                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2046         Buffer const & buf = *cur.buffer();
2047
2048         odocstringstream ods;
2049         otexstream os(ods);
2050         OutputParams runparams(&buf.params().encoding());
2051         runparams.nice = false;
2052         runparams.flavor = OutputParams::LATEX;
2053         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2054         // No side effect of file copying and image conversion
2055         runparams.dryrun = true;
2056         runparams.for_search = true;
2057
2058         if (cur.inTexted()) {
2059                 // @TODO what about searching beyond/across paragraph breaks ?
2060                 pos_type endpos = cur.paragraph().size();
2061                 if (len != -1 && endpos > cur.pos() + len)
2062                         endpos = cur.pos() + len;
2063                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2064                           string(), cur.pos(), endpos);
2065                 string s = lyx::to_utf8(ods.str());
2066                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2067                 return(lyx::from_utf8(s));
2068         } else if (cur.inMathed()) {
2069                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2070                 for (int s = cur.depth() - 1; s >= 0; --s) {
2071                         CursorSlice const & cs = cur[s];
2072                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2073                                 WriteStream ws(os);
2074                                 cs.asInsetMath()->asHullInset()->header_write(ws);
2075                                 break;
2076                         }
2077                 }
2078
2079                 CursorSlice const & cs = cur.top();
2080                 MathData md = cs.cell();
2081                 MathData::const_iterator it_end =
2082                         ((len == -1 || cs.pos() + len > int(md.size()))
2083                          ? md.end()
2084                          : md.begin() + cs.pos() + len);
2085                 for (MathData::const_iterator it = md.begin() + cs.pos();
2086                      it != it_end; ++it)
2087                         ods << asString(*it);
2088
2089                 // Retrieve the math environment type, and add '$' or '$]'
2090                 // or others (\end{equation}) accordingly
2091                 for (int s = cur.depth() - 1; s >= 0; --s) {
2092                         CursorSlice const & cs2 = cur[s];
2093                         InsetMath * inset = cs2.asInsetMath();
2094                         if (inset && inset->asHullInset()) {
2095                                 WriteStream ws(os);
2096                                 inset->asHullInset()->footer_write(ws);
2097                                 break;
2098                         }
2099                 }
2100                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2101         } else {
2102                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2103         }
2104         return ods.str();
2105 }
2106
2107
2108 /** Finalize an advanced find operation, advancing the cursor to the innermost
2109  ** position that matches, plus computing the length of the matching text to
2110  ** be selected
2111  **/
2112 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2113 {
2114         // Search the foremost position that matches (avoids find of entire math
2115         // inset when match at start of it)
2116         size_t d;
2117         DocIterator old_cur(cur.buffer());
2118         do {
2119                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2120                 d = cur.depth();
2121                 old_cur = cur;
2122                 cur.forwardPos();
2123         } while (cur && cur.depth() > d && match(cur) > 0);
2124         cur = old_cur;
2125         if (match(cur) <= 0) return 0;
2126         LYXERR(Debug::FIND, "Ok");
2127
2128         // Compute the match length
2129         int len = 1;
2130         if (cur.pos() + len > cur.lastpos())
2131                 return 0;
2132         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2133         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2134                 ++len;
2135                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2136         }
2137         // Length of matched text (different from len param)
2138         int old_len = match(cur, len);
2139         if (old_len < 0) old_len = 0;
2140         int new_len;
2141         // Greedy behaviour while matching regexps
2142         while ((new_len = match(cur, len + 1)) > old_len) {
2143                 ++len;
2144                 old_len = new_len;
2145                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
2146         }
2147         return len;
2148 }
2149
2150
2151 /// Finds forward
2152 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2153 {
2154         if (!cur)
2155                 return 0;
2156         while (!theApp()->longOperationCancelled() && cur) {
2157                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2158                 int match_len = match(cur, -1, false);
2159                 LYXERR(Debug::FIND, "match_len: " << match_len);
2160                 if (match_len > 0) {
2161                         int match_len_zero_count = 0;
2162                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2163                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2164                                 int match_len2 = match(cur);
2165                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2166                                 if (match_len2 > 0) {
2167                                         // Sometimes in finalize we understand it wasn't a match
2168                                         // and we need to continue the outest loop
2169                                         int len = findAdvFinalize(cur, match);
2170                                         if (len > 0) {
2171                                                 return len;
2172                                         }
2173                                 }
2174                                 if (match_len2 >= 0) {
2175                                         if (match_len2 == 0)
2176                                                 match_len_zero_count++;
2177                                         else
2178                                                 match_len_zero_count = 0;
2179                                 }
2180                                 else {
2181                                         if (++match_len_zero_count > 3) {
2182                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2183                                                 match_len_zero_count = 0;
2184                                         }
2185                                         break;
2186                                 }
2187                         }
2188                         if (!cur)
2189                                 return 0;
2190                 }
2191                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2192                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2193                         cur.forwardPar();
2194                 } else {
2195                         // This should exit nested insets, if any, or otherwise undefine the currsor.
2196                         cur.pos() = cur.lastpos();
2197                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2198                         cur.forwardPos();
2199                 }
2200         }
2201         return 0;
2202 }
2203
2204
2205 /// Find the most backward consecutive match within same paragraph while searching backwards.
2206 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2207 {
2208         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2209         DocIterator tmp_cur = cur;
2210         int len = findAdvFinalize(tmp_cur, match);
2211         Inset & inset = cur.inset();
2212         for (; cur != cur_begin; cur.backwardPos()) {
2213                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2214                 DocIterator new_cur = cur;
2215                 new_cur.backwardPos();
2216                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2217                         break;
2218                 int new_len = findAdvFinalize(new_cur, match);
2219                 if (new_len == len)
2220                         break;
2221                 len = new_len;
2222         }
2223         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2224         return len;
2225 }
2226
2227
2228 /// Finds backwards
2229 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2230 {
2231         if (! cur)
2232                 return 0;
2233         // Backup of original position
2234         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2235         if (cur == cur_begin)
2236                 return 0;
2237         cur.backwardPos();
2238         DocIterator cur_orig(cur);
2239         bool pit_changed = false;
2240         do {
2241                 cur.pos() = 0;
2242                 bool found_match = match(cur, -1, false);
2243
2244                 if (found_match) {
2245                         if (pit_changed)
2246                                 cur.pos() = cur.lastpos();
2247                         else
2248                                 cur.pos() = cur_orig.pos();
2249                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2250                         DocIterator cur_prev_iter;
2251                         do {
2252                                 found_match = match(cur);
2253                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2254                                        << found_match << ", cur: " << cur);
2255                                 if (found_match)
2256                                         return findMostBackwards(cur, match);
2257
2258                                 // Stop if begin of document reached
2259                                 if (cur == cur_begin)
2260                                         break;
2261                                 cur_prev_iter = cur;
2262                                 cur.backwardPos();
2263                         } while (true);
2264                 }
2265                 if (cur == cur_begin)
2266                         break;
2267                 if (cur.pit() > 0)
2268                         --cur.pit();
2269                 else
2270                         cur.backwardPos();
2271                 pit_changed = true;
2272         } while (!theApp()->longOperationCancelled());
2273         return 0;
2274 }
2275
2276
2277 } // namespace
2278
2279
2280 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2281                                  DocIterator const & cur, int len)
2282 {
2283         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2284                 return docstring();
2285         if (!opt.ignoreformat)
2286                 return latexifyFromCursor(cur, len);
2287         else
2288                 return stringifyFromCursor(cur, len);
2289 }
2290
2291
2292 FindAndReplaceOptions::FindAndReplaceOptions(
2293         docstring const & find_buf_name, bool casesensitive,
2294         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2295         docstring const & repl_buf_name, bool keep_case,
2296         SearchScope scope, SearchRestriction restr)
2297         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2298           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2299           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2300 {
2301 }
2302
2303
2304 namespace {
2305
2306
2307 /** Check if 'len' letters following cursor are all non-lowercase */
2308 static bool allNonLowercase(Cursor const & cur, int len)
2309 {
2310         pos_type beg_pos = cur.selectionBegin().pos();
2311         pos_type end_pos = cur.selectionBegin().pos() + len;
2312         if (len > cur.lastpos() + 1 - beg_pos) {
2313                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2314                 len = cur.lastpos() + 1 - beg_pos;
2315                 end_pos = beg_pos + len;
2316         }
2317         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2318                 if (isLowerCase(cur.paragraph().getChar(pos)))
2319                         return false;
2320         return true;
2321 }
2322
2323
2324 /** Check if first letter is upper case and second one is lower case */
2325 static bool firstUppercase(Cursor const & cur)
2326 {
2327         char_type ch1, ch2;
2328         pos_type pos = cur.selectionBegin().pos();
2329         if (pos >= cur.lastpos() - 1) {
2330                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2331                 return false;
2332         }
2333         ch1 = cur.paragraph().getChar(pos);
2334         ch2 = cur.paragraph().getChar(pos + 1);
2335         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2336         LYXERR(Debug::FIND, "firstUppercase(): "
2337                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2338                << ch2 << "(" << char(ch2) << ")"
2339                << ", result=" << result << ", cur=" << cur);
2340         return result;
2341 }
2342
2343
2344 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2345  **
2346  ** \fixme What to do with possible further paragraphs in replace buffer ?
2347  **/
2348 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2349 {
2350         ParagraphList::iterator pit = buffer.paragraphs().begin();
2351         LASSERT(pit->size() >= 1, /**/);
2352         pos_type right = pos_type(1);
2353         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2354         right = pit->size();
2355         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2356 }
2357
2358 } // namespace
2359
2360 ///
2361 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2362 {
2363         Cursor & cur = bv->cursor();
2364         if (opt.repl_buf_name == docstring()
2365             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2366             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2367                 return;
2368
2369         DocIterator sel_beg = cur.selectionBegin();
2370         DocIterator sel_end = cur.selectionEnd();
2371         if (&sel_beg.inset() != &sel_end.inset()
2372             || sel_beg.pit() != sel_end.pit()
2373             || sel_beg.idx() != sel_end.idx())
2374                 return;
2375         int sel_len = sel_end.pos() - sel_beg.pos();
2376         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2377                << ", sel_len: " << sel_len << endl);
2378         if (sel_len == 0)
2379                 return;
2380         LASSERT(sel_len > 0, return);
2381
2382         if (!matchAdv(sel_beg, sel_len))
2383                 return;
2384
2385         // Build a copy of the replace buffer, adapted to the KeepCase option
2386         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2387         ostringstream oss;
2388         repl_buffer_orig.write(oss);
2389         string lyx = oss.str();
2390         Buffer repl_buffer("", false);
2391         repl_buffer.setUnnamed(true);
2392         LASSERT(repl_buffer.readString(lyx), return);
2393         if (opt.keep_case && sel_len >= 2) {
2394                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2395                 if (cur.inTexted()) {
2396                         if (firstUppercase(cur))
2397                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2398                         else if (allNonLowercase(cur, sel_len))
2399                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2400                 }
2401         }
2402         cap::cutSelection(cur, false);
2403         if (cur.inTexted()) {
2404                 repl_buffer.changeLanguage(
2405                         repl_buffer.language(),
2406                         cur.getFont().language());
2407                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2408                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2409                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2410                                         repl_buffer.params().documentClassPtr(),
2411                                         bv->buffer().errorList("Paste"));
2412                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2413                 sel_len = repl_buffer.paragraphs().begin()->size();
2414         } else if (cur.inMathed()) {
2415                 odocstringstream ods;
2416                 otexstream os(ods);
2417                 OutputParams runparams(&repl_buffer.params().encoding());
2418                 runparams.nice = false;
2419                 runparams.flavor = OutputParams::LATEX;
2420                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2421                 runparams.dryrun = true;
2422                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2423                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2424                 docstring repl_latex = ods.str();
2425                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2426                 string s;
2427                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2428                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2429                 repl_latex = from_utf8(s);
2430                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2431                 MathData ar(cur.buffer());
2432                 asArray(repl_latex, ar, Parse::NORMAL);
2433                 cur.insert(ar);
2434                 sel_len = ar.size();
2435                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2436         }
2437         if (cur.pos() >= sel_len)
2438                 cur.pos() -= sel_len;
2439         else
2440                 cur.pos() = 0;
2441         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2442         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2443         bv->processUpdateFlags(Update::Force);
2444 }
2445
2446
2447 /// Perform a FindAdv operation.
2448 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2449 {
2450         DocIterator cur;
2451         int match_len = 0;
2452
2453         // e.g., when invoking word-findadv from mini-buffer wither with
2454         //       wrong options syntax or before ever opening advanced F&R pane
2455         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2456                 return false;
2457
2458         try {
2459                 MatchStringAdv matchAdv(bv->buffer(), opt);
2460                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2461                 if (length > 0)
2462                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2463                 findAdvReplace(bv, opt, matchAdv);
2464                 cur = bv->cursor();
2465                 if (opt.forward)
2466                         match_len = findForwardAdv(cur, matchAdv);
2467                 else
2468                         match_len = findBackwardsAdv(cur, matchAdv);
2469         } catch (...) {
2470                 // This may only be raised by lyx::regex()
2471                 bv->message(_("Invalid regular expression!"));
2472                 return false;
2473         }
2474
2475         if (match_len == 0) {
2476                 bv->message(_("Match not found!"));
2477                 return false;
2478         }
2479
2480         bv->message(_("Match found!"));
2481
2482         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2483         bv->putSelectionAt(cur, match_len, !opt.forward);
2484
2485         return true;
2486 }
2487
2488
2489 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2490 {
2491         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2492            << opt.casesensitive << ' '
2493            << opt.matchword << ' '
2494            << opt.forward << ' '
2495            << opt.expandmacros << ' '
2496            << opt.ignoreformat << ' '
2497            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2498            << opt.keep_case << ' '
2499            << int(opt.scope) << ' '
2500            << int(opt.restr);
2501
2502         LYXERR(Debug::FIND, "built: " << os.str());
2503
2504         return os;
2505 }
2506
2507
2508 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2509 {
2510         LYXERR(Debug::FIND, "parsing");
2511         string s;
2512         string line;
2513         getline(is, line);
2514         while (line != "EOSS") {
2515                 if (! s.empty())
2516                         s = s + "\n";
2517                 s = s + line;
2518                 if (is.eof())   // Tolerate malformed request
2519                         break;
2520                 getline(is, line);
2521         }
2522         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2523         opt.find_buf_name = from_utf8(s);
2524         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2525         is.get();       // Waste space before replace string
2526         s = "";
2527         getline(is, line);
2528         while (line != "EOSS") {
2529                 if (! s.empty())
2530                         s = s + "\n";
2531                 s = s + line;
2532                 if (is.eof())   // Tolerate malformed request
2533                         break;
2534                 getline(is, line);
2535         }
2536         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2537         opt.repl_buf_name = from_utf8(s);
2538         is >> opt.keep_case;
2539         int i;
2540         is >> i;
2541         opt.scope = FindAndReplaceOptions::SearchScope(i);
2542         is >> i;
2543         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2544
2545         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2546                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2547                << opt.scope << ' ' << opt.restr);
2548         return is;
2549 }
2550
2551 } // namespace lyx