]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
* Allow to set language package on a per-document basis (fixes bug 2909).
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/alert.h"
37
38 #include "mathed/InsetMath.h"
39 #include "mathed/InsetMathGrid.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathStream.h"
42
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49
50 #include "support/regex.h"
51 #include <boost/next_prior.hpp>
52
53 using namespace std;
54 using namespace lyx::support;
55
56 namespace lyx {
57
58 namespace {
59
60 bool parse_bool(docstring & howto)
61 {
62         if (howto.empty())
63                 return false;
64         docstring var;
65         howto = split(howto, var, ' ');
66         return var == "1";
67 }
68
69
70 class MatchString : public binary_function<Paragraph, pos_type, int>
71 {
72 public:
73         MatchString(docstring const & str, bool cs, bool mw)
74                 : str(str), case_sens(cs), whole_words(mw)
75         {}
76
77         // returns true if the specified string is at the specified position
78         // del specifies whether deleted strings in ct mode will be considered
79         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
80         {
81                 return par.find(str, case_sens, whole_words, pos, del);
82         }
83
84 private:
85         // search string
86         docstring str;
87         // case sensitive
88         bool case_sens;
89         // match whole words only
90         bool whole_words;
91 };
92
93
94 int findForward(DocIterator & cur, MatchString const & match,
95                  bool find_del = true)
96 {
97         for (; cur; cur.forwardChar())
98                 if (cur.inTexted()) {
99                         int len = match(cur.paragraph(), cur.pos(), find_del);
100                         if (len > 0)
101                                 return len;
102                 }
103         return 0;
104 }
105
106
107 int findBackwards(DocIterator & cur, MatchString const & match,
108                  bool find_del = true)
109 {
110         while (cur) {
111                 cur.backwardChar();
112                 if (cur.inTexted()) {
113                         int len = match(cur.paragraph(), cur.pos(), find_del);
114                         if (len > 0)
115                                 return len;
116                 }
117         }
118         return 0;
119 }
120
121
122 bool findChange(DocIterator & cur, bool next)
123 {
124         if (!next)
125                 cur.backwardPos();
126         for (; cur; next ? cur.forwardPos() : cur.backwardPos())
127                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
128                         if (!next)
129                                 // if we search backwards, take a step forward
130                                 // to correctly set the anchor
131                                 cur.forwardPos();
132                         return true;
133                 }
134
135         return false;
136 }
137
138
139 bool searchAllowed(docstring const & str)
140 {
141         if (str.empty()) {
142                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
143                 return false;
144         }
145         return true;
146 }
147
148
149 bool findOne(BufferView * bv, docstring const & searchstr,
150         bool case_sens, bool whole, bool forward, bool find_del = true)
151 {
152         if (!searchAllowed(searchstr))
153                 return false;
154
155         DocIterator cur = bv->cursor();
156
157         MatchString const match(searchstr, case_sens, whole);
158
159         int match_len = forward ? findForward(cur, match, find_del) :
160                           findBackwards(cur, match, find_del);
161
162         if (match_len > 0)
163                 bv->putSelectionAt(cur, match_len, !forward);
164
165         return match_len > 0;
166 }
167
168
169 int replaceAll(BufferView * bv,
170                docstring const & searchstr, docstring const & replacestr,
171                bool case_sens, bool whole)
172 {
173         Buffer & buf = bv->buffer();
174
175         if (!searchAllowed(searchstr) || buf.isReadonly())
176                 return 0;
177
178         DocIterator cur_orig(bv->cursor());
179
180         MatchString const match(searchstr, case_sens, whole);
181         int num = 0;
182
183         int const rsize = replacestr.size();
184         int const ssize = searchstr.size();
185
186         Cursor cur(*bv);
187         cur.setCursor(doc_iterator_begin(&buf));
188         int match_len = findForward(cur, match, false);
189         while (match_len > 0) {
190                 // Backup current cursor position and font.
191                 pos_type const pos = cur.pos();
192                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
193                 cur.recordUndo();
194                 int striked = ssize - cur.paragraph().eraseChars(pos, pos + match_len,
195                                                             buf.params().trackChanges);
196                 cur.paragraph().insert(pos, replacestr, font,
197                                        Change(buf.params().trackChanges ?
198                                               Change::INSERTED : Change::UNCHANGED));
199                 for (int i = 0; i < rsize + striked; ++i)
200                         cur.forwardChar();
201                 ++num;
202                 match_len = findForward(cur, match, false);
203         }
204
205         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
206
207         cur_orig.fixIfBroken();
208         bv->setCursor(cur_orig);
209
210         return num;
211 }
212
213
214 // the idea here is that we are going to replace the string that
215 // is selected IF it is the search string. 
216 // if there is a selection, but it is not the search string, then
217 // we basically ignore it. (FIXME We ought to replace only within
218 // the selection.)
219 // if there is no selection, then:
220 //  (i) if some search string has been provided, then we find it.
221 //      (think of how the dialog works when you hit "replace" the
222 //      first time.) 
223 // (ii) if no search string has been provided, then we treat the
224 //      word the cursor is in as the search string. (why? i have no
225 //      idea.) but this only works in text?
226 //
227 // returns the number of replacements made (one, if any) and 
228 // whether anything at all was done.
229 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
230             docstring const & replacestr, bool case_sens, 
231                         bool whole, bool forward)
232 {
233         Cursor & cur = bv->cursor();
234         if (!cur.selection()) {
235                 // no selection, non-empty search string: find it
236                 if (!searchstr.empty()) {
237                         findOne(bv, searchstr, case_sens, whole, forward);
238                         return pair<bool, int>(true, 0);
239                 }
240                 // empty search string
241                 if (!cur.inTexted())
242                         // bail in math
243                         return pair<bool, int>(false, 0);
244                 // select current word and treat it as the search string
245                 cur.innerText()->selectWord(cur, WHOLE_WORD);
246                 searchstr = cur.selectionAsString(false);
247         }
248         
249         // if we still don't have a search string, report the error
250         // and abort.
251         if (!searchAllowed(searchstr))
252                 return pair<bool, int>(false, 0);
253         
254         bool have_selection = cur.selection();
255         docstring const selected = cur.selectionAsString(false);
256         bool match = 
257                 case_sens ? searchstr == selected
258                     : compare_no_case(searchstr, selected) == 0;
259
260         // no selection or current selection is not search word:
261         // just find the search word
262         if (!have_selection || !match) {
263                 findOne(bv, searchstr, case_sens, whole, forward);
264                 return pair<bool, int>(true, 0);
265         }
266
267         // we're now actually ready to replace. if the buffer is
268         // read-only, we can't, though.
269         if (bv->buffer().isReadonly())
270                 return pair<bool, int>(false, 0);
271
272         cap::replaceSelectionWithString(cur, replacestr, forward);
273         if (forward) {
274                 cur.pos() += replacestr.length();
275                 LASSERT(cur.pos() <= cur.lastpos(), /* */);
276         } else {
277                 cur.pos() -= replacestr.length();
278                 LASSERT(cur.pos() >= 0, /* */);
279         }
280         findOne(bv, searchstr, case_sens, whole, forward, false);
281
282         return pair<bool, int>(true, 1);
283 }
284
285 } // namespace anon
286
287
288 docstring const find2string(docstring const & search,
289                          bool casesensitive, bool matchword, bool forward)
290 {
291         odocstringstream ss;
292         ss << search << '\n'
293            << int(casesensitive) << ' '
294            << int(matchword) << ' '
295            << int(forward);
296         return ss.str();
297 }
298
299
300 docstring const replace2string(docstring const & replace,
301         docstring const & search, bool casesensitive, bool matchword,
302         bool all, bool forward)
303 {
304         odocstringstream ss;
305         ss << replace << '\n'
306            << search << '\n'
307            << int(casesensitive) << ' '
308            << int(matchword) << ' '
309            << int(all) << ' '
310            << int(forward);
311         return ss.str();
312 }
313
314
315 bool lyxfind(BufferView * bv, FuncRequest const & ev)
316 {
317         if (!bv || ev.action() != LFUN_WORD_FIND)
318                 return false;
319
320         //lyxerr << "find called, cmd: " << ev << endl;
321
322         // data is of the form
323         // "<search>
324         //  <casesensitive> <matchword> <forward>"
325         docstring search;
326         docstring howto = split(ev.argument(), search, '\n');
327
328         bool casesensitive = parse_bool(howto);
329         bool matchword     = parse_bool(howto);
330         bool forward       = parse_bool(howto);
331
332         return findOne(bv, search, casesensitive, matchword, forward);
333 }
334
335
336 bool lyxreplace(BufferView * bv, 
337                 FuncRequest const & ev, bool has_deleted)
338 {
339         if (!bv || ev.action() != LFUN_WORD_REPLACE)
340                 return false;
341
342         // data is of the form
343         // "<search>
344         //  <replace>
345         //  <casesensitive> <matchword> <all> <forward>"
346         docstring search;
347         docstring rplc;
348         docstring howto = split(ev.argument(), rplc, '\n');
349         howto = split(howto, search, '\n');
350
351         bool casesensitive = parse_bool(howto);
352         bool matchword     = parse_bool(howto);
353         bool all           = parse_bool(howto);
354         bool forward       = parse_bool(howto);
355
356         int replace_count = 0;
357         bool update = false;
358
359         if (!has_deleted) {
360                 if (all) {
361                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
362                         update = replace_count > 0;
363                 } else {
364                         pair<bool, int> rv = 
365                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward);
366                         update = rv.first;
367                         replace_count = rv.second;
368                 }
369
370                 Buffer const & buf = bv->buffer();
371                 if (!update) {
372                         // emit message signal.
373                         buf.message(_("String not found!"));
374                 } else {
375                         if (replace_count == 0) {
376                                 buf.message(_("String found."));
377                         } else if (replace_count == 1) {
378                                 buf.message(_("String has been replaced."));
379                         } else {
380                                 docstring const str = 
381                                         bformat(_("%1$d strings have been replaced."), replace_count);
382                                 buf.message(str);
383                         }
384                 }
385         } else {
386                 // if we have deleted characters, we do not replace at all, but
387                 // rather search for the next occurence
388                 if (findOne(bv, search, casesensitive, matchword, forward))
389                         update = true;
390                 else
391                         bv->message(_("String not found!"));
392         }
393         return update;
394 }
395
396
397 bool findNextChange(BufferView * bv)
398 {
399         return findChange(bv, true);
400 }
401
402
403 bool findPreviousChange(BufferView * bv)
404 {
405         return findChange(bv, false);
406 }
407
408
409 bool findChange(BufferView * bv, bool next)
410 {
411         if (bv->cursor().selection()) {
412                 // set the cursor at the beginning or at the end of the selection
413                 // before searching. Otherwise, the current change will be found.
414                 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
415                         bv->cursor().setCursorToAnchor();
416         }
417
418         DocIterator cur = bv->cursor();
419
420         // Are we within a change ? Then first search forward (backward),
421         // clear the selection and search the other way around (see the end
422         // of this function). This will avoid changes to be selected half.
423         bool search_both_sides = false;
424         DocIterator tmpcur = cur;
425         // Leave math first
426         while (tmpcur.inMathed())
427                 tmpcur.pop_back();
428         Change change_next_pos
429                 = tmpcur.paragraph().lookupChange(tmpcur.pos());
430         if (change_next_pos.changed() && cur.inMathed()) {
431                 cur = tmpcur;
432                 search_both_sides = true;
433         } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
434                 Change change_prev_pos
435                         = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
436                 if (change_next_pos.isSimilarTo(change_prev_pos))
437                         search_both_sides = true;
438         }
439
440         if (!findChange(cur, next))
441                 return false;
442
443         bv->cursor().setCursor(cur);
444         bv->cursor().resetAnchor();
445
446         if (!next)
447                 // take a step into the change
448                 cur.backwardPos();
449
450         Change orig_change = cur.paragraph().lookupChange(cur.pos());
451
452         CursorSlice & tip = cur.top();
453         if (next) {
454                 for (; !tip.at_end(); tip.forwardPos()) {
455                         Change change = tip.paragraph().lookupChange(tip.pos());
456                         if (!change.isSimilarTo(orig_change))
457                                 break;
458                 }
459         } else {
460                 for (; !tip.at_begin();) {
461                         tip.backwardPos();
462                         Change change = tip.paragraph().lookupChange(tip.pos());
463                         if (!change.isSimilarTo(orig_change)) {
464                                 // take a step forward to correctly set the selection
465                                 tip.forwardPos();
466                                 break;
467                         }
468                 }
469         }
470
471         // Now put cursor to end of selection:
472         bv->cursor().setCursor(cur);
473         bv->cursor().setSelection();
474
475         if (search_both_sides) {
476                 bv->cursor().setSelection(false);
477                 findChange(bv, !next);
478         }
479
480         return true;
481 }
482
483 namespace {
484
485 typedef vector<pair<string, string> > Escapes;
486
487 /// A map of symbols and their escaped equivalent needed within a regex.
488 Escapes const & get_regexp_escapes()
489 {
490         static Escapes escape_map;
491         if (escape_map.empty()) {
492                 escape_map.push_back(pair<string, string>("\\", "\\\\"));
493                 escape_map.push_back(pair<string, string>("^", "\\^"));
494                 escape_map.push_back(pair<string, string>("$", "\\$"));
495                 escape_map.push_back(pair<string, string>("{", "\\{"));
496                 escape_map.push_back(pair<string, string>("}", "\\}"));
497                 escape_map.push_back(pair<string, string>("[", "\\["));
498                 escape_map.push_back(pair<string, string>("]", "\\]"));
499                 escape_map.push_back(pair<string, string>("(", "\\("));
500                 escape_map.push_back(pair<string, string>(")", "\\)"));
501                 escape_map.push_back(pair<string, string>("+", "\\+"));
502                 escape_map.push_back(pair<string, string>("*", "\\*"));
503                 escape_map.push_back(pair<string, string>(".", "\\."));
504         }
505         return escape_map;
506 }
507
508 /// A map of lyx escaped strings and their unescaped equivalent.
509 Escapes const & get_lyx_unescapes() {
510         static Escapes escape_map;
511         if (escape_map.empty()) {
512                 escape_map.push_back(pair<string, string>("{*}", "*"));
513                 escape_map.push_back(pair<string, string>("{[}", "["));
514                 escape_map.push_back(pair<string, string>("\\$", "$"));
515                 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
516                 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
517                 escape_map.push_back(pair<string, string>("\\sim ", "~"));
518                 escape_map.push_back(pair<string, string>("\\^", "^"));
519         }
520         return escape_map;
521 }
522
523 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
524  ** the found occurrence were escaped.
525  **/
526 string apply_escapes(string s, Escapes const & escape_map)
527 {
528         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
529         Escapes::const_iterator it;
530         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
531 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
532                 unsigned int pos = 0;
533                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
534                         s.replace(pos, it->first.length(), it->second);
535 //                      LYXERR(Debug::FIND, "After escape: " << s);
536                         pos += it->second.length();
537 //                      LYXERR(Debug::FIND, "pos: " << pos);
538                 }
539         }
540         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
541         return s;
542 }
543
544 /** Return the position of the closing brace matching the open one at s[pos],
545  ** or s.size() if not found.
546  **/
547 size_t find_matching_brace(string const & s, size_t pos)
548 {
549         LASSERT(s[pos] == '{', /* */);
550         int open_braces = 1;
551         for (++pos; pos < s.size(); ++pos) {
552                 if (s[pos] == '\\')
553                         ++pos;
554                 else if (s[pos] == '{')
555                         ++open_braces;
556                 else if (s[pos] == '}') {
557                         --open_braces;
558                         if (open_braces == 0)
559                                 return pos;
560                 }
561         }
562         return s.size();
563 }
564
565 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
566 string escape_for_regex(string s)
567 {
568         size_t pos = 0;
569         while (pos < s.size()) {
570                 size_t new_pos = s.find("\\regexp{{{", pos);
571                 if (new_pos == string::npos)
572                         new_pos = s.size();
573                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
574                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
575                 LYXERR(Debug::FIND, "t      : " << t);
576                 t = apply_escapes(t, get_regexp_escapes());
577                 LYXERR(Debug::FIND, "t      : " << t);
578                 s.replace(pos, new_pos - pos, t);
579                 new_pos = pos + t.size();
580                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
581                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
582                 if (new_pos == s.size())
583                         break;
584                 size_t end_pos = s.find("}}}", new_pos + 10); // find_matching_brace(s, new_pos + 7);
585                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
586                 t = apply_escapes(s.substr(new_pos + 10, end_pos - (new_pos + 10)), get_lyx_unescapes());
587                 LYXERR(Debug::FIND, "t      : " << t);
588                 if (end_pos == s.size()) {
589                         s.replace(new_pos, end_pos - new_pos, t);
590                         pos = s.size();
591                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
592                         break;
593                 }
594                 s.replace(new_pos, end_pos + 3 - new_pos, t);
595                 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
596                 pos = new_pos + t.size();
597                 LYXERR(Debug::FIND, "pos: " << pos);
598         }
599         return s;
600 }
601
602 /// Wrapper for lyx::regex_replace with simpler interface
603 bool regex_replace(string const & s, string & t, string const & searchstr,
604         string const & replacestr)
605 {
606         lyx::regex e(searchstr);
607         ostringstream oss;
608         ostream_iterator<char, char> it(oss);
609         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
610         // tolerate t and s be references to the same variable
611         bool rv = (s != oss.str());
612         t = oss.str();
613         return rv;
614 }
615
616 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
617  **
618  ** Verify that closed braces exactly match open braces. This avoids that, for example,
619  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
620  **
621  ** @param unmatched
622  ** Number of open braces that must remain open at the end for the verification to succeed.
623  **/
624 bool braces_match(string::const_iterator const & beg,
625                   string::const_iterator const & end,
626                   int unmatched = 0)
627 {
628         int open_pars = 0;
629         string::const_iterator it = beg;
630         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
631         for (; it != end; ++it) {
632                 // Skip escaped braces in the count
633                 if (*it == '\\') {
634                         ++it;
635                         if (it == end)
636                                 break;
637                 } else if (*it == '{') {
638                         ++open_pars;
639                 } else if (*it == '}') {
640                         if (open_pars == 0) {
641                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
642                                 return false;
643                         } else
644                                 --open_pars;
645                 }
646         }
647         if (open_pars != unmatched) {
648           LYXERR(Debug::FIND, "Found " << open_pars 
649                  << " instead of " << unmatched 
650                  << " unmatched open braces at the end of count");
651                         return false;
652         }
653         LYXERR(Debug::FIND, "Braces match as expected");
654         return true;
655 }
656
657 /** The class performing a match between a position in the document and the FindAdvOptions.
658  **/
659 class MatchStringAdv {
660 public:
661         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
662
663         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
664          ** constructor as opt.search, under the opt.* options settings.
665          **
666          ** @param at_begin
667          **     If set, then match is searched only against beginning of text starting at cur.
668          **     If unset, then match is searched anywhere in text starting at cur.
669          **
670          ** @return
671          ** The length of the matching text, or zero if no match was found.
672          **/
673         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
674
675 public:
676         /// buffer
677         lyx::Buffer * p_buf;
678         /// first buffer on which search was started
679         lyx::Buffer * const p_first_buf;
680         /// options
681         FindAndReplaceOptions const & opt;
682
683 private:
684         /// Auxiliary find method (does not account for opt.matchword)
685         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
686
687         /** Normalize a stringified or latexified LyX paragraph.
688          **
689          ** Normalize means:
690          ** <ul>
691          **   <li>if search is not casesensitive, then lowercase the string;
692          **   <li>remove any newline at begin or end of the string;
693          **   <li>replace any newline in the middle of the string with a simple space;
694          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
695          ** </ul>
696          **
697          ** @todo Normalization should also expand macros, if the corresponding
698          ** search option was checked.
699          **/
700         string normalize(docstring const & s) const;
701         // normalized string to search
702         string par_as_string;
703         // regular expression to use for searching
704         lyx::regex regexp;
705         // same as regexp, but prefixed with a ".*"
706         lyx::regex regexp2;
707         // unmatched open braces in the search string/regexp
708         int open_braces;
709         // number of (.*?) subexpressions added at end of search regexp for closing
710         // environments, math mode, styles, etc...
711         int close_wildcards;
712 };
713
714
715 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
716         : p_buf(&buf), p_first_buf(&buf), opt(opt)
717 {
718         par_as_string = normalize(opt.search);
719         open_braces = 0;
720         close_wildcards = 0;
721
722         if (! opt.regexp) {
723                 // Remove trailing closure of math, macros and environments, so to catch parts of them.
724                 do {
725                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
726                         if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
727                                         continue;
728                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
729                                         continue;
730                         // @todo need to account for open square braces as well ?
731                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
732                                         continue;
733                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
734                                         continue;
735                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
736                                 ++open_braces;
737                                 continue;
738                         }
739                         break;
740                 } while (true);
741                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
742                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
743         } else {
744                 par_as_string = escape_for_regex(par_as_string);
745                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
746                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
747                 if (
748                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
749                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
750                                 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
751                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
752                                 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
753                                 || regex_replace(par_as_string, par_as_string, 
754                                         "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
755                                 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
756                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
757                 ) {
758                         ++close_wildcards;
759                 }
760                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
761                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
762                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
763                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
764                 // If entered regexp must match at begin of searched string buffer
765                 regexp = lyx::regex(string("\\`") + par_as_string);
766                 // If entered regexp may match wherever in searched string buffer
767                 regexp2 = lyx::regex(string("\\`.*") + par_as_string);
768         }
769 }
770
771
772 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
773 {
774         docstring docstr = stringifyFromForSearch(opt, cur, len);
775         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
776         string str = normalize(docstr);
777         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
778         if (! opt.regexp) {
779                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
780                 if (at_begin) {
781                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
782                         if (str.substr(0, par_as_string.size()) == par_as_string)
783                                 return par_as_string.size();
784                 } else {
785                         string t = par_as_string;
786                         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\{", "")
787                                || regex_replace(t, t, "^\\$", "")
788                                || regex_replace(t, t, "^\\\\\\[ ", ""))
789                                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: " << t);
790                         size_t pos = str.find(t);
791                         if (pos != string::npos)
792                                 return par_as_string.size();
793                 }
794         } else {
795                 LYXERR(Debug::FIND, "Searching in regexp mode");
796                 // Try all possible regexp matches, 
797                 //until one that verifies the braces match test is found
798                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
799                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
800                 sregex_iterator re_it_end;
801                 for (; re_it != re_it_end; ++re_it) {
802                         match_results<string::const_iterator> const & m = *re_it;
803                         // Check braces on the segment that matched the entire regexp expression,
804                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
805                         if (!braces_match(m[0].first, m[0].second, open_braces))
806                                 return 0;
807                         // Check braces on segments that matched all (.*?) subexpressions.
808                         for (size_t i = 1; i < m.size(); ++i)
809                                 if (!braces_match(m[i].first, m[i].second))
810                                         return false;
811                         // Exclude from the returned match length any length 
812                         // due to close wildcards added at end of regexp
813                         if (close_wildcards == 0)
814                                 return m[0].second - m[0].first;
815                         else
816                                 return m[m.size() - close_wildcards].first - m[0].first;
817                 }
818         }
819         return 0;
820 }
821
822
823 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
824 {
825         int res = findAux(cur, len, at_begin);
826         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
827                 return res;
828         Paragraph const & par = cur.paragraph();
829         bool ws_left = cur.pos() > 0 ?
830                 par.isWordSeparator(cur.pos() - 1) : true;
831         bool ws_right = cur.pos() + res < par.size() ?
832                 par.isWordSeparator(cur.pos() + res) : true;
833         LYXERR(Debug::FIND,
834                "cur.pos()=" << cur.pos() << ", res=" << res
835                << ", separ: " << ws_left << ", " << ws_right
836                << endl);
837         if (ws_left && ws_right)
838                 return res;
839         return 0;
840 }
841
842
843 string MatchStringAdv::normalize(docstring const & s) const
844 {
845         string t;
846         if (! opt.casesensitive)
847                 t = lyx::to_utf8(lowercase(s));
848         else
849                 t = lyx::to_utf8(s);
850         // Remove \n at begin
851         while (t.size() > 0 && t[0] == '\n')
852                 t = t.substr(1);
853         // Remove \n at end
854         while (t.size() > 0 && t[t.size() - 1] == '\n')
855                 t = t.substr(0, t.size() - 1);
856         size_t pos;
857         // Replace all other \n with spaces
858         while ((pos = t.find("\n")) != string::npos)
859                 t.replace(pos, 1, " ");
860         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
861         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
862         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
863                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
864         return t;
865 }
866
867
868 docstring stringifyFromCursor(DocIterator const & cur, int len)
869 {
870         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
871         if (cur.inTexted()) {
872                         Paragraph const & par = cur.paragraph();
873                         // TODO what about searching beyond/across paragraph breaks ?
874                         // TODO Try adding a AS_STR_INSERTS as last arg
875                         pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
876                                 int(par.size()) : cur.pos() + len;
877                         OutputParams runparams(&cur.buffer()->params().encoding());
878                         odocstringstream os;
879                         runparams.nice = true;
880                         runparams.flavor = OutputParams::LATEX;
881                         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
882                         // No side effect of file copying and image conversion
883                         runparams.dryrun = true;
884                         LYXERR(Debug::FIND, "Stringifying with cur: " 
885                                 << cur << ", from pos: " << cur.pos() << ", end: " << end);
886                         return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
887         } else if (cur.inMathed()) {
888                         odocstringstream os;
889                         CursorSlice cs = cur.top();
890                         MathData md = cs.cell();
891                         MathData::const_iterator it_end = 
892                                 ( ( len == -1 || cs.pos() + len > int(md.size()) )
893                                         ? md.end() : md.begin() + cs.pos() + len );
894                         for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
895                                         os << *it;
896                         return os.str();
897         }
898         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
899         return docstring();
900 }
901
902
903 /** Computes the LaTeX export of buf starting from cur and ending len positions
904  * after cur, if len is positive, or at the paragraph or innermost inset end
905  * if len is -1.
906  */
907 docstring latexifyFromCursor(DocIterator const & cur, int len)
908 {
909         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
910         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
911                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
912         Buffer const & buf = *cur.buffer();
913         LASSERT(buf.isLatex(), /* */);
914
915         TexRow texrow;
916         odocstringstream ods;
917         otexstream os(ods);
918         OutputParams runparams(&buf.params().encoding());
919         runparams.nice = false;
920         runparams.flavor = OutputParams::LATEX;
921         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
922         // No side effect of file copying and image conversion
923         runparams.dryrun = true;
924
925         if (cur.inTexted()) {
926                 // @TODO what about searching beyond/across paragraph breaks ?
927                 pos_type endpos = cur.paragraph().size();
928                 if (len != -1 && endpos > cur.pos() + len)
929                         endpos = cur.pos() + len;
930                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, texrow, runparams,
931                         string(), cur.pos(), endpos);
932                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
933         } else if (cur.inMathed()) {
934                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
935                 for (int s = cur.depth() - 1; s >= 0; --s) {
936                                 CursorSlice const & cs = cur[s];
937                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
938                                                 WriteStream ws(ods);
939                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
940                                                 break;
941                                 }
942                 }
943
944                 CursorSlice const & cs = cur.top();
945                 MathData md = cs.cell();
946                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
947                         ? md.end() : md.begin() + cs.pos() + len );
948                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
949                                 ods << *it;
950
951                 // Retrieve the math environment type, and add '$' or '$]'
952                 // or others (\end{equation}) accordingly
953                 for (int s = cur.depth() - 1; s >= 0; --s) {
954                         CursorSlice const & cs = cur[s];
955                         InsetMath * inset = cs.asInsetMath();
956                         if (inset && inset->asHullInset()) {
957                                 WriteStream ws(ods);
958                                 inset->asHullInset()->footer_write(ws);
959                                 break;
960                         }
961                 }
962                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
963         } else {
964                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
965         }
966         return ods.str();
967 }
968
969
970 /** Finalize an advanced find operation, advancing the cursor to the innermost
971  ** position that matches, plus computing the length of the matching text to
972  ** be selected
973  **/
974 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
975 {
976         // Search the foremost position that matches (avoids find of entire math
977         // inset when match at start of it)
978         size_t d;
979         DocIterator old_cur(cur.buffer());
980         do {
981                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
982                 d = cur.depth();
983                 old_cur = cur;
984                 cur.forwardPos();
985         } while (cur && cur.depth() > d && match(cur) > 0);
986         cur = old_cur;
987         LASSERT(match(cur) > 0, /* */);
988         LYXERR(Debug::FIND, "Ok");
989
990         // Compute the match length
991         int len = 1;
992         if (cur.pos() + len > cur.lastpos())
993                 return 0;
994         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
995         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
996                 ++len;
997                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
998         }
999         // Length of matched text (different from len param)
1000         int old_len = match(cur, len);
1001         int new_len;
1002         // Greedy behaviour while matching regexps
1003         while ((new_len = match(cur, len + 1)) > old_len) {
1004                 ++len;
1005                 old_len = new_len;
1006                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1007         }
1008         return len;
1009 }
1010
1011
1012 /// Finds forward
1013 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1014 {
1015         if (!cur)
1016                 return 0;
1017         while (cur && !match(cur, -1, false)) {
1018                 if (cur.pit() < cur.lastpit())
1019                         cur.forwardPar();
1020                 else {
1021                         cur.forwardPos();
1022                 }
1023         }
1024         for (; cur; cur.forwardPos()) {
1025                 if (match(cur))
1026                         return findAdvFinalize(cur, match);
1027         }
1028         return 0;
1029 }
1030
1031
1032 /// Find the most backward consecutive match within same paragraph while searching backwards.
1033 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1034 {
1035         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1036         DocIterator tmp_cur = cur;
1037         int len = findAdvFinalize(tmp_cur, match);
1038         Inset & inset = cur.inset();
1039         for (; cur != cur_begin; cur.backwardPos()) {
1040                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1041                 DocIterator new_cur = cur;
1042                 new_cur.backwardPos();
1043                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1044                         break;
1045                 int new_len = findAdvFinalize(new_cur, match);
1046                 if (new_len == len)
1047                         break;
1048                 len = new_len;
1049         }
1050         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1051         return len;
1052 }
1053
1054
1055 /// Finds backwards
1056 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1057         if (! cur)
1058                 return 0;
1059         // Backup of original position
1060         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1061         if (cur == cur_begin)
1062                 return 0;
1063         cur.backwardPos();
1064         DocIterator cur_orig(cur);
1065         bool found_match;
1066         bool pit_changed = false;
1067         found_match = false;
1068         do {
1069                 cur.pos() = 0;
1070                 found_match = match(cur, -1, false);
1071
1072                 if (found_match) {
1073                         if (pit_changed)
1074                                 cur.pos() = cur.lastpos();
1075                         else
1076                                 cur.pos() = cur_orig.pos();
1077                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1078                         DocIterator cur_prev_iter;
1079                         do {
1080                                 found_match = match(cur);
1081                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1082                                        << found_match << ", cur: " << cur);
1083                                 if (found_match)
1084                                         return findMostBackwards(cur, match);
1085
1086                                 // Stop if begin of document reached
1087                                 if (cur == cur_begin)
1088                                         break;
1089                                 cur_prev_iter = cur;
1090                                 cur.backwardPos();
1091                         } while (true);
1092                 }
1093                 if (cur == cur_begin)
1094                         break;
1095                 if (cur.pit() > 0)
1096                         --cur.pit();
1097                 else
1098                         cur.backwardPos();
1099                 pit_changed = true;
1100         } while (true);
1101         return 0;
1102 }
1103
1104
1105 } // anonym namespace
1106
1107
1108 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1109         DocIterator const & cur, int len)
1110 {
1111         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1112         if (!opt.ignoreformat)
1113                 return latexifyFromCursor(cur, len);
1114         else
1115                 return stringifyFromCursor(cur, len);
1116 }
1117
1118
1119 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1120         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1121         bool regexp, docstring const & replace, bool keep_case,
1122         SearchScope scope)
1123         : search(search), casesensitive(casesensitive), matchword(matchword),
1124         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1125         regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1126 {
1127 }
1128
1129
1130 namespace {
1131
1132
1133 /** Check if 'len' letters following cursor are all non-lowercase */
1134 static bool allNonLowercase(DocIterator const & cur, int len) {
1135         pos_type end_pos = cur.pos() + len;
1136         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1137                 if (isLowerCase(cur.paragraph().getChar(pos)))
1138                         return false;
1139         return true;
1140 }
1141
1142
1143 /** Check if first letter is upper case and second one is lower case */
1144 static bool firstUppercase(DocIterator const & cur) {
1145         char_type ch1, ch2;
1146         if (cur.pos() >= cur.lastpos() - 1) {
1147                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1148                 return false;
1149         }
1150         ch1 = cur.paragraph().getChar(cur.pos());
1151         ch2 = cur.paragraph().getChar(cur.pos()+1);
1152         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1153         LYXERR(Debug::FIND, "firstUppercase(): "
1154                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1155                << ch2 << "(" << char(ch2) << ")"
1156                << ", result=" << result << ", cur=" << cur);
1157         return result;
1158 }
1159
1160
1161 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1162  **
1163  ** \fixme What to do with possible further paragraphs in replace buffer ?
1164  **/
1165 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1166         ParagraphList::iterator pit = buffer.paragraphs().begin();
1167         pos_type right = pos_type(1);
1168         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1169         right = pit->size() + 1;
1170         pit->changeCase(buffer.params(), right, right, others_case);
1171 }
1172 } // anon namespace
1173
1174 ///
1175 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1176 {
1177         Cursor & cur = bv->cursor();
1178         if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING)))
1179                 return;
1180         DocIterator sel_beg = cur.selectionBegin();
1181         DocIterator sel_end = cur.selectionEnd();
1182         if (&sel_beg.inset() != &sel_end.inset()
1183             || sel_beg.pit() != sel_end.pit())
1184                 return;
1185         int sel_len = sel_end.pos() - sel_beg.pos();
1186         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1187                << ", sel_len: " << sel_len << endl);
1188         if (sel_len == 0)
1189                 return;
1190         LASSERT(sel_len > 0, /**/);
1191
1192         if (!matchAdv(sel_beg, sel_len))
1193                 return;
1194
1195         string lyx = to_utf8(opt.replace);
1196         // FIXME: Seems so stupid to me to rebuild a buffer here,
1197         // when we already have one (replace_work_area_.buffer())
1198         Buffer repl_buffer("", false);
1199         repl_buffer.setUnnamed(true);
1200         LASSERT(repl_buffer.readString(lyx), /**/);
1201         if (opt.keep_case && sel_len >= 2) {
1202                 if (cur.inTexted()) {
1203                         if (firstUppercase(cur))
1204                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1205                         else if (allNonLowercase(cur, sel_len))
1206                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1207                 }
1208         }
1209         cap::cutSelection(cur, false, false);
1210         if (!cur.inMathed()) {
1211                 repl_buffer.changeLanguage(
1212                         repl_buffer.language(),
1213                         cur.getFont().language());
1214                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1215                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1216                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1217                                         repl_buffer.params().documentClassPtr(),
1218                                         bv->buffer().errorList("Paste"));
1219                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1220                 sel_len = repl_buffer.paragraphs().begin()->size();
1221         } else {
1222                 odocstringstream ods;
1223                 otexstream os(ods);
1224                 OutputParams runparams(&repl_buffer.params().encoding());
1225                 runparams.nice = false;
1226                 runparams.flavor = OutputParams::LATEX;
1227                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1228                 runparams.dryrun = true;
1229                 TexRow texrow;
1230                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, texrow, runparams);
1231                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1232                 docstring repl_latex = ods.str();
1233                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1234                 string s;
1235                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1236                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1237                 repl_latex = from_utf8(s);
1238                 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1239                 sel_len = cur.niceInsert(repl_latex);
1240         }
1241         cur.pos() -= sel_len;
1242         if (cur.pos() < 0)
1243                 cur.pos() = 0;
1244         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << sel_len);
1245         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1246         bv->processUpdateFlags(Update::Force);
1247 }
1248
1249
1250 /// Perform a FindAdv operation.
1251 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1252 {
1253         DocIterator cur;
1254         int match_len = 0;
1255
1256         if (opt.search.empty()) {
1257                 bv->message(_("Search text is empty!"));
1258                 return false;
1259         }
1260
1261         try {
1262                 MatchStringAdv matchAdv(bv->buffer(), opt);
1263                 findAdvReplace(bv, opt, matchAdv);
1264                 cur = bv->cursor();
1265                 if (opt.forward)
1266                                 match_len = findForwardAdv(cur, matchAdv);
1267                 else
1268                                 match_len = findBackwardsAdv(cur, matchAdv);
1269         } catch (...) {
1270                 // This may only be raised by lyx::regex()
1271                 bv->message(_("Invalid regular expression!"));
1272                 return false;
1273         }
1274
1275         if (match_len == 0) {
1276                 bv->message(_("Match not found!"));
1277                 return false;
1278         }
1279
1280         bv->message(_("Match found!"));
1281
1282         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1283         bv->putSelectionAt(cur, match_len, !opt.forward);
1284
1285         return true;
1286 }
1287
1288
1289 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1290 {
1291         os << to_utf8(opt.search) << "\nEOSS\n"
1292            << opt.casesensitive << ' '
1293            << opt.matchword << ' '
1294            << opt.forward << ' '
1295            << opt.expandmacros << ' '
1296            << opt.ignoreformat << ' '
1297            << opt.regexp << ' '
1298            << to_utf8(opt.replace) << "\nEOSS\n"
1299            << opt.keep_case << ' '
1300            << int(opt.scope);
1301
1302         LYXERR(Debug::FIND, "built: " << os.str());
1303
1304         return os;
1305 }
1306
1307 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1308 {
1309         LYXERR(Debug::FIND, "parsing");
1310         string s;
1311         string line;
1312         getline(is, line);
1313         while (line != "EOSS") {
1314                 if (! s.empty())
1315                                 s = s + "\n";
1316                 s = s + line;
1317                 if (is.eof())   // Tolerate malformed request
1318                                 break;
1319                 getline(is, line);
1320         }
1321         LYXERR(Debug::FIND, "searching for: '" << s << "'");
1322         opt.search = from_utf8(s);
1323         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1324         is.get();       // Waste space before replace string
1325         s = "";
1326         getline(is, line);
1327         while (line != "EOSS") {
1328                 if (! s.empty())
1329                                 s = s + "\n";
1330                 s = s + line;
1331                 if (is.eof())   // Tolerate malformed request
1332                                 break;
1333                 getline(is, line);
1334         }
1335         is >> opt.keep_case;
1336         int i;
1337         is >> i;
1338         opt.scope = FindAndReplaceOptions::SearchScope(i);
1339         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1340                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1341         LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1342         opt.replace = from_utf8(s);
1343         return is;
1344 }
1345
1346 } // lyx namespace