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