]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Why was there a 1 ? We only have to make sure that pos - 1 >= 0.
[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 "BufferList.h"
21 #include "buffer_funcs.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 "OutputParams.h"
29 #include "output_latex.h"
30 #include "Paragraph.h"
31 #include "ParIterator.h"
32 #include "TexRow.h"
33 #include "Text.h"
34 #include "FuncRequest.h"
35 #include "LyXFunc.h"
36
37 #include "mathed/InsetMath.h"
38 #include "mathed/InsetMathGrid.h"
39 #include "mathed/InsetMathHull.h"
40 #include "mathed/MathStream.h"
41
42 #include "frontends/alert.h"
43
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/gettext.h"
48 #include "support/lstrings.h"
49 #include "support/lassert.h"
50
51 #include "frontends/Application.h"
52 #include "frontends/LyXView.h"
53
54 #include <boost/regex.hpp>
55 #include <boost/next_prior.hpp>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 namespace lyx {
61
62 namespace {
63
64 bool parse_bool(docstring & howto)
65 {
66         if (howto.empty())
67                 return false;
68         docstring var;
69         howto = split(howto, var, ' ');
70         return var == "1";
71 }
72
73
74 class MatchString : public binary_function<Paragraph, pos_type, bool>
75 {
76 public:
77         MatchString(docstring const & str, bool cs, bool mw)
78                 : str(str), cs(cs), mw(mw)
79         {}
80
81         // returns true if the specified string is at the specified position
82         // del specifies whether deleted strings in ct mode will be considered
83         bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
84         {
85                 return par.find(str, cs, mw, pos, del);
86         }
87
88 private:
89         // search string
90         docstring str;
91         // case sensitive
92         bool cs;
93         // match whole words only
94         bool mw;
95 };
96
97
98 bool findForward(DocIterator & cur, MatchString const & match,
99                  bool find_del = true)
100 {
101         for (; cur; cur.forwardChar())
102                 if (cur.inTexted() &&
103                     match(cur.paragraph(), cur.pos(), find_del))
104                         return true;
105         return false;
106 }
107
108
109 bool findBackwards(DocIterator & cur, MatchString const & match,
110                  bool find_del = true)
111 {
112         while (cur) {
113                 cur.backwardChar();
114                 if (cur.inTexted() &&
115                     match(cur.paragraph(), cur.pos(), find_del))
116                         return true;
117         }
118         return false;
119 }
120
121
122 bool findChange(DocIterator & cur, bool next)
123 {
124         if (!next)
125                 cur.backwardPos();
126         for (; cur; next ? cur.forwardPos() : cur.backwardPos())
127                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
128                         if (!next)
129                                 // if we search backwards, take a step forward
130                                 // to correctly set the anchor
131                                 cur.forwardPos();
132                         return true;
133                 }
134
135         return false;
136 }
137
138
139 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
140 {
141         if (str.empty()) {
142                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
143                 return false;
144         }
145         return true;
146 }
147
148
149 bool find(BufferView * bv, docstring const & searchstr,
150         bool cs, bool mw, bool fw, bool find_del = true)
151 {
152         if (!searchAllowed(bv, searchstr))
153                 return false;
154
155         DocIterator cur = bv->cursor();
156
157         MatchString const match(searchstr, cs, mw);
158
159         bool found = fw ? findForward(cur, match, find_del) :
160                           findBackwards(cur, match, find_del);
161
162         if (found)
163                 bv->putSelectionAt(cur, searchstr.length(), !fw);
164
165         return found;
166 }
167
168
169 int replaceAll(BufferView * bv,
170                docstring const & searchstr, docstring const & replacestr,
171                bool cs, bool mw)
172 {
173         Buffer & buf = bv->buffer();
174
175         if (!searchAllowed(bv, searchstr) || buf.isReadonly())
176                 return 0;
177
178         MatchString const match(searchstr, cs, mw);
179         int num = 0;
180
181         int const rsize = replacestr.size();
182         int const ssize = searchstr.size();
183
184         Cursor cur(*bv);
185         cur.setCursor(doc_iterator_begin(&buf));
186         while (findForward(cur, match, false)) {
187                 // Backup current cursor position and font.
188                 pos_type const pos = cur.pos();
189                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
190                 cur.recordUndo();
191                 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
192                                                             buf.params().trackChanges);
193                 cur.paragraph().insert(pos, replacestr, font,
194                                        Change(buf.params().trackChanges ?
195                                               Change::INSERTED : Change::UNCHANGED));
196                 for (int i = 0; i < rsize + striked; ++i)
197                         cur.forwardChar();
198                 ++num;
199         }
200
201         buf.updateLabels();
202         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
203         if (num)
204                 buf.markDirty();
205         return num;
206 }
207
208
209 bool stringSelected(BufferView * bv, docstring & searchstr,
210                     bool cs, bool mw, bool fw)
211 {
212         // if nothing selected and searched string is empty, this
213         // means that we want to search current word at cursor position.
214         if (!bv->cursor().selection() && searchstr.empty()) {
215                 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
216                 searchstr = bv->cursor().selectionAsString(false);
217                 return true;
218         }
219
220         // if nothing selected or selection does not equal search
221         // string search and select next occurance and return
222         docstring const & str1 = searchstr;
223         docstring const str2 = bv->cursor().selectionAsString(false);
224         if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
225                 find(bv, searchstr, cs, mw, fw);
226                 return false;
227         }
228
229         return true;
230 }
231
232
233 int replace(BufferView * bv, docstring & searchstr,
234             docstring const & replacestr, bool cs, bool mw, bool fw)
235 {
236         if (!stringSelected(bv, searchstr, cs, mw, fw))
237                 return 0;
238
239         if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
240                 return 0;
241
242         Cursor & cur = bv->cursor();
243         cap::replaceSelectionWithString(cur, replacestr, fw);
244         bv->buffer().markDirty();
245         find(bv, searchstr, cs, mw, fw, false);
246         bv->buffer().updateMacros();
247         bv->processUpdateFlags(Update::Force | Update::FitCursor);
248
249         return 1;
250 }
251
252 } // namespace anon
253
254
255 docstring const find2string(docstring const & search,
256                          bool casesensitive, bool matchword, bool forward)
257 {
258         odocstringstream ss;
259         ss << search << '\n'
260            << int(casesensitive) << ' '
261            << int(matchword) << ' '
262            << int(forward);
263         return ss.str();
264 }
265
266
267 docstring const replace2string(docstring const & replace,
268         docstring const & search, bool casesensitive, bool matchword,
269         bool all, bool forward)
270 {
271         odocstringstream ss;
272         ss << replace << '\n'
273            << search << '\n'
274            << int(casesensitive) << ' '
275            << int(matchword) << ' '
276            << int(all) << ' '
277            << int(forward);
278         return ss.str();
279 }
280
281
282 bool find(BufferView * bv, FuncRequest const & ev)
283 {
284         if (!bv || ev.action != LFUN_WORD_FIND)
285                 return false;
286
287         //lyxerr << "find called, cmd: " << ev << endl;
288
289         // data is of the form
290         // "<search>
291         //  <casesensitive> <matchword> <forward>"
292         docstring search;
293         docstring howto = split(ev.argument(), search, '\n');
294
295         bool casesensitive = parse_bool(howto);
296         bool matchword     = parse_bool(howto);
297         bool forward       = parse_bool(howto);
298
299         return find(bv, search, casesensitive, matchword, forward);
300 }
301
302
303 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
304 {
305         if (!bv || ev.action != LFUN_WORD_REPLACE)
306                 return;
307
308         // data is of the form
309         // "<search>
310         //  <replace>
311         //  <casesensitive> <matchword> <all> <forward>"
312         docstring search;
313         docstring rplc;
314         docstring howto = split(ev.argument(), rplc, '\n');
315         howto = split(howto, search, '\n');
316
317         bool casesensitive = parse_bool(howto);
318         bool matchword     = parse_bool(howto);
319         bool all           = parse_bool(howto);
320         bool forward       = parse_bool(howto);
321
322         if (!has_deleted) {
323                 int const replace_count = all
324                         ? replaceAll(bv, search, rplc, casesensitive, matchword)
325                         : replace(bv, search, rplc, casesensitive, matchword, forward);
326
327                 Buffer & buf = bv->buffer();
328                 if (replace_count == 0) {
329                         // emit message signal.
330                         buf.message(_("String not found!"));
331                 } else {
332                         if (replace_count == 1) {
333                                 // emit message signal.
334                                 buf.message(_("String has been replaced."));
335                         } else {
336                                 docstring str = convert<docstring>(replace_count);
337                                 str += _(" strings have been replaced.");
338                                 // emit message signal.
339                                 buf.message(str);
340                         }
341                 }
342         } else {
343                 // if we have deleted characters, we do not replace at all, but
344                 // rather search for the next occurence
345                 if (find(bv, search, casesensitive, matchword, forward))
346                         bv->showCursor();
347                 else
348                         bv->message(_("String not found!"));
349         }
350 }
351
352
353 bool findNextChange(BufferView * bv)
354 {
355         return findChange(bv, true);
356 }
357
358
359 bool findPreviousChange(BufferView * bv)
360 {
361         return findChange(bv, false);
362 }
363
364
365 bool findChange(BufferView * bv, bool next)
366 {
367         if (bv->cursor().selection()) {
368                 // set the cursor at the beginning or at the end of the selection
369                 // before searching. Otherwise, the current change will be found.
370                 if (next != (bv->cursor().top() > bv->cursor().anchor()))
371                         bv->cursor().setCursorToAnchor();
372         }
373
374         DocIterator cur = bv->cursor();
375
376         // Are we within a change ? Then first search forward (backward),
377         // clear the selection and search the other way around (see the end
378         // of this function). This will avoid changes to be selected half.
379         bool search_both_sides = false;
380         if (cur.pos() > 0) {
381                 Change change_next_pos
382                         = cur.paragraph().lookupChange(cur.pos());
383                 Change change_prev_pos
384                         = cur.paragraph().lookupChange(cur.pos() - 1);
385                 if (change_next_pos.isSimilarTo(change_prev_pos))
386                         search_both_sides = true;
387         }
388
389         if (!findChange(cur, next))
390                 return false;
391
392         bv->cursor().setCursor(cur);
393         bv->cursor().resetAnchor();
394
395         if (!next)
396                 // take a step into the change
397                 cur.backwardPos();
398
399         Change orig_change = cur.paragraph().lookupChange(cur.pos());
400
401         CursorSlice & tip = cur.top();
402         if (next) {
403                 for (; !tip.at_end(); tip.forwardPos()) {
404                         Change change = tip.paragraph().lookupChange(tip.pos());
405                         if (change != orig_change)
406                                 break;
407                 }
408         } else {
409                 for (; !tip.at_begin();) {
410                         tip.backwardPos();
411                         Change change = tip.paragraph().lookupChange(tip.pos());
412                         if (change != orig_change) {
413                                 // take a step forward to correctly set the selection
414                                 tip.forwardPos();
415                                 break;
416                         }
417                 }
418         }
419
420         // Now put cursor to end of selection:
421         bv->cursor().setCursor(cur);
422         bv->cursor().setSelection();
423
424         if (search_both_sides) {
425                 bv->cursor().setSelection(false);
426                 findChange(bv, !next);
427         }
428
429         return true;
430 }
431
432 namespace {
433
434 typedef vector<pair<string, string> > Escapes;
435
436 /// A map of symbols and their escaped equivalent needed within a regex.
437 Escapes const & get_regexp_escapes()
438 {
439         static Escapes escape_map;
440         if (escape_map.empty()) {
441                 escape_map.push_back(pair<string, string>("\\", "\\\\"));
442                 escape_map.push_back(pair<string, string>("^", "\\^"));
443                 escape_map.push_back(pair<string, string>("$", "\\$"));
444                 escape_map.push_back(pair<string, string>("{", "\\{"));
445                 escape_map.push_back(pair<string, string>("}", "\\}"));
446                 escape_map.push_back(pair<string, string>("[", "\\["));
447                 escape_map.push_back(pair<string, string>("]", "\\]"));
448                 escape_map.push_back(pair<string, string>("(", "\\("));
449                 escape_map.push_back(pair<string, string>(")", "\\)"));
450                 escape_map.push_back(pair<string, string>("+", "\\+"));
451                 escape_map.push_back(pair<string, string>("*", "\\*"));
452                 escape_map.push_back(pair<string, string>(".", "\\."));
453         }
454         return escape_map;
455 }
456
457 /// A map of lyx escaped strings and their unescaped equivalent.
458 Escapes const & get_lyx_unescapes() {
459         static Escapes escape_map;
460         if (escape_map.empty()) {
461                 escape_map.push_back(pair<string, string>("{*}", "*"));
462                 escape_map.push_back(pair<string, string>("{[}", "["));
463                 escape_map.push_back(pair<string, string>("\\$", "$"));
464                 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
465                 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
466                 escape_map.push_back(pair<string, string>("\\sim ", "~"));
467                 escape_map.push_back(pair<string, string>("\\^", "^"));
468         }
469         return escape_map;
470 }
471
472 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
473  ** the found occurrence were escaped.
474  **/
475 string apply_escapes(string s, Escapes const & escape_map)
476 {
477         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
478         Escapes::const_iterator it;
479         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
480 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
481                 unsigned int pos = 0;
482                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
483                         s.replace(pos, it->first.length(), it->second);
484 //                      LYXERR(Debug::FIND, "After escape: " << s);
485                         pos += it->second.length();
486 //                      LYXERR(Debug::FIND, "pos: " << pos);
487                 }
488         }
489         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
490         return s;
491 }
492
493 /** Return the position of the closing brace matching the open one at s[pos],
494  ** or s.size() if not found.
495  **/
496 size_t find_matching_brace(string const & s, size_t pos)
497 {
498         LASSERT(s[pos] == '{', /* */);
499         int open_braces = 1;
500         for (++pos; pos < s.size(); ++pos) {
501                 if (s[pos] == '\\')
502                         ++pos;
503                 else if (s[pos] == '{')
504                         ++open_braces;
505                 else if (s[pos] == '}') {
506                         --open_braces;
507                         if (open_braces == 0)
508                                 return pos;
509                 }
510         }
511         return s.size();
512 }
513
514 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
515 string escape_for_regex(string s)
516 {
517         size_t pos = 0;
518         while (pos < s.size()) {
519                         size_t new_pos = s.find("\\regexp{", pos);
520                         if (new_pos == string::npos)
521                                         new_pos = s.size();
522                         LYXERR(Debug::FIND, "new_pos: " << new_pos);
523                         string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
524                         LYXERR(Debug::FIND, "t      : " << t);
525                         t = apply_escapes(t, get_regexp_escapes());
526                         s.replace(pos, new_pos - pos, t);
527                         new_pos = pos + t.size();
528                         LYXERR(Debug::FIND, "Regexp after escaping: " << s);
529                         LYXERR(Debug::FIND, "new_pos: " << new_pos);
530                         if (new_pos == s.size())
531                                         break;
532                         size_t end_pos = find_matching_brace(s, new_pos + 7);
533                         LYXERR(Debug::FIND, "end_pos: " << end_pos);
534                         t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
535                         LYXERR(Debug::FIND, "t      : " << t);
536                         if (end_pos == s.size()) {
537                                         s.replace(new_pos, end_pos - new_pos, t);
538                                         pos = s.size();
539                                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
540                                         break;
541                         }
542                         s.replace(new_pos, end_pos + 1 - new_pos, t);
543                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
544                         pos = new_pos + t.size();
545                         LYXERR(Debug::FIND, "pos: " << pos);
546         }
547         return s;
548 }
549
550 /// Wrapper for boost::regex_replace with simpler interface
551 bool regex_replace(string const & s, string & t, string const & searchstr,
552         string const & replacestr)
553 {
554         boost::regex e(searchstr);
555         ostringstream oss;
556         ostream_iterator<char, char> it(oss);
557         boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
558         // tolerate t and s be references to the same variable
559         bool rv = (s != oss.str());
560         t = oss.str();
561         return rv;
562 }
563
564 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
565  **
566  ** Verify that closed braces exactly match open braces. This avoids that, for example,
567  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
568  **
569  ** @param unmatched
570  ** Number of open braces that must remain open at the end for the verification to succeed.
571  **/
572 bool braces_match(string::const_iterator const & beg,
573         string::const_iterator const & end, int unmatched = 0)
574 {
575         int open_pars = 0;
576         string::const_iterator it = beg;
577         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
578         for (; it != end; ++it) {
579                 // Skip escaped braces in the count
580                 if (*it == '\\') {
581                         ++it;
582                         if (it == end)
583                                 break;
584                 } else if (*it == '{') {
585                         ++open_pars;
586                 } else if (*it == '}') {
587                         if (open_pars == 0) {
588                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
589                                 return false;
590                         } else
591                                 --open_pars;
592                 }
593         }
594         if (open_pars != unmatched) {
595           LYXERR(Debug::FIND, "Found " << open_pars 
596                  << " instead of " << unmatched 
597                  << " unmatched open braces at the end of count");
598                         return false;
599         }
600         LYXERR(Debug::FIND, "Braces match as expected");
601         return true;
602 }
603
604 /** The class performing a match between a position in the document and the FindAdvOptions.
605  **/
606 class MatchStringAdv {
607 public:
608         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
609
610         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
611          ** constructor as opt.search, under the opt.* options settings.
612          **
613          ** @param at_begin
614          **     If set, then match is searched only against beginning of text starting at cur.
615          **     If unset, then match is searched anywhere in text starting at cur.
616          **
617          ** @return
618          ** The length of the matching text, or zero if no match was found.
619          **/
620         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
621
622 public:
623         /// buffer
624         lyx::Buffer * p_buf;
625         /// first buffer on which search was started
626         lyx::Buffer * const p_first_buf;
627         /// options
628         FindAndReplaceOptions const & opt;
629
630 private:
631         /** Normalize a stringified or latexified LyX paragraph.
632          **
633          ** Normalize means:
634          ** <ul>
635          **   <li>if search is not casesensitive, then lowercase the string;
636          **   <li>remove any newline at begin or end of the string;
637          **   <li>replace any newline in the middle of the string with a simple space;
638          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
639          ** </ul>
640          **
641          ** @todo Normalization should also expand macros, if the corresponding
642          ** search option was checked.
643          **/
644         string normalize(docstring const & s) const;
645         // normalized string to search
646         string par_as_string;
647         // regular expression to use for searching
648         boost::regex regexp;
649         // same as regexp, but prefixed with a ".*"
650         boost::regex regexp2;
651         // unmatched open braces in the search string/regexp
652         int open_braces;
653         // number of (.*?) subexpressions added at end of search regexp for closing
654         // environments, math mode, styles, etc...
655         int close_wildcards;
656 };
657
658
659 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
660         : p_buf(&buf), p_first_buf(&buf), opt(opt)
661 {
662         par_as_string = normalize(opt.search);
663         open_braces = 0;
664         close_wildcards = 0;
665
666         if (! opt.regexp) {
667                 // Remove trailing closure of math, macros and environments, so to catch parts of them.
668                 do {
669                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
670                         if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
671                                         continue;
672                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
673                                         continue;
674                         // @todo need to account for open square braces as well ?
675                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
676                                         continue;
677                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
678                                         continue;
679                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
680                                 ++open_braces;
681                                 continue;
682                         }
683                         break;
684                 } while (true);
685                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
686                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
687                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
688         } else {
689                 par_as_string = escape_for_regex(par_as_string);
690                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
691                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
692                 if (
693                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
694                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
695                                 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
696                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
697                                 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
698                                 || regex_replace(par_as_string, par_as_string, 
699                                         "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
700                                 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
701                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
702                 ) {
703                         ++close_wildcards;
704                 }
705                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
706                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
707                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
708                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
709                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
710                 // If entered regexp must match at begin of searched string buffer
711                 regexp = boost::regex(string("\\`") + par_as_string);
712                 // If entered regexp may match wherever in searched string buffer
713                 regexp2 = boost::regex(string("\\`.*") + par_as_string);
714         }
715 }
716
717
718 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
719 {
720         docstring docstr = stringifyFromForSearch(opt, cur, len);
721         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
722         string str = normalize(docstr);
723         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
724         if (! opt.regexp) {
725                 if (at_begin) {
726                         if (str.substr(0, par_as_string.size()) == par_as_string)
727                                 return par_as_string.size();
728                 } else {
729                         size_t pos = str.find(par_as_string);
730                         if (pos != string::npos)
731                                 return par_as_string.size();
732                 }
733         } else {
734                 // Try all possible regexp matches, 
735                 //until one that verifies the braces match test is found
736                 boost::regex const *p_regexp = at_begin ? &regexp : &regexp2;
737                 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
738                 boost::sregex_iterator re_it_end;
739                 for (; re_it != re_it_end; ++re_it) {
740                         boost::match_results<string::const_iterator> const & m = *re_it;
741                         // Check braces on the segment that matched the entire regexp expression,
742                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
743                         if (! braces_match(m[0].first, m[0].second, open_braces))
744                                 return 0;
745                         // Check braces on segments that matched all (.*?) subexpressions.
746                         for (size_t i = 1; i < m.size(); ++i)
747                                 if (! braces_match(m[i].first, m[i].second))
748                                         return false;
749                         // Exclude from the returned match length any length 
750                         // due to close wildcards added at end of regexp
751                         if (close_wildcards == 0)
752                                 return m[0].second - m[0].first;
753                         else
754                                 return m[m.size() - close_wildcards].first - m[0].first;
755                 }
756         }
757         return 0;
758 }
759
760
761 string MatchStringAdv::normalize(docstring const & s) const
762 {
763         string t;
764         if (! opt.casesensitive)
765                 t = lyx::to_utf8(lowercase(s));
766         else
767                 t = lyx::to_utf8(s);
768         // Remove \n at begin
769         while (t.size() > 0 && t[0] == '\n')
770                 t = t.substr(1);
771         // Remove \n at end
772         while (t.size() > 0 && t[t.size() - 1] == '\n')
773                 t = t.substr(0, t.size() - 1);
774         size_t pos;
775         // Replace all other \n with spaces
776         while ((pos = t.find("\n")) != string::npos)
777                 t.replace(pos, 1, " ");
778         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
779         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
780         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
781                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
782         return t;
783 }
784
785
786 docstring stringifyFromCursor(DocIterator const & cur, int len)
787 {
788         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
789         if (cur.inTexted()) {
790                         Paragraph const & par = cur.paragraph();
791                         // TODO what about searching beyond/across paragraph breaks ?
792                         // TODO Try adding a AS_STR_INSERTS as last arg
793                         pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
794                                 int(par.size()) : cur.pos() + len;
795                         OutputParams runparams(&cur.buffer()->params().encoding());
796                         odocstringstream os;
797                         runparams.nice = true;
798                         runparams.flavor = OutputParams::LATEX;
799                         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
800                         // No side effect of file copying and image conversion
801                         runparams.dryrun = true;
802                         LYXERR(Debug::FIND, "Stringifying with cur: " 
803                                 << cur << ", from pos: " << cur.pos() << ", end: " << end);
804                         return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
805         } else if (cur.inMathed()) {
806                         odocstringstream os;
807                         CursorSlice cs = cur.top();
808                         MathData md = cs.cell();
809                         MathData::const_iterator it_end = 
810                                 ( ( len == -1 || cs.pos() + len > int(md.size()) )
811                                         ? md.end() : md.begin() + cs.pos() + len );
812                         for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
813                                         os << *it;
814                         return os.str();
815         }
816         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
817         return docstring();
818 }
819
820
821 /** Computes the LaTeX export of buf starting from cur and ending len positions
822  * after cur, if len is positive, or at the paragraph or innermost inset end
823  * if len is -1.
824  */
825 docstring latexifyFromCursor(DocIterator const & cur, int len)
826 {
827         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
828         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
829                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
830         Buffer const & buf = *cur.buffer();
831         LASSERT(buf.isLatex(), /* */);
832
833         TexRow texrow;
834         odocstringstream ods;
835         OutputParams runparams(&buf.params().encoding());
836         runparams.nice = false;
837         runparams.flavor = OutputParams::LATEX;
838         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
839         // No side effect of file copying and image conversion
840         runparams.dryrun = true;
841
842         if (cur.inTexted()) {
843                         // @TODO what about searching beyond/across paragraph breaks ?
844                         ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
845                         for (int i = 0; i < cur.pit(); ++i)
846                                         ++pit;
847 //              ParagraphList::const_iterator pit_end = pit;
848 //              ++pit_end;
849 //              lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
850                 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
851                         ? pit->size() : cur.pos() + len;
852                 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
853                         cur.pos(), endpos);
854                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
855         } else if (cur.inMathed()) {
856                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
857                 for (int s = cur.depth() - 1; s >= 0; --s) {
858                                 CursorSlice const & cs = cur[s];
859                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
860                                                 WriteStream ws(ods);
861                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
862                                                 break;
863                                 }
864                 }
865
866                 CursorSlice const & cs = cur.top();
867                 MathData md = cs.cell();
868                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
869                         ? md.end() : md.begin() + cs.pos() + len );
870                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
871                                 ods << *it;
872
873                 // MathData md = cur.cell();
874                 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
875                 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
876                 //      MathAtom const & ma = *it;
877                 //      ma.nucleus()->latex(buf, ods, runparams);
878                 // }
879
880                 // Retrieve the math environment type, and add '$' or '$]'
881                 // or others (\end{equation}) accordingly
882                 for (int s = cur.depth() - 1; s >= 0; --s) {
883                         CursorSlice const & cs = cur[s];
884                         InsetMath * inset = cs.asInsetMath();
885                         if (inset && inset->asHullInset()) {
886                                 WriteStream ws(ods);
887                                 inset->asHullInset()->footer_write(ws);
888                                 break;
889                         }
890                 }
891                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
892         } else {
893                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
894         }
895         return ods.str();
896 }
897
898
899 /** Finalize an advanced find operation, advancing the cursor to the innermost
900  ** position that matches, plus computing the length of the matching text to
901  ** be selected
902  **/
903 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
904 {
905         // Search the foremost position that matches (avoids find of entire math
906         // inset when match at start of it)
907         size_t d;
908         DocIterator old_cur(cur.buffer());
909         do {
910                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
911                 d = cur.depth();
912                 old_cur = cur;
913                 cur.forwardPos();
914         } while (cur && cur.depth() > d && match(cur) > 0);
915         cur = old_cur;
916         LASSERT(match(cur) > 0, /* */);
917         LYXERR(Debug::FIND, "Ok");
918
919         // Compute the match length
920         int len = 1;
921         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
922         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
923                 ++len;
924                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
925         }
926         // Length of matched text (different from len param)
927         int old_len = match(cur, len);
928         int new_len;
929         // Greedy behaviour while matching regexps
930         while ((new_len = match(cur, len + 1)) > old_len) {
931                 ++len;
932                 old_len = new_len;
933                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
934         }
935         return len;
936 }
937
938
939 /// Finds forward
940 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
941 {
942         if (!cur)
943                 return 0;
944         while (cur && !match(cur, -1, false)) {
945                 if (cur.pit() < cur.lastpit())
946                         cur.forwardPar();
947                 else {
948                         cur.forwardPos();
949                 }
950         }
951         for (; cur; cur.forwardPos()) {
952                 if (match(cur))
953                         return findAdvFinalize(cur, match);
954         }
955         return 0;
956 }
957
958
959 /// Find the most backward consecutive match within same paragraph while searching backwards.
960 void findMostBackwards(DocIterator & cur, MatchStringAdv const & match, int & len)
961 {
962         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
963         len = findAdvFinalize(cur, match);
964         if (cur != cur_begin) {
965                 Inset & inset = cur.inset();
966                 int old_len;
967                 DocIterator old_cur;
968                 DocIterator dit2;
969                 do {
970                         old_cur = cur;
971                         old_len = len;
972                         cur.backwardPos();
973                         LYXERR(Debug::FIND, "findMostBackwards(): old_cur=" 
974                                 << old_cur << ", old_len=" << len << ", cur=" << cur);
975                         dit2 = cur;
976                 } while (cur != cur_begin && &cur.inset() == &inset && match(cur)
977                          && (len = findAdvFinalize(dit2, match)) > old_len);
978                 cur = old_cur;
979                 len = old_len;
980         }
981         LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
982 }
983
984
985 /// Finds backwards
986 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
987         if (! cur)
988                 return 0;
989         // Backup of original position
990         DocIterator cur_orig(cur);
991         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
992         if (cur == cur_begin)
993                 return 0;
994         bool found_match;
995         bool pit_changed = false;
996         found_match = false;
997         do {
998                 cur.pos() = 0;
999                 found_match = match(cur, -1, false);
1000
1001                 if (found_match) {
1002                         if (pit_changed)
1003                                 cur.pos() = cur.lastpos();
1004                         else
1005                                 cur.pos() = cur_orig.pos();
1006                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1007                         DocIterator cur_prev_iter;
1008                         while (true) {
1009                                 found_match = match(cur);
1010                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1011                                        << found_match << ", cur: " << cur);
1012                                 if (found_match) {
1013                                         int len;
1014                                         findMostBackwards(cur, match, len);
1015                                         if (cur < cur_orig)
1016                                                 return len;
1017                                 }
1018                                 // Prevent infinite loop at begin of document
1019                                 if (cur == cur_begin || cur == cur_prev_iter)
1020                                         break;
1021                                 cur_prev_iter = cur;
1022                                 cur.backwardPos();
1023                         }
1024                 }
1025                 if (cur == cur_begin)
1026                         break;
1027                 if (cur.pit() > 0)
1028                         --cur.pit();
1029                 else
1030                         cur.backwardPos();
1031                 pit_changed = true;
1032         } while (true);
1033         return 0;
1034 }
1035
1036
1037 } // anonym namespace
1038
1039
1040 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1041         DocIterator const & cur, int len)
1042 {
1043         if (!opt.ignoreformat)
1044                 return latexifyFromCursor(cur, len);
1045         else
1046                 return stringifyFromCursor(cur, len);
1047 }
1048
1049
1050 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1051         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1052         bool regexp, docstring const & replace, bool keep_case,
1053         SearchScope scope)
1054         : search(search), casesensitive(casesensitive), matchword(matchword),
1055         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1056         regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1057 {
1058 }
1059
1060
1061 /** Checks if the supplied character is lower-case */
1062 static bool isLowerCase(char_type ch) {
1063         return lowercase(ch) == ch;
1064 }
1065
1066
1067 /** Checks if the supplied character is upper-case */
1068 static bool isUpperCase(char_type ch) {
1069         return uppercase(ch) == ch;
1070 }
1071
1072
1073 /** Check if 'len' letters following cursor are all non-lowercase */
1074 static bool allNonLowercase(DocIterator const & cur, int len) {
1075         pos_type end_pos = cur.pos() + len;
1076         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1077                 if (isLowerCase(cur.paragraph().getChar(pos)))
1078                         return false;
1079         return true;
1080 }
1081
1082
1083 /** Check if first letter is upper case and second one is lower case */
1084 static bool firstUppercase(DocIterator const & cur) {
1085         char_type ch1, ch2;
1086         if (cur.pos() >= cur.lastpos() - 1) {
1087                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1088                 return false;
1089         }
1090         ch1 = cur.paragraph().getChar(cur.pos());
1091         ch2 = cur.paragraph().getChar(cur.pos()+1);
1092         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1093         LYXERR(Debug::FIND, "firstUppercase(): "
1094                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1095                << ch2 << "(" << char(ch2) << ")"
1096                << ", result=" << result << ", cur=" << cur);
1097         return result;
1098 }
1099
1100
1101 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1102  **
1103  ** \fixme What to do with possible further paragraphs in replace buffer ?
1104  **/
1105 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1106         ParagraphList::iterator pit = buffer.paragraphs().begin();
1107         pos_type right = pos_type(1);
1108         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1109         right = pit->size() + 1;
1110         pit->changeCase(buffer.params(), right, right, others_case);
1111 }
1112
1113
1114 /// Perform a FindAdv operation.
1115 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1116 {
1117         DocIterator cur = bv->cursor();
1118         int match_len = 0;
1119
1120         if (opt.search.empty()) {
1121                         bv->message(_("Search text is empty!"));
1122                         return false;
1123         }
1124
1125         MatchStringAdv matchAdv(bv->buffer(), opt);
1126         try {
1127                 if (opt.forward)
1128                                 match_len = findForwardAdv(cur, matchAdv);
1129                 else
1130                                 match_len = findBackwardsAdv(cur, matchAdv);
1131         } catch (...) {
1132                 // This may only be raised by boost::regex()
1133                 bv->message(_("Invalid regular expression!"));
1134                 return false;
1135         }
1136
1137         if (match_len == 0) {
1138                 bv->message(_("Match not found!"));
1139                 return false;
1140         }
1141
1142         LYXERR(Debug::FIND, "Putting selection at buf=" << matchAdv.p_buf
1143                 << "cur=" << cur << " with len: " << match_len);
1144
1145         bv->putSelectionAt(cur, match_len, ! opt.forward);
1146         if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING))) {
1147                 bv->message(_("Match found!"));
1148         } else {
1149                 string lyx = to_utf8(opt.replace);
1150                 // FIXME: Seems so stupid to me to rebuild a buffer here,
1151                 // when we already have one (replace_work_area_.buffer())
1152                 Buffer repl_buffer("", false);
1153                 repl_buffer.setUnnamed(true);
1154                 if (repl_buffer.readString(lyx)) {
1155                         if (opt.keep_case && match_len >= 2) {
1156                                 if (cur.inTexted()) {
1157                                         if (firstUppercase(cur))
1158                                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1159                                         else if (allNonLowercase(cur, match_len))
1160                                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1161                                 }
1162                         }
1163                         cap::cutSelection(bv->cursor(), false, false);
1164                         if (! cur.inMathed()) {
1165                                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1166                                 cap::pasteParagraphList(bv->cursor(), repl_buffer.paragraphs(),
1167                                                         repl_buffer.params().documentClassPtr(),
1168                                                         bv->buffer().errorList("Paste"));
1169                         } else {
1170                                 odocstringstream ods;
1171                                 OutputParams runparams(&repl_buffer.params().encoding());
1172                                 runparams.nice = false;
1173                                 runparams.flavor = OutputParams::LATEX;
1174                                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1175                                 runparams.dryrun = true;
1176                                 TexRow texrow;
1177                                 TeXOnePar(repl_buffer, repl_buffer.text(), 
1178                                           repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1179                                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1180                                 docstring repl_latex = ods.str();
1181                                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1182                                 string s;
1183                                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1184                                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1185                                 repl_latex = from_utf8(s);
1186                                 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1187                                 bv->cursor().niceInsert(repl_latex);
1188                         }
1189                         bv->putSelectionAt(cur, repl_buffer.paragraphs().begin()->size(), ! opt.forward);
1190                         bv->message(_("Match found and replaced !"));
1191                 } else
1192                         LASSERT(false, /**/);
1193         }
1194
1195         return true;
1196 }
1197
1198
1199 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1200 {
1201         os << to_utf8(opt.search) << "\nEOSS\n"
1202            << opt.casesensitive << ' '
1203            << opt.matchword << ' '
1204            << opt.forward << ' '
1205            << opt.expandmacros << ' '
1206            << opt.ignoreformat << ' '
1207            << opt.regexp << ' '
1208            << to_utf8(opt.replace) << "\nEOSS\n"
1209            << opt.keep_case << ' '
1210            << int(opt.scope);
1211
1212         LYXERR(Debug::FIND, "built: " << os.str());
1213
1214         return os;
1215 }
1216
1217 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1218 {
1219         LYXERR(Debug::FIND, "parsing");
1220         string s;
1221         string line;
1222         getline(is, line);
1223         while (line != "EOSS") {
1224                 if (! s.empty())
1225                                 s = s + "\n";
1226                 s = s + line;
1227                 if (is.eof())   // Tolerate malformed request
1228                                 break;
1229                 getline(is, line);
1230         }
1231         LYXERR(Debug::FIND, "searching for: '" << s << "'");
1232         opt.search = from_utf8(s);
1233         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1234         is.get();       // Waste space before replace string
1235         s = "";
1236         getline(is, line);
1237         while (line != "EOSS") {
1238                 if (! s.empty())
1239                                 s = s + "\n";
1240                 s = s + line;
1241                 if (is.eof())   // Tolerate malformed request
1242                                 break;
1243                 getline(is, line);
1244         }
1245         is >> opt.keep_case;
1246         int i;
1247         is >> i;
1248         opt.scope = FindAndReplaceOptions::SearchScope(i);
1249         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1250                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1251         LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1252         opt.replace = from_utf8(s);
1253         return is;
1254 }
1255
1256 } // lyx namespace