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