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