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