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