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