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