]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Update previews after doing a find/replace (#7242)
[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/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
44
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
52
53 #include "support/regex.h"
54 #include <boost/next_prior.hpp>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60
61 namespace {
62
63 bool parse_bool(docstring & howto)
64 {
65         if (howto.empty())
66                 return false;
67         docstring var;
68         howto = split(howto, var, ' ');
69         return var == "1";
70 }
71
72
73 class MatchString : public binary_function<Paragraph, pos_type, int>
74 {
75 public:
76         MatchString(docstring const & str, bool cs, bool mw)
77                 : str(str), case_sens(cs), whole_words(mw)
78         {}
79
80         // returns true if the specified string is at the specified position
81         // del specifies whether deleted strings in ct mode will be considered
82         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
83         {
84                 return par.find(str, case_sens, whole_words, pos, del);
85         }
86
87 private:
88         // search string
89         docstring str;
90         // case sensitive
91         bool case_sens;
92         // match whole words only
93         bool whole_words;
94 };
95
96
97 int findForward(DocIterator & cur, MatchString const & match,
98                 bool find_del = true)
99 {
100         for (; cur; cur.forwardChar())
101                 if (cur.inTexted()) {
102                         int len = match(cur.paragraph(), cur.pos(), find_del);
103                         if (len > 0)
104                                 return len;
105                 }
106         return 0;
107 }
108
109
110 int findBackwards(DocIterator & cur, MatchString const & match,
111                   bool find_del = true)
112 {
113         while (cur) {
114                 cur.backwardChar();
115                 if (cur.inTexted()) {
116                         int len = match(cur.paragraph(), cur.pos(), find_del);
117                         if (len > 0)
118                                 return len;
119                 }
120         }
121         return 0;
122 }
123
124
125 bool searchAllowed(docstring const & str)
126 {
127         if (str.empty()) {
128                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
129                 return false;
130         }
131         return true;
132 }
133
134
135 bool findOne(BufferView * bv, docstring const & searchstr,
136              bool case_sens, bool whole, bool forward, bool find_del = true)
137 {
138         if (!searchAllowed(searchstr))
139                 return false;
140
141         DocIterator cur = forward 
142                 ? bv->cursor().selectionEnd() 
143                 : bv->cursor().selectionBegin();
144
145         MatchString const match(searchstr, case_sens, whole);
146
147         int match_len = forward
148                 ? findForward(cur, match, find_del)
149                 : findBackwards(cur, match, find_del);
150
151         if (match_len > 0)
152                 bv->putSelectionAt(cur, match_len, !forward);
153
154         return match_len > 0;
155 }
156
157
158 int replaceAll(BufferView * bv,
159                docstring const & searchstr, docstring const & replacestr,
160                bool case_sens, bool whole)
161 {
162         Buffer & buf = bv->buffer();
163
164         if (!searchAllowed(searchstr) || buf.isReadonly())
165                 return 0;
166
167         DocIterator cur_orig(bv->cursor());
168
169         MatchString const match(searchstr, case_sens, whole);
170         int num = 0;
171
172         int const rsize = replacestr.size();
173         int const ssize = searchstr.size();
174
175         Cursor cur(*bv);
176         cur.setCursor(doc_iterator_begin(&buf));
177         int match_len = findForward(cur, match, false);
178         while (match_len > 0) {
179                 // Backup current cursor position and font.
180                 pos_type const pos = cur.pos();
181                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
182                 cur.recordUndo();
183                 int striked = ssize -
184                         cur.paragraph().eraseChars(pos, pos + match_len,
185                                                    buf.params().track_changes);
186                 cur.paragraph().insert(pos, replacestr, font,
187                                        Change(buf.params().track_changes
188                                               ? Change::INSERTED
189                                               : Change::UNCHANGED));
190                 for (int i = 0; i < rsize + striked; ++i)
191                         cur.forwardChar();
192                 ++num;
193                 match_len = findForward(cur, match, false);
194         }
195
196         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
197
198         cur_orig.fixIfBroken();
199         bv->setCursor(cur_orig);
200
201         return num;
202 }
203
204
205 // the idea here is that we are going to replace the string that
206 // is selected IF it is the search string. 
207 // if there is a selection, but it is not the search string, then
208 // we basically ignore it. (FIXME We ought to replace only within
209 // the selection.)
210 // if there is no selection, then:
211 //  (i) if some search string has been provided, then we find it.
212 //      (think of how the dialog works when you hit "replace" the
213 //      first time.) 
214 // (ii) if no search string has been provided, then we treat the
215 //      word the cursor is in as the search string. (why? i have no
216 //      idea.) but this only works in text?
217 //
218 // returns the number of replacements made (one, if any) and 
219 // whether anything at all was done.
220 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
221                            docstring const & replacestr, bool case_sens,
222                            bool whole, bool forward, bool findnext)
223 {
224         Cursor & cur = bv->cursor();
225         if (!cur.selection()) {
226                 // no selection, non-empty search string: find it
227                 if (!searchstr.empty()) {
228                         findOne(bv, searchstr, case_sens, whole, forward);
229                         return make_pair(true, 0);
230                 }
231                 // empty search string
232                 if (!cur.inTexted())
233                         // bail in math
234                         return make_pair(false, 0);
235                 // select current word and treat it as the search string.
236                 // This causes a minor bug as undo will restore this selection,
237                 // which the user did not create (#8986).
238                 cur.innerText()->selectWord(cur, WHOLE_WORD);
239                 searchstr = cur.selectionAsString(false);
240         }
241         
242         // if we still don't have a search string, report the error
243         // and abort.
244         if (!searchAllowed(searchstr))
245                 return make_pair(false, 0);
246         
247         bool have_selection = cur.selection();
248         docstring const selected = cur.selectionAsString(false);
249         bool match = 
250                 case_sens
251                 ? searchstr == selected
252                 : compare_no_case(searchstr, selected) == 0;
253
254         // no selection or current selection is not search word:
255         // just find the search word
256         if (!have_selection || !match) {
257                 findOne(bv, searchstr, case_sens, whole, forward);
258                 return make_pair(true, 0);
259         }
260
261         // we're now actually ready to replace. if the buffer is
262         // read-only, we can't, though.
263         if (bv->buffer().isReadonly())
264                 return make_pair(false, 0);
265
266         cap::replaceSelectionWithString(cur, replacestr);
267         if (forward) {
268                 cur.pos() += replacestr.length();
269                 LASSERT(cur.pos() <= cur.lastpos(),
270                         cur.pos() = cur.lastpos());
271         }
272         if (findnext)
273                 findOne(bv, searchstr, case_sens, whole, forward, false);
274
275         return make_pair(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,
295                                bool casesensitive, bool matchword,
296                                bool all, bool forward, bool findnext)
297 {
298         odocstringstream ss;
299         ss << replace << '\n'
300            << search << '\n'
301            << int(casesensitive) << ' '
302            << int(matchword) << ' '
303            << int(all) << ' '
304            << int(forward) << ' '
305            << int(findnext);
306         return ss.str();
307 }
308
309
310 bool lyxfind(BufferView * bv, FuncRequest const & ev)
311 {
312         if (!bv || ev.action() != LFUN_WORD_FIND)
313                 return false;
314
315         //lyxerr << "find called, cmd: " << ev << endl;
316
317         // data is of the form
318         // "<search>
319         //  <casesensitive> <matchword> <forward>"
320         docstring search;
321         docstring howto = split(ev.argument(), search, '\n');
322
323         bool casesensitive = parse_bool(howto);
324         bool matchword     = parse_bool(howto);
325         bool forward       = parse_bool(howto);
326
327         return findOne(bv, search, casesensitive, matchword, forward);
328 }
329
330
331 bool lyxreplace(BufferView * bv, 
332                 FuncRequest const & ev, bool has_deleted)
333 {
334         if (!bv || ev.action() != LFUN_WORD_REPLACE)
335                 return false;
336
337         // data is of the form
338         // "<search>
339         //  <replace>
340         //  <casesensitive> <matchword> <all> <forward> <findnext>"
341         docstring search;
342         docstring rplc;
343         docstring howto = split(ev.argument(), rplc, '\n');
344         howto = split(howto, search, '\n');
345
346         bool casesensitive = parse_bool(howto);
347         bool matchword     = parse_bool(howto);
348         bool all           = parse_bool(howto);
349         bool forward       = parse_bool(howto);
350         bool findnext      = howto.empty() ? true : 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, findnext);
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 if (findnext) {
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         bv->buffer().updatePreviews();
390         return update;
391 }
392
393
394 bool findNextChange(DocIterator & cur)
395 {
396         for (; cur; cur.forwardPos())
397                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
398                         return true;
399         return false;
400 }
401
402
403 bool findPreviousChange(DocIterator & cur)
404 {
405         for (cur.backwardPos(); cur; cur.backwardPos()) {
406                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
407                         return true;
408         }
409         return false;
410 }
411
412
413 bool selectChange(Cursor & cur, bool forward)
414 {
415         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
416                 return false;
417         Change ch = cur.paragraph().lookupChange(cur.pos());
418
419         CursorSlice tip1 = cur.top();
420         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
421                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
422                 if (!ch2.isSimilarTo(ch))
423                         break;
424         }
425         CursorSlice tip2 = cur.top();
426         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
427                 tip2.backwardPos();
428                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
429                 if (!ch2.isSimilarTo(ch)) {
430                         // take a step forward to correctly set the selection
431                         tip2.forwardPos();
432                         break;
433                 }
434         }
435         if (forward)
436                 swap(tip1, tip2);
437         cur.top() = tip1;
438         cur.bv().mouseSetCursor(cur, false);
439         cur.top() = tip2;
440         cur.bv().mouseSetCursor(cur, true);
441         return true;
442 }
443
444
445 namespace {
446
447
448 bool findChange(BufferView * bv, bool forward)
449 {
450         Cursor cur(*bv);
451         cur.setCursor(forward ? bv->cursor().selectionEnd()
452                       : bv->cursor().selectionBegin());
453         forward ? findNextChange(cur) : findPreviousChange(cur);
454         return selectChange(cur, forward);
455 }
456
457 }
458
459 bool findNextChange(BufferView * bv)
460 {
461         return findChange(bv, true);
462 }
463
464
465 bool findPreviousChange(BufferView * bv)
466 {
467         return findChange(bv, false);
468 }
469
470
471
472 namespace {
473
474 typedef vector<pair<string, string> > Escapes;
475
476 /// A map of symbols and their escaped equivalent needed within a regex.
477 /// @note Beware of order
478 Escapes const & get_regexp_escapes()
479 {
480         typedef std::pair<std::string, std::string> P;
481
482         static Escapes escape_map;
483         if (escape_map.empty()) {
484                 escape_map.push_back(P("$", "_x_$"));
485                 escape_map.push_back(P("{", "_x_{"));
486                 escape_map.push_back(P("}", "_x_}"));
487                 escape_map.push_back(P("[", "_x_["));
488                 escape_map.push_back(P("]", "_x_]"));
489                 escape_map.push_back(P("(", "_x_("));
490                 escape_map.push_back(P(")", "_x_)"));
491                 escape_map.push_back(P("+", "_x_+"));
492                 escape_map.push_back(P("*", "_x_*"));
493                 escape_map.push_back(P(".", "_x_."));
494                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
495                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
496                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
497                 escape_map.push_back(P("_x_", "\\"));
498         }
499         return escape_map;
500 }
501
502 /// A map of lyx escaped strings and their unescaped equivalent.
503 Escapes const & get_lyx_unescapes()
504 {
505         typedef std::pair<std::string, std::string> P;
506
507         static Escapes escape_map;
508         if (escape_map.empty()) {
509                 escape_map.push_back(P("\\%", "%"));
510                 escape_map.push_back(P("\\mathcircumflex ", "^"));
511                 escape_map.push_back(P("\\mathcircumflex", "^"));
512                 escape_map.push_back(P("\\backslash ", "\\"));
513                 escape_map.push_back(P("\\backslash", "\\"));
514                 escape_map.push_back(P("\\\\{", "_x_<"));
515                 escape_map.push_back(P("\\\\}", "_x_>"));
516                 escape_map.push_back(P("\\sim ", "~"));
517                 escape_map.push_back(P("\\sim", "~"));
518         }
519         return escape_map;
520 }
521
522 /// A map of escapes turning a regexp matching text to one matching latex.
523 Escapes const & get_regexp_latex_escapes()
524 {
525         typedef std::pair<std::string, std::string> P;
526
527         static Escapes escape_map;
528         if (escape_map.empty()) {
529                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
530                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
531                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
532                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
533                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
534                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
535                 escape_map.push_back(P("%", "\\\\\\%"));
536         }
537         return escape_map;
538 }
539
540 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
541  ** the found occurrence were escaped.
542  **/
543 string apply_escapes(string s, Escapes const & escape_map)
544 {
545         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
546         Escapes::const_iterator it;
547         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
548 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
549                 unsigned int pos = 0;
550                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
551                         s.replace(pos, it->first.length(), it->second);
552                         LYXERR(Debug::FIND, "After escape: " << s);
553                         pos += it->second.length();
554 //                      LYXERR(Debug::FIND, "pos: " << pos);
555                 }
556         }
557         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
558         return s;
559 }
560
561
562 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
563 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
564 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
565 string escape_for_regex(string s, bool match_latex)
566 {
567         size_t pos = 0;
568         while (pos < s.size()) {
569                 size_t new_pos = s.find("\\regexp{", pos);
570                 if (new_pos == string::npos)
571                         new_pos = s.size();
572                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
573                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
574                 LYXERR(Debug::FIND, "t [lyx]: " << t);
575                 t = apply_escapes(t, get_regexp_escapes());
576                 LYXERR(Debug::FIND, "t [rxp]: " << t);
577                 s.replace(pos, new_pos - pos, t);
578                 new_pos = pos + t.size();
579                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
580                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
581                 if (new_pos == s.size())
582                         break;
583                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
584                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
585                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
586                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
587                 LYXERR(Debug::FIND, "t in regexp      : " << t);
588                 t = apply_escapes(t, get_lyx_unescapes());
589                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
590                 if (match_latex) {
591                         t = apply_escapes(t, get_regexp_latex_escapes());
592                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
593                 }
594                 if (end_pos == s.size()) {
595                         s.replace(new_pos, end_pos - new_pos, t);
596                         pos = s.size();
597                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
598                         break;
599                 }
600                 s.replace(new_pos, end_pos + 13 - new_pos, t);
601                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
602                 pos = new_pos + t.size();
603                 LYXERR(Debug::FIND, "pos: " << pos);
604         }
605         return s;
606 }
607
608
609 /// Wrapper for lyx::regex_replace with simpler interface
610 bool regex_replace(string const & s, string & t, string const & searchstr,
611                    string const & replacestr)
612 {
613         lyx::regex e(searchstr);
614         ostringstream oss;
615         ostream_iterator<char, char> it(oss);
616         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
617         // tolerate t and s be references to the same variable
618         bool rv = (s != oss.str());
619         t = oss.str();
620         return rv;
621 }
622
623
624 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
625  **
626  ** Verify that closed braces exactly match open braces. This avoids that, for example,
627  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
628  **
629  ** @param unmatched
630  ** Number of open braces that must remain open at the end for the verification to succeed.
631  **/
632 bool braces_match(string::const_iterator const & beg,
633                   string::const_iterator const & end,
634                   int unmatched = 0)
635 {
636         int open_pars = 0;
637         string::const_iterator it = beg;
638         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
639         for (; it != end; ++it) {
640                 // Skip escaped braces in the count
641                 if (*it == '\\') {
642                         ++it;
643                         if (it == end)
644                                 break;
645                 } else if (*it == '{') {
646                         ++open_pars;
647                 } else if (*it == '}') {
648                         if (open_pars == 0) {
649                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
650                                 return false;
651                         } else
652                                 --open_pars;
653                 }
654         }
655         if (open_pars != unmatched) {
656                 LYXERR(Debug::FIND, "Found " << open_pars 
657                        << " instead of " << unmatched 
658                        << " unmatched open braces at the end of count");
659                 return false;
660         }
661         LYXERR(Debug::FIND, "Braces match as expected");
662         return true;
663 }
664
665
666 /** The class performing a match between a position in the document and the FindAdvOptions.
667  **/
668 class MatchStringAdv {
669 public:
670         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
671
672         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
673          ** constructor as opt.search, under the opt.* options settings.
674          **
675          ** @param at_begin
676          **     If set, then match is searched only against beginning of text starting at cur.
677          **     If unset, then match is searched anywhere in text starting at cur.
678          **
679          ** @return
680          ** The length of the matching text, or zero if no match was found.
681          **/
682         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
683
684 public:
685         /// buffer
686         lyx::Buffer * p_buf;
687         /// first buffer on which search was started
688         lyx::Buffer * const p_first_buf;
689         /// options
690         FindAndReplaceOptions const & opt;
691
692 private:
693         /// Auxiliary find method (does not account for opt.matchword)
694         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
695
696         /** Normalize a stringified or latexified LyX paragraph.
697          **
698          ** Normalize means:
699          ** <ul>
700          **   <li>if search is not casesensitive, then lowercase the string;
701          **   <li>remove any newline at begin or end of the string;
702          **   <li>replace any newline in the middle of the string with a simple space;
703          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
704          ** </ul>
705          **
706          ** @todo Normalization should also expand macros, if the corresponding
707          ** search option was checked.
708          **/
709         string normalize(docstring const & s, bool hack_braces) const;
710         // normalized string to search
711         string par_as_string;
712         // regular expression to use for searching
713         lyx::regex regexp;
714         // same as regexp, but prefixed with a ".*"
715         lyx::regex regexp2;
716         // leading format material as string
717         string lead_as_string;
718         // par_as_string after removal of lead_as_string
719         string par_as_string_nolead;
720         // unmatched open braces in the search string/regexp
721         int open_braces;
722         // number of (.*?) subexpressions added at end of search regexp for closing
723         // environments, math mode, styles, etc...
724         int close_wildcards;
725         // Are we searching with regular expressions ?
726         bool use_regexp;
727 };
728
729
730 static docstring buffer_to_latex(Buffer & buffer) 
731 {
732         OutputParams runparams(&buffer.params().encoding());
733         TexRow texrow;
734         odocstringstream ods;
735         otexstream os(ods, texrow);
736         runparams.nice = true;
737         runparams.flavor = OutputParams::LATEX;
738         runparams.linelen = 80; //lyxrc.plaintext_linelen;
739         // No side effect of file copying and image conversion
740         runparams.dryrun = true;
741         pit_type const endpit = buffer.paragraphs().size();
742         for (pit_type pit = 0; pit != endpit; ++pit) {
743                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
744                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
745         }
746         return ods.str();
747 }
748
749
750 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
751 {
752         docstring str;
753         if (!opt.ignoreformat) {
754                 str = buffer_to_latex(buffer);
755         } else {
756                 OutputParams runparams(&buffer.params().encoding());
757                 runparams.nice = true;
758                 runparams.flavor = OutputParams::LATEX;
759                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
760                 runparams.dryrun = true;
761                 runparams.for_search = true;
762                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
763                         Paragraph const & par = buffer.paragraphs().at(pit);
764                         LYXERR(Debug::FIND, "Adding to search string: '"
765                                << par.asString(pos_type(0), par.size(),
766                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
767                                                &runparams)
768                                << "'");
769                         str += par.asString(pos_type(0), par.size(),
770                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
771                                             &runparams);
772                 }
773         }
774         return str;
775 }
776
777
778 /// Return separation pos between the leading material and the rest
779 static size_t identifyLeading(string const & s)
780 {
781         string t = s;
782         // @TODO Support \item[text]
783         while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
784                || regex_replace(t, t, "^\\$", "")
785                || regex_replace(t, t, "^\\\\\\[ ", "")
786                || regex_replace(t, t, "^\\\\item ", "")
787                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
788                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
789         return s.find(t);
790 }
791
792
793 // Remove trailing closure of math, macros and environments, so to catch parts of them.
794 static int identifyClosing(string & t)
795 {
796         int open_braces = 0;
797         do {
798                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
799                 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
800                         continue;
801                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
802                         continue;
803                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
804                         continue;
805                 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
806                         ++open_braces;
807                         continue;
808                 }
809                 break;
810         } while (true);
811         return open_braces;
812 }
813
814
815 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
816         : p_buf(&buf), p_first_buf(&buf), opt(opt)
817 {
818         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
819         docstring const & ds = stringifySearchBuffer(find_buf, opt);
820         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
821         // When using regexp, braces are hacked already by escape_for_regex()
822         par_as_string = normalize(ds, !use_regexp);
823         open_braces = 0;
824         close_wildcards = 0;
825
826         size_t lead_size = 0;
827         if (opt.ignoreformat) {
828                 if (!use_regexp) {
829                         // if par_as_string_nolead were emty, 
830                         // the following call to findAux will always *find* the string
831                         // in the checked data, and thus always using the slow
832                         // examining of the current text part.
833                         par_as_string_nolead = par_as_string;
834                 }
835         }
836         else {
837                 lead_size = identifyLeading(par_as_string);
838                 lead_as_string = par_as_string.substr(0, lead_size);
839                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
840         }
841
842         if (!use_regexp) {
843                 open_braces = identifyClosing(par_as_string);
844                 identifyClosing(par_as_string_nolead);
845                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
846                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
847         } else {
848                 string lead_as_regexp;
849                 if (lead_size > 0) {
850                         // @todo No need to search for \regexp{} insets in leading material
851                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
852                         par_as_string = par_as_string_nolead;
853                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
854                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
855                 }
856                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
857                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
858                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
859                 if (
860                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
861                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
862                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
863                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
864                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
865                         || regex_replace(par_as_string, par_as_string,
866                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
867                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
868                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
869                         ) {
870                         ++close_wildcards;
871                 }
872                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
873                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
874                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
875                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
876                 // If entered regexp must match at begin of searched string buffer
877                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
878                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
879                 regexp = lyx::regex(regexp_str);
880
881                 // If entered regexp may match wherever in searched string buffer
882                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
883                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
884                 regexp2 = lyx::regex(regexp2_str);
885         }
886 }
887
888
889 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
890 {
891         if (at_begin &&
892                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
893                 return 0;
894         docstring docstr = stringifyFromForSearch(opt, cur, len);
895         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
896         string str = normalize(docstr, true);
897         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
898         if (! use_regexp) {
899                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
900                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
901                 if (at_begin) {
902                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
903                         if (str.substr(0, par_as_string.size()) == par_as_string)
904                                 return par_as_string.size();
905                 } else {
906                         size_t pos = str.find(par_as_string_nolead);
907                         if (pos != string::npos)
908                                 return par_as_string.size();
909                 }
910         } else {
911                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
912                 // Try all possible regexp matches, 
913                 //until one that verifies the braces match test is found
914                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
915                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
916                 sregex_iterator re_it_end;
917                 for (; re_it != re_it_end; ++re_it) {
918                         match_results<string::const_iterator> const & m = *re_it;
919                         // Check braces on the segment that matched the entire regexp expression,
920                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
921                         if (!braces_match(m[0].first, m[0].second, open_braces))
922                                 return 0;
923                         // Check braces on segments that matched all (.*?) subexpressions,
924                         // except the last "padding" one inserted by lyx.
925                         for (size_t i = 1; i < m.size() - 1; ++i)
926                                 if (!braces_match(m[i].first, m[i].second))
927                                         return false;
928                         // Exclude from the returned match length any length 
929                         // due to close wildcards added at end of regexp
930                         if (close_wildcards == 0)
931                                 return m[0].second - m[0].first;
932                         else
933                                 return m[m.size() - close_wildcards].first - m[0].first;
934                 }
935         }
936         return 0;
937 }
938
939
940 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
941 {
942         int res = findAux(cur, len, at_begin);
943         LYXERR(Debug::FIND,
944                "res=" << res << ", at_begin=" << at_begin
945                << ", matchword=" << opt.matchword
946                << ", inTexted=" << cur.inTexted());
947         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
948                 return res;
949         Paragraph const & par = cur.paragraph();
950         bool ws_left = (cur.pos() > 0)
951                 ? par.isWordSeparator(cur.pos() - 1)
952                 : true;
953         bool ws_right = (cur.pos() + res < par.size())
954                 ? par.isWordSeparator(cur.pos() + res)
955                 : true;
956         LYXERR(Debug::FIND,
957                "cur.pos()=" << cur.pos() << ", res=" << res
958                << ", separ: " << ws_left << ", " << ws_right
959                << endl);
960         if (ws_left && ws_right)
961                 return res;
962         return 0;
963 }
964
965
966 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
967 {
968         string t;
969         if (! opt.casesensitive)
970                 t = lyx::to_utf8(lowercase(s));
971         else
972                 t = lyx::to_utf8(s);
973         // Remove \n at begin
974         while (!t.empty() && t[0] == '\n')
975                 t = t.substr(1);
976         // Remove \n at end
977         while (!t.empty() && t[t.size() - 1] == '\n')
978                 t = t.substr(0, t.size() - 1);
979         size_t pos;
980         // Replace all other \n with spaces
981         while ((pos = t.find("\n")) != string::npos)
982                 t.replace(pos, 1, " ");
983         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
984         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
985         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
986                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
987
988         // FIXME - check what preceeds the brace
989         if (hack_braces) {
990                 if (opt.ignoreformat)
991                         while (regex_replace(t, t, "\\{", "_x_<")
992                                || regex_replace(t, t, "\\}", "_x_>"))
993                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
994                 else
995                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
996                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
997                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
998         }
999
1000         return t;
1001 }
1002
1003
1004 docstring stringifyFromCursor(DocIterator const & cur, int len)
1005 {
1006         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1007         if (cur.inTexted()) {
1008                 Paragraph const & par = cur.paragraph();
1009                 // TODO what about searching beyond/across paragraph breaks ?
1010                 // TODO Try adding a AS_STR_INSERTS as last arg
1011                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1012                         int(par.size()) : cur.pos() + len;
1013                 OutputParams runparams(&cur.buffer()->params().encoding());
1014                 odocstringstream os;
1015                 runparams.nice = true;
1016                 runparams.flavor = OutputParams::LATEX;
1017                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1018                 // No side effect of file copying and image conversion
1019                 runparams.dryrun = true;
1020                 LYXERR(Debug::FIND, "Stringifying with cur: "
1021                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1022                 return par.asString(cur.pos(), end,
1023                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1024                         &runparams);
1025         } else if (cur.inMathed()) {
1026                 docstring s;
1027                 CursorSlice cs = cur.top();
1028                 MathData md = cs.cell();
1029                 MathData::const_iterator it_end =
1030                         (( len == -1 || cs.pos() + len > int(md.size()))
1031                          ? md.end()
1032                          : md.begin() + cs.pos() + len );
1033                 for (MathData::const_iterator it = md.begin() + cs.pos();
1034                      it != it_end; ++it)
1035                         s = s + asString(*it);
1036                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1037                 return s;
1038         }
1039         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1040         return docstring();
1041 }
1042
1043
1044 /** Computes the LaTeX export of buf starting from cur and ending len positions
1045  * after cur, if len is positive, or at the paragraph or innermost inset end
1046  * if len is -1.
1047  */
1048 docstring latexifyFromCursor(DocIterator const & cur, int len)
1049 {
1050         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1051         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1052                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1053         Buffer const & buf = *cur.buffer();
1054         LBUFERR(buf.params().isLatex());
1055
1056         TexRow texrow;
1057         odocstringstream ods;
1058         otexstream os(ods, texrow);
1059         OutputParams runparams(&buf.params().encoding());
1060         runparams.nice = false;
1061         runparams.flavor = OutputParams::LATEX;
1062         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1063         // No side effect of file copying and image conversion
1064         runparams.dryrun = true;
1065
1066         if (cur.inTexted()) {
1067                 // @TODO what about searching beyond/across paragraph breaks ?
1068                 pos_type endpos = cur.paragraph().size();
1069                 if (len != -1 && endpos > cur.pos() + len)
1070                         endpos = cur.pos() + len;
1071                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1072                           string(), cur.pos(), endpos);
1073                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1074         } else if (cur.inMathed()) {
1075                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1076                 for (int s = cur.depth() - 1; s >= 0; --s) {
1077                         CursorSlice const & cs = cur[s];
1078                         if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1079                                 WriteStream ws(ods);
1080                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1081                                 break;
1082                         }
1083                 }
1084
1085                 CursorSlice const & cs = cur.top();
1086                 MathData md = cs.cell();
1087                 MathData::const_iterator it_end =
1088                         ((len == -1 || cs.pos() + len > int(md.size()))
1089                          ? md.end()
1090                          : md.begin() + cs.pos() + len);
1091                 for (MathData::const_iterator it = md.begin() + cs.pos();
1092                      it != it_end; ++it)
1093                         ods << asString(*it);
1094
1095                 // Retrieve the math environment type, and add '$' or '$]'
1096                 // or others (\end{equation}) accordingly
1097                 for (int s = cur.depth() - 1; s >= 0; --s) {
1098                         CursorSlice const & cs = cur[s];
1099                         InsetMath * inset = cs.asInsetMath();
1100                         if (inset && inset->asHullInset()) {
1101                                 WriteStream ws(ods);
1102                                 inset->asHullInset()->footer_write(ws);
1103                                 break;
1104                         }
1105                 }
1106                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1107         } else {
1108                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1109         }
1110         return ods.str();
1111 }
1112
1113
1114 /** Finalize an advanced find operation, advancing the cursor to the innermost
1115  ** position that matches, plus computing the length of the matching text to
1116  ** be selected
1117  **/
1118 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1119 {
1120         // Search the foremost position that matches (avoids find of entire math
1121         // inset when match at start of it)
1122         size_t d;
1123         DocIterator old_cur(cur.buffer());
1124         do {
1125                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1126                 d = cur.depth();
1127                 old_cur = cur;
1128                 cur.forwardPos();
1129         } while (cur && cur.depth() > d && match(cur) > 0);
1130         cur = old_cur;
1131         LASSERT(match(cur) > 0, return 0);
1132         LYXERR(Debug::FIND, "Ok");
1133
1134         // Compute the match length
1135         int len = 1;
1136         if (cur.pos() + len > cur.lastpos())
1137                 return 0;
1138         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1139         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1140                 ++len;
1141                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1142         }
1143         // Length of matched text (different from len param)
1144         int old_len = match(cur, len);
1145         int new_len;
1146         // Greedy behaviour while matching regexps
1147         while ((new_len = match(cur, len + 1)) > old_len) {
1148                 ++len;
1149                 old_len = new_len;
1150                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1151         }
1152         return len;
1153 }
1154
1155
1156 /// Finds forward
1157 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1158 {
1159         if (!cur)
1160                 return 0;
1161         while (!theApp()->longOperationCancelled() && cur) {
1162                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1163                 int match_len = match(cur, -1, false);
1164                 LYXERR(Debug::FIND, "match_len: " << match_len);
1165                 if (match_len) {
1166                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1167                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1168                                 int match_len = match(cur);
1169                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1170                                 if (match_len) {
1171                                         // Sometimes in finalize we understand it wasn't a match
1172                                         // and we need to continue the outest loop
1173                                         int len = findAdvFinalize(cur, match);
1174                                         if (len > 0)
1175                                                 return len;
1176                                 }
1177                         }
1178                         if (!cur)
1179                                 return 0;
1180                 }
1181                 if (cur.pit() < cur.lastpit()) {
1182                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1183                         cur.forwardPar();
1184                 } else {
1185                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1186                         cur.pos() = cur.lastpos();
1187                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1188                         cur.forwardPos();
1189                 }
1190         }
1191         return 0;
1192 }
1193
1194
1195 /// Find the most backward consecutive match within same paragraph while searching backwards.
1196 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1197 {
1198         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1199         DocIterator tmp_cur = cur;
1200         int len = findAdvFinalize(tmp_cur, match);
1201         Inset & inset = cur.inset();
1202         for (; cur != cur_begin; cur.backwardPos()) {
1203                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1204                 DocIterator new_cur = cur;
1205                 new_cur.backwardPos();
1206                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1207                         break;
1208                 int new_len = findAdvFinalize(new_cur, match);
1209                 if (new_len == len)
1210                         break;
1211                 len = new_len;
1212         }
1213         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1214         return len;
1215 }
1216
1217
1218 /// Finds backwards
1219 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1220 {
1221         if (! cur)
1222                 return 0;
1223         // Backup of original position
1224         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1225         if (cur == cur_begin)
1226                 return 0;
1227         cur.backwardPos();
1228         DocIterator cur_orig(cur);
1229         bool found_match;
1230         bool pit_changed = false;
1231         found_match = false;
1232         do {
1233                 cur.pos() = 0;
1234                 found_match = match(cur, -1, false);
1235
1236                 if (found_match) {
1237                         if (pit_changed)
1238                                 cur.pos() = cur.lastpos();
1239                         else
1240                                 cur.pos() = cur_orig.pos();
1241                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1242                         DocIterator cur_prev_iter;
1243                         do {
1244                                 found_match = match(cur);
1245                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1246                                        << found_match << ", cur: " << cur);
1247                                 if (found_match)
1248                                         return findMostBackwards(cur, match);
1249
1250                                 // Stop if begin of document reached
1251                                 if (cur == cur_begin)
1252                                         break;
1253                                 cur_prev_iter = cur;
1254                                 cur.backwardPos();
1255                         } while (true);
1256                 }
1257                 if (cur == cur_begin)
1258                         break;
1259                 if (cur.pit() > 0)
1260                         --cur.pit();
1261                 else
1262                         cur.backwardPos();
1263                 pit_changed = true;
1264         } while (!theApp()->longOperationCancelled());
1265         return 0;
1266 }
1267
1268
1269 } // anonym namespace
1270
1271
1272 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1273                                  DocIterator const & cur, int len)
1274 {
1275         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1276                 return docstring());
1277         if (!opt.ignoreformat)
1278                 return latexifyFromCursor(cur, len);
1279         else
1280                 return stringifyFromCursor(cur, len);
1281 }
1282
1283
1284 FindAndReplaceOptions::FindAndReplaceOptions(
1285         docstring const & find_buf_name, bool casesensitive,
1286         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1287         docstring const & repl_buf_name, bool keep_case,
1288         SearchScope scope, SearchRestriction restr)
1289         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1290           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1291           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1292 {
1293 }
1294
1295
1296 namespace {
1297
1298
1299 /** Check if 'len' letters following cursor are all non-lowercase */
1300 static bool allNonLowercase(Cursor const & cur, int len)
1301 {
1302         pos_type beg_pos = cur.selectionBegin().pos();
1303         pos_type end_pos = cur.selectionBegin().pos() + len;
1304         if (len > cur.lastpos() + 1 - beg_pos) {
1305                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1306                 len = cur.lastpos() + 1 - beg_pos;
1307         }
1308         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1309                 if (isLowerCase(cur.paragraph().getChar(pos)))
1310                         return false;
1311         return true;
1312 }
1313
1314
1315 /** Check if first letter is upper case and second one is lower case */
1316 static bool firstUppercase(Cursor const & cur)
1317 {
1318         char_type ch1, ch2;
1319         pos_type pos = cur.selectionBegin().pos();
1320         if (pos >= cur.lastpos() - 1) {
1321                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1322                 return false;
1323         }
1324         ch1 = cur.paragraph().getChar(pos);
1325         ch2 = cur.paragraph().getChar(pos + 1);
1326         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1327         LYXERR(Debug::FIND, "firstUppercase(): "
1328                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1329                << ch2 << "(" << char(ch2) << ")"
1330                << ", result=" << result << ", cur=" << cur);
1331         return result;
1332 }
1333
1334
1335 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1336  **
1337  ** \fixme What to do with possible further paragraphs in replace buffer ?
1338  **/
1339 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1340 {
1341         ParagraphList::iterator pit = buffer.paragraphs().begin();
1342         LASSERT(pit->size() >= 1, /**/);
1343         pos_type right = pos_type(1);
1344         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1345         right = pit->size();
1346         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1347 }
1348
1349 } // anon namespace
1350
1351 ///
1352 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1353 {
1354         Cursor & cur = bv->cursor();
1355         if (opt.repl_buf_name == docstring())
1356                 return;
1357
1358         DocIterator sel_beg = cur.selectionBegin();
1359         DocIterator sel_end = cur.selectionEnd();
1360         if (&sel_beg.inset() != &sel_end.inset()
1361             || sel_beg.pit() != sel_end.pit()
1362             || sel_beg.idx() != sel_end.idx())
1363                 return;
1364         int sel_len = sel_end.pos() - sel_beg.pos();
1365         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1366                << ", sel_len: " << sel_len << endl);
1367         if (sel_len == 0)
1368                 return;
1369         LASSERT(sel_len > 0, return);
1370
1371         if (!matchAdv(sel_beg, sel_len))
1372                 return;
1373
1374         // Build a copy of the replace buffer, adapted to the KeepCase option
1375         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1376         ostringstream oss;
1377         repl_buffer_orig.write(oss);
1378         string lyx = oss.str();
1379         Buffer repl_buffer("", false);
1380         repl_buffer.setUnnamed(true);
1381         LASSERT(repl_buffer.readString(lyx), return);
1382         if (opt.keep_case && sel_len >= 2) {
1383                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1384                 if (cur.inTexted()) {
1385                         if (firstUppercase(cur))
1386                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1387                         else if (allNonLowercase(cur, sel_len))
1388                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1389                 }
1390         }
1391         cap::cutSelection(cur, false, false);
1392         if (cur.inTexted()) {
1393                 repl_buffer.changeLanguage(
1394                         repl_buffer.language(),
1395                         cur.getFont().language());
1396                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1397                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1398                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1399                                         repl_buffer.params().documentClassPtr(),
1400                                         bv->buffer().errorList("Paste"));
1401                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1402                 sel_len = repl_buffer.paragraphs().begin()->size();
1403         } else if (cur.inMathed()) {
1404                 TexRow texrow;
1405                 odocstringstream ods;
1406                 otexstream os(ods, texrow);
1407                 OutputParams runparams(&repl_buffer.params().encoding());
1408                 runparams.nice = false;
1409                 runparams.flavor = OutputParams::LATEX;
1410                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1411                 runparams.dryrun = true;
1412                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1413                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1414                 docstring repl_latex = ods.str();
1415                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1416                 string s;
1417                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1418                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1419                 repl_latex = from_utf8(s);
1420                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1421                 MathData ar(cur.buffer());
1422                 asArray(repl_latex, ar, Parse::NORMAL);
1423                 cur.insert(ar);
1424                 sel_len = ar.size();
1425                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1426         }
1427         if (cur.pos() >= sel_len)
1428                 cur.pos() -= sel_len;
1429         else
1430                 cur.pos() = 0;
1431         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1432         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1433         bv->processUpdateFlags(Update::Force);
1434         bv->buffer().updatePreviews();
1435 }
1436
1437
1438 /// Perform a FindAdv operation.
1439 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1440 {
1441         DocIterator cur;
1442         int match_len = 0;
1443
1444         try {
1445                 MatchStringAdv matchAdv(bv->buffer(), opt);
1446                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1447                 if (length > 0)
1448                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1449                 findAdvReplace(bv, opt, matchAdv);
1450                 cur = bv->cursor();
1451                 if (opt.forward)
1452                         match_len = findForwardAdv(cur, matchAdv);
1453                 else
1454                         match_len = findBackwardsAdv(cur, matchAdv);
1455         } catch (...) {
1456                 // This may only be raised by lyx::regex()
1457                 bv->message(_("Invalid regular expression!"));
1458                 return false;
1459         }
1460
1461         if (match_len == 0) {
1462                 bv->message(_("Match not found!"));
1463                 return false;
1464         }
1465
1466         bv->message(_("Match found!"));
1467
1468         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1469         bv->putSelectionAt(cur, match_len, !opt.forward);
1470
1471         return true;
1472 }
1473
1474
1475 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1476 {
1477         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1478            << opt.casesensitive << ' '
1479            << opt.matchword << ' '
1480            << opt.forward << ' '
1481            << opt.expandmacros << ' '
1482            << opt.ignoreformat << ' '
1483            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1484            << opt.keep_case << ' '
1485            << int(opt.scope) << ' '
1486            << int(opt.restr);
1487
1488         LYXERR(Debug::FIND, "built: " << os.str());
1489
1490         return os;
1491 }
1492
1493
1494 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1495 {
1496         LYXERR(Debug::FIND, "parsing");
1497         string s;
1498         string line;
1499         getline(is, line);
1500         while (line != "EOSS") {
1501                 if (! s.empty())
1502                         s = s + "\n";
1503                 s = s + line;
1504                 if (is.eof())   // Tolerate malformed request
1505                         break;
1506                 getline(is, line);
1507         }
1508         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1509         opt.find_buf_name = from_utf8(s);
1510         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1511         is.get();       // Waste space before replace string
1512         s = "";
1513         getline(is, line);
1514         while (line != "EOSS") {
1515                 if (! s.empty())
1516                         s = s + "\n";
1517                 s = s + line;
1518                 if (is.eof())   // Tolerate malformed request
1519                         break;
1520                 getline(is, line);
1521         }
1522         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1523         opt.repl_buf_name = from_utf8(s);
1524         is >> opt.keep_case;
1525         int i;
1526         is >> i;
1527         opt.scope = FindAndReplaceOptions::SearchScope(i);
1528         is >> i;
1529         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1530
1531         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1532                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1533                << opt.scope << ' ' << opt.restr);
1534         return is;
1535 }
1536
1537 } // lyx namespace