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