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