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