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