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