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