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