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