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