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