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