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