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