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