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