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