]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Natbib authoryear uses (Ref1; Ref2) by default.
[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 searchAllowed(docstring const & str)
125 {
126         if (str.empty()) {
127                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
128                 return false;
129         }
130         return true;
131 }
132
133
134 bool findOne(BufferView * bv, docstring const & searchstr,
135              bool case_sens, bool whole, bool forward, bool find_del = true)
136 {
137         if (!searchAllowed(searchstr))
138                 return false;
139
140         DocIterator cur = forward 
141                 ? bv->cursor().selectionEnd() 
142                 : bv->cursor().selectionBegin();
143
144         MatchString const match(searchstr, case_sens, whole);
145
146         int match_len = forward
147                 ? findForward(cur, match, find_del)
148                 : findBackwards(cur, match, find_del);
149
150         if (match_len > 0)
151                 bv->putSelectionAt(cur, match_len, !forward);
152
153         return match_len > 0;
154 }
155
156
157 int replaceAll(BufferView * bv,
158                docstring const & searchstr, docstring const & replacestr,
159                bool case_sens, bool whole)
160 {
161         Buffer & buf = bv->buffer();
162
163         if (!searchAllowed(searchstr) || buf.isReadonly())
164                 return 0;
165
166         DocIterator cur_orig(bv->cursor());
167
168         MatchString const match(searchstr, case_sens, whole);
169         int num = 0;
170
171         int const rsize = replacestr.size();
172         int const ssize = searchstr.size();
173
174         Cursor cur(*bv);
175         cur.setCursor(doc_iterator_begin(&buf));
176         int match_len = findForward(cur, match, false);
177         while (match_len > 0) {
178                 // Backup current cursor position and font.
179                 pos_type const pos = cur.pos();
180                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
181                 cur.recordUndo();
182                 int striked = ssize -
183                         cur.paragraph().eraseChars(pos, pos + match_len,
184                                                    buf.params().trackChanges);
185                 cur.paragraph().insert(pos, replacestr, font,
186                                        Change(buf.params().trackChanges
187                                               ? Change::INSERTED
188                                               : Change::UNCHANGED));
189                 for (int i = 0; i < rsize + striked; ++i)
190                         cur.forwardChar();
191                 ++num;
192                 match_len = findForward(cur, match, false);
193         }
194
195         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
196
197         cur_orig.fixIfBroken();
198         bv->setCursor(cur_orig);
199
200         return num;
201 }
202
203
204 // the idea here is that we are going to replace the string that
205 // is selected IF it is the search string. 
206 // if there is a selection, but it is not the search string, then
207 // we basically ignore it. (FIXME We ought to replace only within
208 // the selection.)
209 // if there is no selection, then:
210 //  (i) if some search string has been provided, then we find it.
211 //      (think of how the dialog works when you hit "replace" the
212 //      first time.) 
213 // (ii) if no search string has been provided, then we treat the
214 //      word the cursor is in as the search string. (why? i have no
215 //      idea.) but this only works in text?
216 //
217 // returns the number of replacements made (one, if any) and 
218 // whether anything at all was done.
219 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
220                            docstring const & replacestr, bool case_sens,
221                            bool whole, bool forward, bool findnext)
222 {
223         Cursor & cur = bv->cursor();
224         if (!cur.selection()) {
225                 // no selection, non-empty search string: find it
226                 if (!searchstr.empty()) {
227                         findOne(bv, searchstr, case_sens, whole, forward);
228                         return make_pair(true, 0);
229                 }
230                 // empty search string
231                 if (!cur.inTexted())
232                         // bail in math
233                         return make_pair(false, 0);
234                 // select current word and treat it as the search string
235                 cur.innerText()->selectWord(cur, WHOLE_WORD);
236                 searchstr = cur.selectionAsString(false);
237         }
238         
239         // if we still don't have a search string, report the error
240         // and abort.
241         if (!searchAllowed(searchstr))
242                 return make_pair(false, 0);
243         
244         bool have_selection = cur.selection();
245         docstring const selected = cur.selectionAsString(false);
246         bool match = 
247                 case_sens
248                 ? searchstr == selected
249                 : compare_no_case(searchstr, selected) == 0;
250
251         // no selection or current selection is not search word:
252         // just find the search word
253         if (!have_selection || !match) {
254                 findOne(bv, searchstr, case_sens, whole, forward);
255                 return make_pair(true, 0);
256         }
257
258         // we're now actually ready to replace. if the buffer is
259         // read-only, we can't, though.
260         if (bv->buffer().isReadonly())
261                 return make_pair(false, 0);
262
263         cap::replaceSelectionWithString(cur, replacestr);
264         if (forward) {
265                 cur.pos() += replacestr.length();
266                 LASSERT(cur.pos() <= cur.lastpos(),
267                         cur.pos() = cur.lastpos());
268         }
269         if (findnext)
270                 findOne(bv, searchstr, case_sens, whole, forward, false);
271
272         return make_pair(true, 1);
273 }
274
275 } // namespace anon
276
277
278 docstring const find2string(docstring const & search,
279                             bool casesensitive, bool matchword, bool forward)
280 {
281         odocstringstream ss;
282         ss << search << '\n'
283            << int(casesensitive) << ' '
284            << int(matchword) << ' '
285            << int(forward);
286         return ss.str();
287 }
288
289
290 docstring const replace2string(docstring const & replace,
291                                docstring const & search,
292                                bool casesensitive, bool matchword,
293                                bool all, bool forward, bool findnext)
294 {
295         odocstringstream ss;
296         ss << replace << '\n'
297            << search << '\n'
298            << int(casesensitive) << ' '
299            << int(matchword) << ' '
300            << int(all) << ' '
301            << int(forward) << ' '
302            << int(findnext);
303         return ss.str();
304 }
305
306
307 bool lyxfind(BufferView * bv, FuncRequest const & ev)
308 {
309         if (!bv || ev.action() != LFUN_WORD_FIND)
310                 return false;
311
312         //lyxerr << "find called, cmd: " << ev << endl;
313
314         // data is of the form
315         // "<search>
316         //  <casesensitive> <matchword> <forward>"
317         docstring search;
318         docstring howto = split(ev.argument(), search, '\n');
319
320         bool casesensitive = parse_bool(howto);
321         bool matchword     = parse_bool(howto);
322         bool forward       = parse_bool(howto);
323
324         return findOne(bv, search, casesensitive, matchword, forward);
325 }
326
327
328 bool lyxreplace(BufferView * bv, 
329                 FuncRequest const & ev, bool has_deleted)
330 {
331         if (!bv || ev.action() != LFUN_WORD_REPLACE)
332                 return false;
333
334         // data is of the form
335         // "<search>
336         //  <replace>
337         //  <casesensitive> <matchword> <all> <forward> <findnext>"
338         docstring search;
339         docstring rplc;
340         docstring howto = split(ev.argument(), rplc, '\n');
341         howto = split(howto, search, '\n');
342
343         bool casesensitive = parse_bool(howto);
344         bool matchword     = parse_bool(howto);
345         bool all           = parse_bool(howto);
346         bool forward       = parse_bool(howto);
347         bool findnext      = howto.empty() ? true : parse_bool(howto);
348
349         int replace_count = 0;
350         bool update = false;
351
352         if (!has_deleted) {
353                 if (all) {
354                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
355                         update = replace_count > 0;
356                 } else {
357                         pair<bool, int> rv =
358                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
359                         update = rv.first;
360                         replace_count = rv.second;
361                 }
362
363                 Buffer const & buf = bv->buffer();
364                 if (!update) {
365                         // emit message signal.
366                         buf.message(_("String not found."));
367                 } else {
368                         if (replace_count == 0) {
369                                 buf.message(_("String found."));
370                         } else if (replace_count == 1) {
371                                 buf.message(_("String has been replaced."));
372                         } else {
373                                 docstring const str = 
374                                         bformat(_("%1$d strings have been replaced."), replace_count);
375                                 buf.message(str);
376                         }
377                 }
378         } else if (findnext) {
379                 // if we have deleted characters, we do not replace at all, but
380                 // rather search for the next occurence
381                 if (findOne(bv, search, casesensitive, matchword, forward))
382                         update = true;
383                 else
384                         bv->message(_("String not found."));
385         }
386         return update;
387 }
388
389
390 namespace {
391 bool findChange(DocIterator & cur, bool next)
392 {
393         if (!next)
394                 cur.backwardPos();
395         for (; cur; next ? cur.forwardPos() : cur.backwardPos())
396                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
397                         if (!next)
398                                 // if we search backwards, take a step forward
399                                 // to correctly set the anchor
400                                 cur.forwardPos();
401                         return true;
402                 }
403
404         return false;
405 }
406
407
408 bool findChange(BufferView * bv, bool next)
409 {
410         Cursor cur(*bv);
411         cur.setCursor(next ? bv->cursor().selectionEnd()
412                       : bv->cursor().selectionBegin());
413
414         // Are we within a change ? Then first search forward (backward),
415         // clear the selection and search the other way around (see the end
416         // of this function). This will avoid changes to be selected half.
417         bool search_both_sides = false;
418         Cursor tmpcur = cur;
419         // Leave math first
420         while (tmpcur.inMathed())
421                 tmpcur.pop_back();
422         Change change_next_pos
423                 = tmpcur.paragraph().lookupChange(tmpcur.pos());
424         if (change_next_pos.changed() && cur.inMathed()) {
425                 cur = tmpcur;
426                 search_both_sides = true;
427         } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
428                 Change change_prev_pos
429                         = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
430                 if (change_next_pos.isSimilarTo(change_prev_pos))
431                         search_both_sides = true;
432         }
433
434         if (!findChange(cur, next))
435                 return false;
436
437         bv->mouseSetCursor(cur, false);
438
439         CursorSlice & tip = cur.top();
440
441         if (!next)
442                 // take a step into the change
443                 tip.backwardPos();
444
445         Change orig_change = tip.paragraph().lookupChange(tip.pos());
446
447         if (next) {
448                 for (; tip.pit() < tip.lastpit() || tip.pos() < tip.lastpos(); tip.forwardPos()) {
449                         Change change = tip.paragraph().lookupChange(tip.pos());
450                         if (!change.isSimilarTo(orig_change))
451                                 break;
452                 }
453         } else {
454                 for (; tip.pit() > 0 || tip.pos() > 0;) {
455                         tip.backwardPos();
456                         Change change = tip.paragraph().lookupChange(tip.pos());
457                         if (!change.isSimilarTo(orig_change)) {
458                                 // take a step forward to correctly set the selection
459                                 tip.forwardPos();
460                                 break;
461                         }
462                 }
463         }
464
465         if (!search_both_sides) {
466                 // Now set the selection.
467                 bv->mouseSetCursor(cur, true);
468         } else {
469                 bv->mouseSetCursor(cur, false);
470                 findChange(bv, !next);
471         }
472
473         return true;
474 }
475 }
476
477
478 bool findNextChange(BufferView * bv)
479 {
480         return findChange(bv, true);
481 }
482
483
484 bool findPreviousChange(BufferView * bv)
485 {
486         return findChange(bv, false);
487 }
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                 if (!use_regexp) {
844                         // if par_as_string_nolead were emty, 
845                         // the following call to findAux will always *find* the string
846                         // in the checked data, and thus always using the slow
847                         // examining of the current text part.
848                         par_as_string_nolead = par_as_string;
849                 }
850         }
851         else {
852                 lead_size = identifyLeading(par_as_string);
853                 lead_as_string = par_as_string.substr(0, lead_size);
854                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
855         }
856
857         if (!use_regexp) {
858                 open_braces = identifyClosing(par_as_string);
859                 identifyClosing(par_as_string_nolead);
860                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
861                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
862         } else {
863                 string lead_as_regexp;
864                 if (lead_size > 0) {
865                         // @todo No need to search for \regexp{} insets in leading material
866                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
867                         par_as_string = par_as_string_nolead;
868                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
869                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
870                 }
871                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
872                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
873                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
874                 if (
875                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
876                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
877                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
878                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
879                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
880                         || regex_replace(par_as_string, par_as_string,
881                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
882                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
883                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
884                         ) {
885                         ++close_wildcards;
886                 }
887                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
888                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
889                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
890                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
891                 // If entered regexp must match at begin of searched string buffer
892                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
893                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
894                 regexp = lyx::regex(regexp_str);
895
896                 // If entered regexp may match wherever in searched string buffer
897                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
898                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
899                 regexp2 = lyx::regex(regexp2_str);
900         }
901 }
902
903
904 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
905 {
906         docstring docstr = stringifyFromForSearch(opt, cur, len);
907         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
908         string str = normalize(docstr, true);
909         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
910         if (! use_regexp) {
911                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
912                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
913                 if (at_begin) {
914                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
915                         if (str.substr(0, par_as_string.size()) == par_as_string)
916                                 return par_as_string.size();
917                 } else {
918                         size_t pos = str.find(par_as_string_nolead);
919                         if (pos != string::npos)
920                                 return par_as_string.size();
921                 }
922         } else {
923                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
924                 // Try all possible regexp matches, 
925                 //until one that verifies the braces match test is found
926                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
927                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
928                 sregex_iterator re_it_end;
929                 for (; re_it != re_it_end; ++re_it) {
930                         match_results<string::const_iterator> const & m = *re_it;
931                         // Check braces on the segment that matched the entire regexp expression,
932                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
933                         if (!braces_match(m[0].first, m[0].second, open_braces))
934                                 return 0;
935                         // Check braces on segments that matched all (.*?) subexpressions,
936                         // except the last "padding" one inserted by lyx.
937                         for (size_t i = 1; i < m.size() - 1; ++i)
938                                 if (!braces_match(m[i].first, m[i].second))
939                                         return false;
940                         // Exclude from the returned match length any length 
941                         // due to close wildcards added at end of regexp
942                         if (close_wildcards == 0)
943                                 return m[0].second - m[0].first;
944                         else
945                                 return m[m.size() - close_wildcards].first - m[0].first;
946                 }
947         }
948         return 0;
949 }
950
951
952 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
953 {
954         int res = findAux(cur, len, at_begin);
955         LYXERR(Debug::FIND,
956                "res=" << res << ", at_begin=" << at_begin
957                << ", matchword=" << opt.matchword
958                << ", inTexted=" << cur.inTexted());
959         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
960                 return res;
961         Paragraph const & par = cur.paragraph();
962         bool ws_left = (cur.pos() > 0)
963                 ? par.isWordSeparator(cur.pos() - 1)
964                 : true;
965         bool ws_right = (cur.pos() + res < par.size())
966                 ? par.isWordSeparator(cur.pos() + res)
967                 : true;
968         LYXERR(Debug::FIND,
969                "cur.pos()=" << cur.pos() << ", res=" << res
970                << ", separ: " << ws_left << ", " << ws_right
971                << endl);
972         if (ws_left && ws_right)
973                 return res;
974         return 0;
975 }
976
977
978 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
979 {
980         string t;
981         if (! opt.casesensitive)
982                 t = lyx::to_utf8(lowercase(s));
983         else
984                 t = lyx::to_utf8(s);
985         // Remove \n at begin
986         while (!t.empty() && t[0] == '\n')
987                 t = t.substr(1);
988         // Remove \n at end
989         while (!t.empty() && t[t.size() - 1] == '\n')
990                 t = t.substr(0, t.size() - 1);
991         size_t pos;
992         // Replace all other \n with spaces
993         while ((pos = t.find("\n")) != string::npos)
994                 t.replace(pos, 1, " ");
995         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
996         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
997         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
998                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
999
1000         // FIXME - check what preceeds the brace
1001         if (hack_braces) {
1002                 if (opt.ignoreformat)
1003                         while (regex_replace(t, t, "\\{", "_x_<")
1004                                || regex_replace(t, t, "\\}", "_x_>"))
1005                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1006                 else
1007                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1008                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1009                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1010         }
1011
1012         return t;
1013 }
1014
1015
1016 docstring stringifyFromCursor(DocIterator const & cur, int len)
1017 {
1018         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1019         if (cur.inTexted()) {
1020                 Paragraph const & par = cur.paragraph();
1021                 // TODO what about searching beyond/across paragraph breaks ?
1022                 // TODO Try adding a AS_STR_INSERTS as last arg
1023                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1024                         int(par.size()) : cur.pos() + len;
1025                 OutputParams runparams(&cur.buffer()->params().encoding());
1026                 odocstringstream os;
1027                 runparams.nice = true;
1028                 runparams.flavor = OutputParams::LATEX;
1029                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1030                 // No side effect of file copying and image conversion
1031                 runparams.dryrun = true;
1032                 LYXERR(Debug::FIND, "Stringifying with cur: "
1033                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1034                 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
1035         } else if (cur.inMathed()) {
1036                 docstring s;
1037                 CursorSlice cs = cur.top();
1038                 MathData md = cs.cell();
1039                 MathData::const_iterator it_end =
1040                         (( len == -1 || cs.pos() + len > int(md.size()))
1041                          ? md.end()
1042                          : md.begin() + cs.pos() + len );
1043                 for (MathData::const_iterator it = md.begin() + cs.pos();
1044                      it != it_end; ++it)
1045                         s = s + asString(*it);
1046                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1047                 return s;
1048         }
1049         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1050         return docstring();
1051 }
1052
1053
1054 /** Computes the LaTeX export of buf starting from cur and ending len positions
1055  * after cur, if len is positive, or at the paragraph or innermost inset end
1056  * if len is -1.
1057  */
1058 docstring latexifyFromCursor(DocIterator const & cur, int len)
1059 {
1060         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1061         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1062                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1063         Buffer const & buf = *cur.buffer();
1064         LBUFERR(buf.params().isLatex());
1065
1066         TexRow texrow;
1067         odocstringstream ods;
1068         otexstream os(ods, texrow);
1069         OutputParams runparams(&buf.params().encoding());
1070         runparams.nice = false;
1071         runparams.flavor = OutputParams::LATEX;
1072         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1073         // No side effect of file copying and image conversion
1074         runparams.dryrun = true;
1075
1076         if (cur.inTexted()) {
1077                 // @TODO what about searching beyond/across paragraph breaks ?
1078                 pos_type endpos = cur.paragraph().size();
1079                 if (len != -1 && endpos > cur.pos() + len)
1080                         endpos = cur.pos() + len;
1081                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1082                           string(), cur.pos(), endpos);
1083                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1084         } else if (cur.inMathed()) {
1085                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1086                 for (int s = cur.depth() - 1; s >= 0; --s) {
1087                         CursorSlice const & cs = cur[s];
1088                         if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1089                                 WriteStream ws(ods);
1090                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1091                                 break;
1092                         }
1093                 }
1094
1095                 CursorSlice const & cs = cur.top();
1096                 MathData md = cs.cell();
1097                 MathData::const_iterator it_end =
1098                         ((len == -1 || cs.pos() + len > int(md.size()))
1099                          ? md.end()
1100                          : md.begin() + cs.pos() + len);
1101                 for (MathData::const_iterator it = md.begin() + cs.pos();
1102                      it != it_end; ++it)
1103                         ods << asString(*it);
1104
1105                 // Retrieve the math environment type, and add '$' or '$]'
1106                 // or others (\end{equation}) accordingly
1107                 for (int s = cur.depth() - 1; s >= 0; --s) {
1108                         CursorSlice const & cs = cur[s];
1109                         InsetMath * inset = cs.asInsetMath();
1110                         if (inset && inset->asHullInset()) {
1111                                 WriteStream ws(ods);
1112                                 inset->asHullInset()->footer_write(ws);
1113                                 break;
1114                         }
1115                 }
1116                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1117         } else {
1118                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1119         }
1120         return ods.str();
1121 }
1122
1123
1124 /** Finalize an advanced find operation, advancing the cursor to the innermost
1125  ** position that matches, plus computing the length of the matching text to
1126  ** be selected
1127  **/
1128 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1129 {
1130         // Search the foremost position that matches (avoids find of entire math
1131         // inset when match at start of it)
1132         size_t d;
1133         DocIterator old_cur(cur.buffer());
1134         do {
1135                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1136                 d = cur.depth();
1137                 old_cur = cur;
1138                 cur.forwardPos();
1139         } while (cur && cur.depth() > d && match(cur) > 0);
1140         cur = old_cur;
1141         LASSERT(match(cur) > 0, return 0);
1142         LYXERR(Debug::FIND, "Ok");
1143
1144         // Compute the match length
1145         int len = 1;
1146         if (cur.pos() + len > cur.lastpos())
1147                 return 0;
1148         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1149         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1150                 ++len;
1151                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1152         }
1153         // Length of matched text (different from len param)
1154         int old_len = match(cur, len);
1155         int new_len;
1156         // Greedy behaviour while matching regexps
1157         while ((new_len = match(cur, len + 1)) > old_len) {
1158                 ++len;
1159                 old_len = new_len;
1160                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1161         }
1162         return len;
1163 }
1164
1165
1166 /// Finds forward
1167 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1168 {
1169         if (!cur)
1170                 return 0;
1171         while (!theApp()->longOperationCancelled() && cur) {
1172                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1173                 int match_len = match(cur, -1, false);
1174                 LYXERR(Debug::FIND, "match_len: " << match_len);
1175                 if (match_len) {
1176                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1177                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1178                                 int match_len = match(cur);
1179                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1180                                 if (match_len) {
1181                                         // Sometimes in finalize we understand it wasn't a match
1182                                         // and we need to continue the outest loop
1183                                         int len = findAdvFinalize(cur, match);
1184                                         if (len > 0)
1185                                                 return len;
1186                                 }
1187                         }
1188                         if (!cur)
1189                                 return 0;
1190                 }
1191                 if (cur.pit() < cur.lastpit()) {
1192                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1193                         cur.forwardPar();
1194                 } else {
1195                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1196                         cur.pos() = cur.lastpos();
1197                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1198                         cur.forwardPos();
1199                 }
1200         }
1201         return 0;
1202 }
1203
1204
1205 /// Find the most backward consecutive match within same paragraph while searching backwards.
1206 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1207 {
1208         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1209         DocIterator tmp_cur = cur;
1210         int len = findAdvFinalize(tmp_cur, match);
1211         Inset & inset = cur.inset();
1212         for (; cur != cur_begin; cur.backwardPos()) {
1213                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1214                 DocIterator new_cur = cur;
1215                 new_cur.backwardPos();
1216                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1217                         break;
1218                 int new_len = findAdvFinalize(new_cur, match);
1219                 if (new_len == len)
1220                         break;
1221                 len = new_len;
1222         }
1223         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1224         return len;
1225 }
1226
1227
1228 /// Finds backwards
1229 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1230 {
1231         if (! cur)
1232                 return 0;
1233         // Backup of original position
1234         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1235         if (cur == cur_begin)
1236                 return 0;
1237         cur.backwardPos();
1238         DocIterator cur_orig(cur);
1239         bool found_match;
1240         bool pit_changed = false;
1241         found_match = false;
1242         do {
1243                 cur.pos() = 0;
1244                 found_match = match(cur, -1, false);
1245
1246                 if (found_match) {
1247                         if (pit_changed)
1248                                 cur.pos() = cur.lastpos();
1249                         else
1250                                 cur.pos() = cur_orig.pos();
1251                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1252                         DocIterator cur_prev_iter;
1253                         do {
1254                                 found_match = match(cur);
1255                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1256                                        << found_match << ", cur: " << cur);
1257                                 if (found_match)
1258                                         return findMostBackwards(cur, match);
1259
1260                                 // Stop if begin of document reached
1261                                 if (cur == cur_begin)
1262                                         break;
1263                                 cur_prev_iter = cur;
1264                                 cur.backwardPos();
1265                         } while (true);
1266                 }
1267                 if (cur == cur_begin)
1268                         break;
1269                 if (cur.pit() > 0)
1270                         --cur.pit();
1271                 else
1272                         cur.backwardPos();
1273                 pit_changed = true;
1274         } while (!theApp()->longOperationCancelled());
1275         return 0;
1276 }
1277
1278
1279 } // anonym namespace
1280
1281
1282 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1283                                  DocIterator const & cur, int len)
1284 {
1285         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1286                 return docstring());
1287         if (!opt.ignoreformat)
1288                 return latexifyFromCursor(cur, len);
1289         else
1290                 return stringifyFromCursor(cur, len);
1291 }
1292
1293
1294 FindAndReplaceOptions::FindAndReplaceOptions(
1295         docstring const & find_buf_name, bool casesensitive,
1296         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1297         docstring const & repl_buf_name, bool keep_case,
1298         SearchScope scope)
1299         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1300           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1301           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1302 {
1303 }
1304
1305
1306 namespace {
1307
1308
1309 /** Check if 'len' letters following cursor are all non-lowercase */
1310 static bool allNonLowercase(DocIterator const & cur, int len)
1311 {
1312         pos_type end_pos = cur.pos() + len;
1313         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1314                 if (isLowerCase(cur.paragraph().getChar(pos)))
1315                         return false;
1316         return true;
1317 }
1318
1319
1320 /** Check if first letter is upper case and second one is lower case */
1321 static bool firstUppercase(DocIterator const & cur)
1322 {
1323         char_type ch1, ch2;
1324         if (cur.pos() >= cur.lastpos() - 1) {
1325                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1326                 return false;
1327         }
1328         ch1 = cur.paragraph().getChar(cur.pos());
1329         ch2 = cur.paragraph().getChar(cur.pos()+1);
1330         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1331         LYXERR(Debug::FIND, "firstUppercase(): "
1332                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1333                << ch2 << "(" << char(ch2) << ")"
1334                << ", result=" << result << ", cur=" << cur);
1335         return result;
1336 }
1337
1338
1339 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1340  **
1341  ** \fixme What to do with possible further paragraphs in replace buffer ?
1342  **/
1343 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1344 {
1345         ParagraphList::iterator pit = buffer.paragraphs().begin();
1346         pos_type right = pos_type(1);
1347         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1348         right = pit->size() + 1;
1349         pit->changeCase(buffer.params(), right, right, others_case);
1350 }
1351
1352 } // anon namespace
1353
1354 ///
1355 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1356 {
1357         Cursor & cur = bv->cursor();
1358         if (opt.repl_buf_name == docstring())
1359                 return;
1360
1361         DocIterator sel_beg = cur.selectionBegin();
1362         DocIterator sel_end = cur.selectionEnd();
1363         if (&sel_beg.inset() != &sel_end.inset()
1364             || sel_beg.pit() != sel_end.pit())
1365                 return;
1366         int sel_len = sel_end.pos() - sel_beg.pos();
1367         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1368                << ", sel_len: " << sel_len << endl);
1369         if (sel_len == 0)
1370                 return;
1371         LASSERT(sel_len > 0, return);
1372
1373         if (!matchAdv(sel_beg, sel_len))
1374                 return;
1375
1376         // Build a copy of the replace buffer, adapted to the KeepCase option
1377         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1378         ostringstream oss;
1379         repl_buffer_orig.write(oss);
1380         string lyx = oss.str();
1381         Buffer repl_buffer("", false);
1382         repl_buffer.setUnnamed(true);
1383         LASSERT(repl_buffer.readString(lyx), return);
1384         if (opt.keep_case && sel_len >= 2) {
1385                 if (cur.inTexted()) {
1386                         if (firstUppercase(cur))
1387                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1388                         else if (allNonLowercase(cur, sel_len))
1389                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1390                 }
1391         }
1392         cap::cutSelection(cur, false, false);
1393         if (cur.inTexted()) {
1394                 repl_buffer.changeLanguage(
1395                         repl_buffer.language(),
1396                         cur.getFont().language());
1397                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1398                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1399                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1400                                         repl_buffer.params().documentClassPtr(),
1401                                         bv->buffer().errorList("Paste"));
1402                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1403                 sel_len = repl_buffer.paragraphs().begin()->size();
1404         } else if (cur.inMathed()) {
1405                 TexRow texrow;
1406                 odocstringstream ods;
1407                 otexstream os(ods, texrow);
1408                 OutputParams runparams(&repl_buffer.params().encoding());
1409                 runparams.nice = false;
1410                 runparams.flavor = OutputParams::LATEX;
1411                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1412                 runparams.dryrun = true;
1413                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1414                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1415                 docstring repl_latex = ods.str();
1416                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1417                 string s;
1418                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1419                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1420                 repl_latex = from_utf8(s);
1421                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1422                 MathData ar(cur.buffer());
1423                 asArray(repl_latex, ar, Parse::NORMAL);
1424                 cur.insert(ar);
1425                 sel_len = ar.size();
1426                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1427         }
1428         if (cur.pos() >= sel_len)
1429                 cur.pos() -= sel_len;
1430         else
1431                 cur.pos() = 0;
1432         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1433         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1434         bv->processUpdateFlags(Update::Force);
1435         bv->buffer().updatePreviews();
1436 }
1437
1438
1439 /// Perform a FindAdv operation.
1440 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1441 {
1442         DocIterator cur;
1443         int match_len = 0;
1444
1445         try {
1446                 MatchStringAdv matchAdv(bv->buffer(), opt);
1447                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1448                 if (length > 0)
1449                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1450                 findAdvReplace(bv, opt, matchAdv);
1451                 cur = bv->cursor();
1452                 if (opt.forward)
1453                         match_len = findForwardAdv(cur, matchAdv);
1454                 else
1455                         match_len = findBackwardsAdv(cur, matchAdv);
1456         } catch (...) {
1457                 // This may only be raised by lyx::regex()
1458                 bv->message(_("Invalid regular expression!"));
1459                 return false;
1460         }
1461
1462         if (match_len == 0) {
1463                 bv->message(_("Match not found!"));
1464                 return false;
1465         }
1466
1467         bv->message(_("Match found!"));
1468
1469         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1470         bv->putSelectionAt(cur, match_len, !opt.forward);
1471
1472         return true;
1473 }
1474
1475
1476 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1477 {
1478         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1479            << opt.casesensitive << ' '
1480            << opt.matchword << ' '
1481            << opt.forward << ' '
1482            << opt.expandmacros << ' '
1483            << opt.ignoreformat << ' '
1484            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1485            << opt.keep_case << ' '
1486            << int(opt.scope);
1487
1488         LYXERR(Debug::FIND, "built: " << os.str());
1489
1490         return os;
1491 }
1492
1493
1494 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1495 {
1496         LYXERR(Debug::FIND, "parsing");
1497         string s;
1498         string line;
1499         getline(is, line);
1500         while (line != "EOSS") {
1501                 if (! s.empty())
1502                         s = s + "\n";
1503                 s = s + line;
1504                 if (is.eof())   // Tolerate malformed request
1505                         break;
1506                 getline(is, line);
1507         }
1508         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1509         opt.find_buf_name = from_utf8(s);
1510         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1511         is.get();       // Waste space before replace string
1512         s = "";
1513         getline(is, line);
1514         while (line != "EOSS") {
1515                 if (! s.empty())
1516                         s = s + "\n";
1517                 s = s + line;
1518                 if (is.eof())   // Tolerate malformed request
1519                         break;
1520                 getline(is, line);
1521         }
1522         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1523         opt.repl_buf_name = from_utf8(s);
1524         is >> opt.keep_case;
1525         int i;
1526         is >> i;
1527         opt.scope = FindAndReplaceOptions::SearchScope(i);
1528         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1529                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);
1530         return is;
1531 }
1532
1533 } // lyx namespace