]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
continue spellchecking after "replace all"
[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().isUnchanged(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 \regex{} 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  ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
601  **       to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
602  **/
603 class MatchStringAdv {
604 public:
605         MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt);
606
607         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
608          ** constructor as opt.search, under the opt.* options settings.
609          **
610          ** @param at_begin
611          **     If set, then match is searched only against beginning of text starting at cur.
612          **     If unset, then match is searched anywhere in text starting at cur.
613          **
614          ** @return
615          ** The length of the matching text, or zero if no match was found.
616          **/
617         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
618
619 public:
620         /// buffer
621         lyx::Buffer const & buf;
622         /// options
623         FindAndReplaceOptions const & opt;
624
625 private:
626         /** Normalize a stringified or latexified LyX paragraph.
627          **
628          ** Normalize means:
629          ** <ul>
630          **   <li>if search is not casesensitive, then lowercase the string;
631          **   <li>remove any newline at begin or end of the string;
632          **   <li>replace any newline in the middle of the string with a simple space;
633          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
634          ** </ul>
635          **
636          ** @todo Normalization should also expand macros, if the corresponding
637          ** search option was checked.
638          **/
639         string normalize(docstring const & s) const;
640         // normalized string to search
641         string par_as_string;
642         // regular expression to use for searching
643         boost::regex regexp;
644         // same as regexp, but prefixed with a ".*"
645         boost::regex regexp2;
646         // unmatched open braces in the search string/regexp
647         int open_braces;
648         // number of (.*?) subexpressions added at end of search regexp for closing
649         // environments, math mode, styles, etc...
650         int close_wildcards;
651 };
652
653
654 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt)
655   : buf(buf), opt(opt)
656 {
657         par_as_string = normalize(opt.search);
658         open_braces = 0;
659         close_wildcards = 0;
660
661         if (! opt.regexp) {
662                 // Remove trailing closure of math, macros and environments, so to catch parts of them.
663                 do {
664                         LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
665                         if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
666                                         continue;
667                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
668                                         continue;
669                         // @todo need to account for open square braces as well ?
670                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
671                                         continue;
672                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
673                                         continue;
674                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
675                                 ++open_braces;
676                                 continue;
677                         }
678                         break;
679                 } while (true);
680                 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
681                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
682                 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
683         } else {
684                 par_as_string = escape_for_regex(par_as_string);
685                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
686                 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
687                 if (
688                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
689                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
690                                 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
691                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
692                                 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
693                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
694                                 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
695                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
696                 ) {
697                         ++close_wildcards;
698                 }
699                 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
700                 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
701                 LYXERR(Debug::DEBUG, "Close .*?  : " << close_wildcards);
702                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
703                 // Entered regexp must match at begin of searched string buffer
704                 par_as_string = string("\\`") + par_as_string;
705                 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
706                 regexp = boost::regex(par_as_string);
707                 regexp2 = boost::regex(string(".*") + par_as_string);
708         }
709 }
710
711
712 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
713 {
714         docstring docstr = stringifyFromForSearch(opt, cur, len);
715         LYXERR(Debug::DEBUG, "Matching against     '" << lyx::to_utf8(docstr) << "'");
716         string str = normalize(docstr);
717         LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
718         if (! opt.regexp) {
719                 if (at_begin) {
720                         if (str.substr(0, par_as_string.size()) == par_as_string)
721                                 return par_as_string.size();
722                 } else {
723                         size_t pos = str.find(par_as_string);
724                         if (pos != string::npos)
725                                 return par_as_string.size();
726                 }
727         } else {
728                 // Try all possible regexp matches, until one that verifies the braces match test is found
729                 boost::regex const *p_regexp = at_begin ? &regexp : &regexp2;
730                 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
731                 boost::sregex_iterator re_it_end;
732                 for (; re_it != re_it_end; ++re_it) {
733                         boost::match_results<string::const_iterator> const & m = *re_it;
734                         // Check braces on the segment that matched the entire regexp expression,
735                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
736                         if (! braces_match(m[0].first, m[0].second, open_braces))
737                                 return 0;
738                         // Check braces on segments that matched all (.*?) subexpressions.
739                         for (size_t i = 1; i < m.size(); ++i)
740                                 if (! braces_match(m[i].first, m[i].second))
741                                         return false;
742                         // Exclude from the returned match length any length due to close wildcards added at end of regexp
743                         if (close_wildcards == 0)
744                                 return m[0].second - m[0].first;
745                         else
746                                 return m[m.size() - close_wildcards].first - m[0].first;
747                 }
748         }
749         return 0;
750 }
751
752
753 string MatchStringAdv::normalize(docstring const & s) const
754 {
755         string t;
756         if (! opt.casesensitive)
757                 t = lyx::to_utf8(lowercase(s));
758         else
759                 t = lyx::to_utf8(s);
760         // Remove \n at begin
761         while (t.size() > 0 && t[0] == '\n')
762                 t = t.substr(1);
763         // Remove \n at end
764         while (t.size() > 0 && t[t.size() - 1] == '\n')
765                 t = t.substr(0, t.size() - 1);
766         size_t pos;
767         // Replace all other \n with spaces
768         while ((pos = t.find("\n")) != string::npos)
769                 t.replace(pos, 1, " ");
770         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
771         while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
772                 ;
773         return t;
774 }
775
776
777 docstring stringifyFromCursor(DocIterator const & cur, int len)
778 {
779         LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
780         if (cur.inTexted()) {
781                         Paragraph const & par = cur.paragraph();
782                         // TODO what about searching beyond/across paragraph breaks ?
783                         // TODO Try adding a AS_STR_INSERTS as last arg
784                         pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len;
785                         OutputParams runparams(&cur.buffer()->params().encoding());
786                         odocstringstream os;
787                         runparams.nice = true;
788                         runparams.flavor = OutputParams::LATEX;
789                         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
790                         // No side effect of file copying and image conversion
791                         runparams.dryrun = true;
792                         LYXERR(Debug::DEBUG, "Stringifying with cur: " << cur << ", from pos: " << cur.pos() << ", end: " << end);
793                         return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
794         } else if (cur.inMathed()) {
795                         odocstringstream os;
796                         CursorSlice cs = cur.top();
797                         MathData md = cs.cell();
798                         MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
799                         for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
800                                         os << *it;
801                         return os.str();
802         }
803         LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
804         return docstring();
805 }
806
807 /** Computes the LaTeX export of buf starting from cur and ending len positions
808  * after cur, if len is positive, or at the paragraph or innermost inset end
809  * if len is -1.
810  */
811
812 docstring latexifyFromCursor(DocIterator const & cur, int len)
813 {
814         LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
815         LYXERR(Debug::DEBUG, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
816                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
817         Buffer const & buf = *cur.buffer();
818         LASSERT(buf.isLatex(), /* */);
819
820         TexRow texrow;
821         odocstringstream ods;
822         OutputParams runparams(&buf.params().encoding());
823         runparams.nice = false;
824         runparams.flavor = OutputParams::LATEX;
825         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
826         // No side effect of file copying and image conversion
827         runparams.dryrun = true;
828
829         if (cur.inTexted()) {
830                         // @TODO what about searching beyond/across paragraph breaks ?
831                         ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
832                         for (int i = 0; i < cur.pit(); ++i)
833                                         ++pit;
834 //              ParagraphList::const_iterator pit_end = pit;
835 //              ++pit_end;
836 //              lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
837                 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
838                         ? pit->size() : cur.pos() + len;
839                 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
840                         cur.pos(), endpos);
841                 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
842         } else if (cur.inMathed()) {
843                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
844                 for (int s = cur.depth() - 1; s >= 0; --s) {
845                                 CursorSlice const & cs = cur[s];
846                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
847                                                 WriteStream ws(ods);
848                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
849                                                 break;
850                                 }
851                 }
852
853                 CursorSlice const & cs = cur.top();
854                 MathData md = cs.cell();
855                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
856                         ? md.end() : md.begin() + cs.pos() + len );
857                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
858                                 ods << *it;
859
860                 // MathData md = cur.cell();
861                 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
862                 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
863                 //      MathAtom const & ma = *it;
864                 //      ma.nucleus()->latex(buf, ods, runparams);
865                 // }
866
867                 // Retrieve the math environment type, and add '$' or '$]'
868                 // or others (\end{equation}) accordingly
869                 for (int s = cur.depth() - 1; s >= 0; --s) {
870                         CursorSlice const & cs = cur[s];
871                         InsetMath * inset = cs.asInsetMath();
872                         if (inset && inset->asHullInset()) {
873                                 WriteStream ws(ods);
874                                 inset->asHullInset()->footer_write(ws);
875                                 break;
876                         }
877                 }
878                 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
879         } else {
880                 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
881         }
882         return ods.str();
883 }
884
885 /** Finalize an advanced find operation, advancing the cursor to the innermost
886  ** position that matches, plus computing the length of the matching text to
887  ** be selected
888  **/
889 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
890 {
891         // Search the foremost position that matches (avoids find of entire math
892         // inset when match at start of it)
893         size_t d;
894         DocIterator old_cur(cur.buffer());
895         do {
896                 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
897                 d = cur.depth();
898                 old_cur = cur;
899                 cur.forwardPos();
900         } while (cur && cur.depth() > d && match(cur) > 0);
901         cur = old_cur;
902         LASSERT(match(cur) > 0, /* */);
903         LYXERR(Debug::DEBUG, "Ok");
904
905         // Compute the match length
906         int len = 1;
907         LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
908         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
909                 ++len;
910                 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
911         }
912         // Length of matched text (different from len param)
913         int old_len = match(cur, len);
914         int new_len;
915         // Greedy behaviour while matching regexps
916         while ((new_len = match(cur, len + 1)) > old_len) {
917                 ++len;
918                 old_len = new_len;
919                 LYXERR(Debug::DEBUG, "verifying   match with len = " << len);
920         }
921         return len;
922 }
923
924
925 /// Finds forward
926 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
927 {
928         if (!cur)
929                 return 0;
930         int wrap_answer;
931         do {
932                 while (cur && !match(cur, -1, false)) {
933                         if (cur.pit() < cur.lastpit())
934                                 cur.forwardPar();
935                         else {
936                                 cur.forwardPos();
937                         }
938                 }
939                 for (; cur; cur.forwardPos()) {
940                         if (match(cur))
941                                 return findAdvFinalize(cur, match);
942                 }
943                 wrap_answer = frontend::Alert::prompt(
944                         _("Wrap search ?"),
945                         _("End of document reached while searching forward\n"
946                                 "\n"
947                                 "Continue searching from beginning ?"),
948                         0, 1, _("&Yes"), _("&No"));
949                 cur.clear();
950                 cur.push_back(CursorSlice(match.buf.inset()));
951         } while (wrap_answer == 0);
952         return 0;
953 }
954
955
956 /// Finds backwards
957 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
958         //      if (cur.pos() > 0 || cur.depth() > 0)
959         //              cur.backwardPos();
960         DocIterator cur_orig(cur);
961         if (match(cur_orig))
962                 findAdvFinalize(cur_orig, match);
963         //      int total = cur.bottom().pit() + 1;
964         int wrap_answer;
965         do {
966                 // TODO No ! così non va.
967                 bool pit_changed = false;
968                 while (cur && !match(cur, -1, false)) {
969                         if (cur.pit() > 0)
970                                 --cur.pit();
971                         else {
972                                 cur.backwardPos();
973                                 if (cur)
974                                         cur.pos() = 0;
975                         }
976                         pit_changed = true;
977                 }
978                 if (cur && pit_changed)
979                         cur.pos() = cur.lastpos();
980                 for (; cur; cur.backwardPos()) {
981                         if (match(cur)) {
982                                 // Find the most backward consecutive match within same paragraph while searching backwards.
983                                 int pit = cur.pit();
984                                 int old_len;
985                                 DocIterator old_cur;
986                                 int len = findAdvFinalize(cur, match);
987                                 do {
988                                         old_cur = cur;
989                                         old_len = len;
990                                         cur.backwardPos();
991                                         LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
992                                 } while (cur && cur.pit() == pit && match(cur)
993                                         && (len = findAdvFinalize(cur, match)) > old_len);
994                                 cur = old_cur;
995                                 len = old_len;
996                                 LYXERR(Debug::DEBUG, "cur_orig    : " << cur_orig);
997                                 LYXERR(Debug::DEBUG, "cur         : " << cur);
998                                 if (cur != cur_orig)
999                                         return len;
1000                         }
1001                 }
1002                 wrap_answer = frontend::Alert::prompt(
1003                         _("Wrap search ?"),
1004                         _("Beginning of document reached while searching backwards\n"
1005                                 "\n"
1006                                 "Continue searching from end ?"),
1007                         0, 1, _("&Yes"), _("&No"));
1008                 cur = doc_iterator_end(&match.buf);
1009                 cur.backwardPos();
1010         } while (wrap_answer == 0);
1011         return 0;
1012 }
1013
1014 } // anonym namespace
1015
1016
1017 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1018         DocIterator const & cur, int len)
1019 {
1020         if (!opt.ignoreformat)
1021                 return latexifyFromCursor(cur, len);
1022         else
1023                 return stringifyFromCursor(cur, len);
1024 }
1025
1026
1027 lyx::FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1028         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1029         bool regexp, docstring const & replace)
1030         : search(search), casesensitive(casesensitive), matchword(matchword),
1031         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1032         regexp(regexp), replace(replace)
1033 {
1034 }
1035
1036 /// Perform a FindAdv operation.
1037 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1038 {
1039         DocIterator cur = bv->cursor();
1040         int match_len = 0;
1041
1042         if (opt.search.empty()) {
1043                         bv->message(_("Search text is empty!"));
1044                         return false;
1045         }
1046 //      if (! bv->buffer()) {
1047 //              bv->message(_("No open document !"));
1048 //              return false;
1049 //      }
1050
1051         try {
1052                 MatchStringAdv const matchAdv(bv->buffer(), opt);
1053                 if (opt.forward)
1054                                 match_len = findForwardAdv(cur, matchAdv);
1055                 else
1056                                 match_len = findBackwardsAdv(cur, matchAdv);
1057         } catch (...) {
1058                 // This may only be raised by boost::regex()
1059                 bv->message(_("Invalid regular expression!"));
1060                 return false;
1061         }
1062
1063         if (match_len == 0) {
1064                 bv->message(_("Match not found!"));
1065                 return false;
1066         }
1067
1068         LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
1069         bv->putSelectionAt(cur, match_len, ! opt.forward);
1070         bv->message(_("Match found!"));
1071         if (opt.replace != docstring(from_utf8(LYX_FR_NULL_STRING))) {
1072                 dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1073         }
1074
1075         return true;
1076 }
1077
1078
1079 void findAdv(BufferView * bv, FuncRequest const & ev)
1080 {
1081         if (!bv || ev.action != LFUN_WORD_FINDADV)
1082                 return;
1083
1084         FindAndReplaceOptions opt;
1085         istringstream iss(to_utf8(ev.argument()));
1086         iss >> opt;
1087         findAdv(bv, opt);
1088 }
1089
1090
1091 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1092 {
1093         os << to_utf8(opt.search) << "\nEOSS\n"
1094            << opt.casesensitive << ' '
1095            << opt.matchword << ' '
1096            << opt.forward << ' '
1097            << opt.expandmacros << ' '
1098            << opt.ignoreformat << ' '
1099            << opt.regexp << ' '
1100            << to_utf8(opt.replace) << "\nEOSS\n";
1101
1102         LYXERR(Debug::DEBUG, "built: " << os.str());
1103
1104         return os;
1105 }
1106
1107 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1108 {
1109         LYXERR(Debug::DEBUG, "parsing");
1110         string s;
1111         string line;
1112         getline(is, line);
1113         while (line != "EOSS") {
1114                 if (! s.empty())
1115                                 s = s + "\n";
1116                 s = s + line;
1117                 if (is.eof())   // Tolerate malformed request
1118                                 break;
1119                 getline(is, line);
1120         }
1121         LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
1122         opt.search = from_utf8(s);
1123         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1124         is.get();       // Waste space before replace string
1125         s = "";
1126         getline(is, line);
1127         while (line != "EOSS") {
1128                 if (! s.empty())
1129                                 s = s + "\n";
1130                 s = s + line;
1131                 if (is.eof())   // Tolerate malformed request
1132                                 break;
1133                 getline(is, line);
1134         }
1135         LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1136                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);
1137         LYXERR(Debug::DEBUG, "replacing with: '" << s << "'");
1138         opt.replace = from_utf8(s);
1139         return is;
1140 }
1141
1142 } // lyx namespace