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