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