]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
listerrors.lyx : Update a link.
[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
569 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
570 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
571 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
572 string escape_for_regex(string s, bool match_latex)
573 {
574         size_t pos = 0;
575         while (pos < s.size()) {
576                 size_t new_pos = s.find("\\regexp{", pos);
577                 if (new_pos == string::npos)
578                         new_pos = s.size();
579                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
580                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
581                 LYXERR(Debug::FIND, "t [lyx]: " << t);
582                 t = apply_escapes(t, get_regexp_escapes());
583                 LYXERR(Debug::FIND, "t [rxp]: " << t);
584                 s.replace(pos, new_pos - pos, t);
585                 new_pos = pos + t.size();
586                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
587                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
588                 if (new_pos == s.size())
589                         break;
590                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
591                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
592                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
593                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
594                 LYXERR(Debug::FIND, "t in regexp      : " << t);
595                 t = apply_escapes(t, get_lyx_unescapes());
596                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
597                 if (match_latex) {
598                         t = apply_escapes(t, get_regexp_latex_escapes());
599                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
600                 }
601                 if (end_pos == s.size()) {
602                         s.replace(new_pos, end_pos - new_pos, t);
603                         pos = s.size();
604                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
605                         break;
606                 }
607                 s.replace(new_pos, end_pos + 13 - new_pos, t);
608                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
609                 pos = new_pos + t.size();
610                 LYXERR(Debug::FIND, "pos: " << pos);
611         }
612         return s;
613 }
614
615 /// Wrapper for lyx::regex_replace with simpler interface
616 bool regex_replace(string const & s, string & t, string const & searchstr,
617         string const & replacestr)
618 {
619         lyx::regex e(searchstr);
620         ostringstream oss;
621         ostream_iterator<char, char> it(oss);
622         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
623         // tolerate t and s be references to the same variable
624         bool rv = (s != oss.str());
625         t = oss.str();
626         return rv;
627 }
628
629 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
630  **
631  ** Verify that closed braces exactly match open braces. This avoids that, for example,
632  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
633  **
634  ** @param unmatched
635  ** Number of open braces that must remain open at the end for the verification to succeed.
636  **/
637 bool braces_match(string::const_iterator const & beg,
638                   string::const_iterator const & end,
639                   int unmatched = 0)
640 {
641         int open_pars = 0;
642         string::const_iterator it = beg;
643         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
644         for (; it != end; ++it) {
645                 // Skip escaped braces in the count
646                 if (*it == '\\') {
647                         ++it;
648                         if (it == end)
649                                 break;
650                 } else if (*it == '{') {
651                         ++open_pars;
652                 } else if (*it == '}') {
653                         if (open_pars == 0) {
654                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
655                                 return false;
656                         } else
657                                 --open_pars;
658                 }
659         }
660         if (open_pars != unmatched) {
661                 LYXERR(Debug::FIND, "Found " << open_pars 
662                        << " instead of " << unmatched 
663                        << " unmatched open braces at the end of count");
664                 return false;
665         }
666         LYXERR(Debug::FIND, "Braces match as expected");
667         return true;
668 }
669
670 /** The class performing a match between a position in the document and the FindAdvOptions.
671  **/
672 class MatchStringAdv {
673 public:
674         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
675
676         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
677          ** constructor as opt.search, under the opt.* options settings.
678          **
679          ** @param at_begin
680          **     If set, then match is searched only against beginning of text starting at cur.
681          **     If unset, then match is searched anywhere in text starting at cur.
682          **
683          ** @return
684          ** The length of the matching text, or zero if no match was found.
685          **/
686         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
687
688 public:
689         /// buffer
690         lyx::Buffer * p_buf;
691         /// first buffer on which search was started
692         lyx::Buffer * const p_first_buf;
693         /// options
694         FindAndReplaceOptions const & opt;
695
696 private:
697         /// Auxiliary find method (does not account for opt.matchword)
698         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
699
700         /** Normalize a stringified or latexified LyX paragraph.
701          **
702          ** Normalize means:
703          ** <ul>
704          **   <li>if search is not casesensitive, then lowercase the string;
705          **   <li>remove any newline at begin or end of the string;
706          **   <li>replace any newline in the middle of the string with a simple space;
707          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
708          ** </ul>
709          **
710          ** @todo Normalization should also expand macros, if the corresponding
711          ** search option was checked.
712          **/
713         string normalize(docstring const & s, bool hack_braces) const;
714         // normalized string to search
715         string par_as_string;
716         // regular expression to use for searching
717         lyx::regex regexp;
718         // same as regexp, but prefixed with a ".*"
719         lyx::regex regexp2;
720         // leading format material as string
721         string lead_as_string;
722         // par_as_string after removal of lead_as_string
723         string par_as_string_nolead;
724         // unmatched open braces in the search string/regexp
725         int open_braces;
726         // number of (.*?) subexpressions added at end of search regexp for closing
727         // environments, math mode, styles, etc...
728         int close_wildcards;
729         // Are we searching with regular expressions ?
730         bool use_regexp;
731 };
732
733
734 static docstring buffer_to_latex(Buffer & buffer) 
735 {
736         OutputParams runparams(&buffer.params().encoding());
737         TexRow texrow;
738         odocstringstream ods;
739         otexstream os(ods, texrow);
740         runparams.nice = true;
741         runparams.flavor = OutputParams::LATEX;
742         runparams.linelen = 80; //lyxrc.plaintext_linelen;
743         // No side effect of file copying and image conversion
744         runparams.dryrun = true;
745         pit_type const endpit = buffer.paragraphs().size();
746         for (pit_type pit = 0; pit != endpit; ++pit) {
747                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
748                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
749         }
750         return ods.str();
751 }
752
753
754 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt) {
755         docstring str;
756         if (!opt.ignoreformat) {
757                 str = buffer_to_latex(buffer);
758         } else {
759                 OutputParams runparams(&buffer.params().encoding());
760                 runparams.nice = true;
761                 runparams.flavor = OutputParams::LATEX;
762                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
763                 runparams.dryrun = true;
764                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
765                         Paragraph const & par = buffer.paragraphs().at(pit);
766                         LYXERR(Debug::FIND, "Adding to search string: '"
767                                 << par.stringify(pos_type(0), par.size(),
768                                                  AS_STR_INSETS, runparams)
769                                 << "'");
770                         str += par.stringify(pos_type(0), par.size(),
771                                              AS_STR_INSETS, runparams);
772                 }
773         }
774         return str;
775 }
776
777
778 /// Return separation pos between the leading material and the rest
779 static size_t identifyLeading(string const & s)  {
780         string t = s;
781         // @TODO Support \item[text]
782         while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
783                || regex_replace(t, t, "^\\$", "")
784                || regex_replace(t, t, "^\\\\\\[ ", "")
785                || regex_replace(t, t, "^\\\\item ", "")
786                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
787                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
788         return s.find(t);
789 }
790
791
792 // Remove trailing closure of math, macros and environments, so to catch parts of them.
793 static int identifyClosing(string & t) {
794         int open_braces = 0;
795         do {
796                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
797                 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
798                         continue;
799                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
800                         continue;
801                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
802                         continue;
803                 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
804                         ++open_braces;
805                         continue;
806                 }
807                 break;
808         } while (true);
809         return open_braces;
810 }
811
812
813 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
814         : p_buf(&buf), p_first_buf(&buf), opt(opt)
815 {
816         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
817         docstring const & ds = stringifySearchBuffer(find_buf, opt);
818         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
819         // When using regexp, braces are hacked already by escape_for_regex()
820         par_as_string = normalize(ds, !use_regexp);
821         open_braces = 0;
822         close_wildcards = 0;
823
824         size_t lead_size = 0;
825         if (!opt.ignoreformat) {
826                 lead_size = identifyLeading(par_as_string);
827                 lead_as_string = par_as_string.substr(0, lead_size);
828                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
829         }
830
831         if (!use_regexp) {
832                 open_braces = identifyClosing(par_as_string);
833                 identifyClosing(par_as_string_nolead);
834                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
835                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
836         } else {
837                 string lead_as_regexp;
838                 if (lead_size > 0) {
839                         // @todo No need to search for \regexp{} insets in leading material
840                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
841                         par_as_string = par_as_string_nolead;
842                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
843                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
844                 }
845                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
846                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
847                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
848                 if (
849                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
850                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
851                                 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
852                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
853                                 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
854                                 || regex_replace(par_as_string, par_as_string, 
855                                         "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
856                                 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
857                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
858                 ) {
859                         ++close_wildcards;
860                 }
861                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
862                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
863                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
864                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
865                 // If entered regexp must match at begin of searched string buffer
866                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
867                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
868                 regexp = lyx::regex(regexp_str);
869
870                 // If entered regexp may match wherever in searched string buffer
871                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
872                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
873                 regexp2 = lyx::regex(regexp2_str);
874         }
875 }
876
877
878 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
879 {
880         docstring docstr = stringifyFromForSearch(opt, cur, len);
881         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
882         string str = normalize(docstr, true);
883         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
884         if (! use_regexp) {
885                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
886                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
887                 if (at_begin) {
888                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
889                         if (str.substr(0, par_as_string.size()) == par_as_string)
890                                 return par_as_string.size();
891                 } else {
892                         size_t pos = str.find(par_as_string_nolead);
893                         if (pos != string::npos)
894                                 return par_as_string.size();
895                 }
896         } else {
897                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
898                 // Try all possible regexp matches, 
899                 //until one that verifies the braces match test is found
900                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
901                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
902                 sregex_iterator re_it_end;
903                 for (; re_it != re_it_end; ++re_it) {
904                         match_results<string::const_iterator> const & m = *re_it;
905                         // Check braces on the segment that matched the entire regexp expression,
906                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
907                         if (!braces_match(m[0].first, m[0].second, open_braces))
908                                 return 0;
909                         // Check braces on segments that matched all (.*?) subexpressions,
910                         // except the last "padding" one inserted by lyx.
911                         for (size_t i = 1; i < m.size() - 1; ++i)
912                                 if (!braces_match(m[i].first, m[i].second))
913                                         return false;
914                         // Exclude from the returned match length any length 
915                         // due to close wildcards added at end of regexp
916                         if (close_wildcards == 0)
917                                 return m[0].second - m[0].first;
918                         else
919                                 return m[m.size() - close_wildcards].first - m[0].first;
920                 }
921         }
922         return 0;
923 }
924
925
926 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
927 {
928         int res = findAux(cur, len, at_begin);
929         LYXERR(Debug::FIND,
930                "res=" << res << ", at_begin=" << at_begin << ", matchword=" << opt.matchword << ", inTexted=" << cur.inTexted());
931         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
932                 return res;
933         Paragraph const & par = cur.paragraph();
934         bool ws_left = cur.pos() > 0 ?
935                 par.isWordSeparator(cur.pos() - 1) : true;
936         bool ws_right = cur.pos() + res < par.size() ?
937                 par.isWordSeparator(cur.pos() + res) : true;
938         LYXERR(Debug::FIND,
939                "cur.pos()=" << cur.pos() << ", res=" << res
940                << ", separ: " << ws_left << ", " << ws_right
941                << endl);
942         if (ws_left && ws_right)
943                 return res;
944         return 0;
945 }
946
947
948 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
949 {
950         string t;
951         if (! opt.casesensitive)
952                 t = lyx::to_utf8(lowercase(s));
953         else
954                 t = lyx::to_utf8(s);
955         // Remove \n at begin
956         while (t.size() > 0 && t[0] == '\n')
957                 t = t.substr(1);
958         // Remove \n at end
959         while (t.size() > 0 && t[t.size() - 1] == '\n')
960                 t = t.substr(0, t.size() - 1);
961         size_t pos;
962         // Replace all other \n with spaces
963         while ((pos = t.find("\n")) != string::npos)
964                 t.replace(pos, 1, " ");
965         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
966         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
967         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
968                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
969
970         // FIXME - check what preceeds the brace
971         if (hack_braces) {
972                 if (opt.ignoreformat)
973                         while (regex_replace(t, t, "\\{", "_x_<")
974                                || regex_replace(t, t, "\\}", "_x_>"))
975                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
976                 else
977                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
978                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
979                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
980         }
981
982         return t;
983 }
984
985
986 docstring stringifyFromCursor(DocIterator const & cur, int len)
987 {
988         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
989         if (cur.inTexted()) {
990                         Paragraph const & par = cur.paragraph();
991                         // TODO what about searching beyond/across paragraph breaks ?
992                         // TODO Try adding a AS_STR_INSERTS as last arg
993                         pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
994                                 int(par.size()) : cur.pos() + len;
995                         OutputParams runparams(&cur.buffer()->params().encoding());
996                         odocstringstream os;
997                         runparams.nice = true;
998                         runparams.flavor = OutputParams::LATEX;
999                         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1000                         // No side effect of file copying and image conversion
1001                         runparams.dryrun = true;
1002                         LYXERR(Debug::FIND, "Stringifying with cur: " 
1003                                 << cur << ", from pos: " << cur.pos() << ", end: " << end);
1004                         return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
1005         } else if (cur.inMathed()) {
1006                         docstring s;
1007                         CursorSlice cs = cur.top();
1008                         MathData md = cs.cell();
1009                         MathData::const_iterator it_end = 
1010                                 ( ( len == -1 || cs.pos() + len > int(md.size()) )
1011                                         ? md.end() : md.begin() + cs.pos() + len );
1012                         for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
1013                                 s = s + asString(*it);
1014                         LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1015                         return s;
1016         }
1017         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1018         return docstring();
1019 }
1020
1021
1022 /** Computes the LaTeX export of buf starting from cur and ending len positions
1023  * after cur, if len is positive, or at the paragraph or innermost inset end
1024  * if len is -1.
1025  */
1026 docstring latexifyFromCursor(DocIterator const & cur, int len)
1027 {
1028         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1029         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1030                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1031         Buffer const & buf = *cur.buffer();
1032         LASSERT(buf.params().isLatex(), /* */);
1033
1034         TexRow texrow;
1035         odocstringstream ods;
1036         otexstream os(ods, texrow);
1037         OutputParams runparams(&buf.params().encoding());
1038         runparams.nice = false;
1039         runparams.flavor = OutputParams::LATEX;
1040         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1041         // No side effect of file copying and image conversion
1042         runparams.dryrun = true;
1043
1044         if (cur.inTexted()) {
1045                 // @TODO what about searching beyond/across paragraph breaks ?
1046                 pos_type endpos = cur.paragraph().size();
1047                 if (len != -1 && endpos > cur.pos() + len)
1048                         endpos = cur.pos() + len;
1049                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1050                         string(), cur.pos(), endpos);
1051                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1052         } else if (cur.inMathed()) {
1053                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1054                 for (int s = cur.depth() - 1; s >= 0; --s) {
1055                                 CursorSlice const & cs = cur[s];
1056                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1057                                                 WriteStream ws(ods);
1058                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1059                                                 break;
1060                                 }
1061                 }
1062
1063                 CursorSlice const & cs = cur.top();
1064                 MathData md = cs.cell();
1065                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
1066                         ? md.end() : md.begin() + cs.pos() + len );
1067                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
1068                         ods << asString(*it);
1069
1070                 // Retrieve the math environment type, and add '$' or '$]'
1071                 // or others (\end{equation}) accordingly
1072                 for (int s = cur.depth() - 1; s >= 0; --s) {
1073                         CursorSlice const & cs = cur[s];
1074                         InsetMath * inset = cs.asInsetMath();
1075                         if (inset && inset->asHullInset()) {
1076                                 WriteStream ws(ods);
1077                                 inset->asHullInset()->footer_write(ws);
1078                                 break;
1079                         }
1080                 }
1081                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1082         } else {
1083                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1084         }
1085         return ods.str();
1086 }
1087
1088
1089 /** Finalize an advanced find operation, advancing the cursor to the innermost
1090  ** position that matches, plus computing the length of the matching text to
1091  ** be selected
1092  **/
1093 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1094 {
1095         // Search the foremost position that matches (avoids find of entire math
1096         // inset when match at start of it)
1097         size_t d;
1098         DocIterator old_cur(cur.buffer());
1099         do {
1100                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1101                 d = cur.depth();
1102                 old_cur = cur;
1103                 cur.forwardPos();
1104         } while (cur && cur.depth() > d && match(cur) > 0);
1105         cur = old_cur;
1106         LASSERT(match(cur) > 0, /* */);
1107         LYXERR(Debug::FIND, "Ok");
1108
1109         // Compute the match length
1110         int len = 1;
1111         if (cur.pos() + len > cur.lastpos())
1112                 return 0;
1113         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1114         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1115                 ++len;
1116                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1117         }
1118         // Length of matched text (different from len param)
1119         int old_len = match(cur, len);
1120         int new_len;
1121         // Greedy behaviour while matching regexps
1122         while ((new_len = match(cur, len + 1)) > old_len) {
1123                 ++len;
1124                 old_len = new_len;
1125                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1126         }
1127         return len;
1128 }
1129
1130
1131 /// Finds forward
1132 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1133 {
1134         if (!cur)
1135                 return 0;
1136         while (cur) {
1137                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1138                 int match_len = match(cur, -1, false);
1139                 LYXERR(Debug::FIND, "match_len: " << match_len);
1140                 if (match_len) {
1141                         for (; cur; cur.forwardPos()) {
1142                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1143                                 int match_len = match(cur);
1144                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1145                                 if (match_len) {
1146                                         // Sometimes in finalize we understand it wasn't a match
1147                                         // and we need to continue the outest loop
1148                                         int len = findAdvFinalize(cur, match);
1149                                         if (len > 0)
1150                                                 return len;
1151                                 }
1152                         }
1153                         if (!cur)
1154                                 return 0;
1155                 }
1156                 if (cur.pit() < cur.lastpit()) {
1157                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1158                         cur.forwardPar();
1159                 } else {
1160                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1161                         cur.pos() = cur.lastpos();
1162                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1163                         cur.forwardPos();
1164                 }
1165         }
1166         return 0;
1167 }
1168
1169
1170 /// Find the most backward consecutive match within same paragraph while searching backwards.
1171 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1172 {
1173         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1174         DocIterator tmp_cur = cur;
1175         int len = findAdvFinalize(tmp_cur, match);
1176         Inset & inset = cur.inset();
1177         for (; cur != cur_begin; cur.backwardPos()) {
1178                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1179                 DocIterator new_cur = cur;
1180                 new_cur.backwardPos();
1181                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1182                         break;
1183                 int new_len = findAdvFinalize(new_cur, match);
1184                 if (new_len == len)
1185                         break;
1186                 len = new_len;
1187         }
1188         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1189         return len;
1190 }
1191
1192
1193 /// Finds backwards
1194 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1195         if (! cur)
1196                 return 0;
1197         // Backup of original position
1198         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1199         if (cur == cur_begin)
1200                 return 0;
1201         cur.backwardPos();
1202         DocIterator cur_orig(cur);
1203         bool found_match;
1204         bool pit_changed = false;
1205         found_match = false;
1206         do {
1207                 cur.pos() = 0;
1208                 found_match = match(cur, -1, false);
1209
1210                 if (found_match) {
1211                         if (pit_changed)
1212                                 cur.pos() = cur.lastpos();
1213                         else
1214                                 cur.pos() = cur_orig.pos();
1215                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1216                         DocIterator cur_prev_iter;
1217                         do {
1218                                 found_match = match(cur);
1219                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1220                                        << found_match << ", cur: " << cur);
1221                                 if (found_match)
1222                                         return findMostBackwards(cur, match);
1223
1224                                 // Stop if begin of document reached
1225                                 if (cur == cur_begin)
1226                                         break;
1227                                 cur_prev_iter = cur;
1228                                 cur.backwardPos();
1229                         } while (true);
1230                 }
1231                 if (cur == cur_begin)
1232                         break;
1233                 if (cur.pit() > 0)
1234                         --cur.pit();
1235                 else
1236                         cur.backwardPos();
1237                 pit_changed = true;
1238         } while (true);
1239         return 0;
1240 }
1241
1242
1243 } // anonym namespace
1244
1245
1246 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1247         DocIterator const & cur, int len)
1248 {
1249         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1250         if (!opt.ignoreformat)
1251                 return latexifyFromCursor(cur, len);
1252         else
1253                 return stringifyFromCursor(cur, len);
1254 }
1255
1256
1257 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & find_buf_name, bool casesensitive,
1258         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1259         docstring const & repl_buf_name, bool keep_case,
1260         SearchScope scope)
1261         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1262         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1263         repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1264 {
1265 }
1266
1267
1268 namespace {
1269
1270
1271 /** Check if 'len' letters following cursor are all non-lowercase */
1272 static bool allNonLowercase(DocIterator const & cur, int len) {
1273         pos_type end_pos = cur.pos() + len;
1274         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1275                 if (isLowerCase(cur.paragraph().getChar(pos)))
1276                         return false;
1277         return true;
1278 }
1279
1280
1281 /** Check if first letter is upper case and second one is lower case */
1282 static bool firstUppercase(DocIterator const & cur) {
1283         char_type ch1, ch2;
1284         if (cur.pos() >= cur.lastpos() - 1) {
1285                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1286                 return false;
1287         }
1288         ch1 = cur.paragraph().getChar(cur.pos());
1289         ch2 = cur.paragraph().getChar(cur.pos()+1);
1290         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1291         LYXERR(Debug::FIND, "firstUppercase(): "
1292                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1293                << ch2 << "(" << char(ch2) << ")"
1294                << ", result=" << result << ", cur=" << cur);
1295         return result;
1296 }
1297
1298
1299 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1300  **
1301  ** \fixme What to do with possible further paragraphs in replace buffer ?
1302  **/
1303 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1304         ParagraphList::iterator pit = buffer.paragraphs().begin();
1305         pos_type right = pos_type(1);
1306         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1307         right = pit->size() + 1;
1308         pit->changeCase(buffer.params(), right, right, others_case);
1309 }
1310 } // anon namespace
1311
1312 ///
1313 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1314 {
1315         Cursor & cur = bv->cursor();
1316         if (opt.repl_buf_name == docstring())
1317                 return;
1318
1319         DocIterator sel_beg = cur.selectionBegin();
1320         DocIterator sel_end = cur.selectionEnd();
1321         if (&sel_beg.inset() != &sel_end.inset()
1322             || sel_beg.pit() != sel_end.pit())
1323                 return;
1324         int sel_len = sel_end.pos() - sel_beg.pos();
1325         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1326                << ", sel_len: " << sel_len << endl);
1327         if (sel_len == 0)
1328                 return;
1329         LASSERT(sel_len > 0, /**/);
1330
1331         if (!matchAdv(sel_beg, sel_len))
1332                 return;
1333
1334         // Build a copy of the replace buffer, adapted to the KeepCase option
1335         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1336         ostringstream oss;
1337         repl_buffer_orig.write(oss);
1338         string lyx = oss.str();
1339         Buffer repl_buffer("", false);
1340         repl_buffer.setUnnamed(true);
1341         LASSERT(repl_buffer.readString(lyx), /**/);
1342         if (opt.keep_case && sel_len >= 2) {
1343                 if (cur.inTexted()) {
1344                         if (firstUppercase(cur))
1345                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1346                         else if (allNonLowercase(cur, sel_len))
1347                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1348                 }
1349         }
1350         cap::cutSelection(cur, false, false);
1351         if (cur.inTexted()) {
1352                 repl_buffer.changeLanguage(
1353                         repl_buffer.language(),
1354                         cur.getFont().language());
1355                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1356                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1357                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1358                                         repl_buffer.params().documentClassPtr(),
1359                                         bv->buffer().errorList("Paste"));
1360                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1361                 sel_len = repl_buffer.paragraphs().begin()->size();
1362         } else if (cur.inMathed()) {
1363                 TexRow texrow;
1364                 odocstringstream ods;
1365                 otexstream os(ods, texrow);
1366                 OutputParams runparams(&repl_buffer.params().encoding());
1367                 runparams.nice = false;
1368                 runparams.flavor = OutputParams::LATEX;
1369                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1370                 runparams.dryrun = true;
1371                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1372                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1373                 docstring repl_latex = ods.str();
1374                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1375                 string s;
1376                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1377                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1378                 repl_latex = from_utf8(s);
1379                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1380                 MathData ar(cur.buffer());
1381                 asArray(repl_latex, ar, Parse::NORMAL);
1382                 cur.insert(ar);
1383                 sel_len = ar.size();
1384                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1385         }
1386         if (cur.pos() >= sel_len)
1387                 cur.pos() -= sel_len;
1388         else
1389                 cur.pos() = 0;
1390         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1391         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1392         bv->processUpdateFlags(Update::Force);
1393         bv->buffer().updatePreviews();
1394 }
1395
1396
1397 /// Perform a FindAdv operation.
1398 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1399 {
1400         DocIterator cur;
1401         int match_len = 0;
1402
1403         try {
1404                 MatchStringAdv matchAdv(bv->buffer(), opt);
1405                 findAdvReplace(bv, opt, matchAdv);
1406                 cur = bv->cursor();
1407                 if (opt.forward)
1408                                 match_len = findForwardAdv(cur, matchAdv);
1409                 else
1410                                 match_len = findBackwardsAdv(cur, matchAdv);
1411         } catch (...) {
1412                 // This may only be raised by lyx::regex()
1413                 bv->message(_("Invalid regular expression!"));
1414                 return false;
1415         }
1416
1417         if (match_len == 0) {
1418                 bv->message(_("Match not found!"));
1419                 return false;
1420         }
1421
1422         bv->message(_("Match found!"));
1423
1424         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1425         bv->putSelectionAt(cur, match_len, !opt.forward);
1426
1427         return true;
1428 }
1429
1430
1431 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1432 {
1433         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1434            << opt.casesensitive << ' '
1435            << opt.matchword << ' '
1436            << opt.forward << ' '
1437            << opt.expandmacros << ' '
1438            << opt.ignoreformat << ' '
1439            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1440            << opt.keep_case << ' '
1441            << int(opt.scope);
1442
1443         LYXERR(Debug::FIND, "built: " << os.str());
1444
1445         return os;
1446 }
1447
1448
1449 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1450 {
1451         LYXERR(Debug::FIND, "parsing");
1452         string s;
1453         string line;
1454         getline(is, line);
1455         while (line != "EOSS") {
1456                 if (! s.empty())
1457                                 s = s + "\n";
1458                 s = s + line;
1459                 if (is.eof())   // Tolerate malformed request
1460                                 break;
1461                 getline(is, line);
1462         }
1463         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1464         opt.find_buf_name = from_utf8(s);
1465         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1466         is.get();       // Waste space before replace string
1467         s = "";
1468         getline(is, line);
1469         while (line != "EOSS") {
1470                 if (! s.empty())
1471                                 s = s + "\n";
1472                 s = s + line;
1473                 if (is.eof())   // Tolerate malformed request
1474                                 break;
1475                 getline(is, line);
1476         }
1477         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1478         opt.repl_buf_name = from_utf8(s);
1479         is >> opt.keep_case;
1480         int i;
1481         is >> i;
1482         opt.scope = FindAndReplaceOptions::SearchScope(i);
1483         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1484                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);
1485         return is;
1486 }
1487
1488 } // lyx namespace