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