]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Implemented the "Current Buffer" & "Current (Master) Document" scopes in the Advanced...
[lyx.git] / src / lyxfind.cpp
1 /**
2  * \file lyxfind.cpp
3  * This file is part of LyX, the document processor.
4  * License details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jürgen Vigna
9  * \author Alfredo Braunstein
10  * \author Tommaso Cucinotta
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "lyxfind.h"
18
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Changes.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "OutputParams.h"
28 #include "output_latex.h"
29 #include "Paragraph.h"
30 #include "ParIterator.h"
31 #include "TexRow.h"
32 #include "Text.h"
33 #include "FuncRequest.h"
34 #include "LyXFunc.h"
35
36 #include "mathed/InsetMath.h"
37 #include "mathed/InsetMathGrid.h"
38 #include "mathed/InsetMathHull.h"
39 #include "mathed/MathStream.h"
40
41 #include "frontends/alert.h"
42
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
48 #include "support/lassert.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/LyXView.h"
52
53 #include <boost/regex.hpp>
54 #include <boost/next_prior.hpp>
55
56 using namespace std;
57 using namespace lyx::support;
58
59 namespace lyx {
60
61 namespace {
62
63 bool parse_bool(docstring & howto)
64 {
65         if (howto.empty())
66                 return false;
67         docstring var;
68         howto = split(howto, var, ' ');
69         return var == "1";
70 }
71
72
73 class MatchString : public binary_function<Paragraph, pos_type, bool>
74 {
75 public:
76         MatchString(docstring const & str, bool cs, bool mw)
77                 : str(str), cs(cs), mw(mw)
78         {}
79
80         // returns true if the specified string is at the specified position
81         // del specifies whether deleted strings in ct mode will be considered
82         bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
83         {
84                 return par.find(str, cs, mw, pos, del);
85         }
86
87 private:
88         // search string
89         docstring str;
90         // case sensitive
91         bool cs;
92         // match whole words only
93         bool mw;
94 };
95
96
97 bool findForward(DocIterator & cur, MatchString const & match,
98                  bool find_del = true)
99 {
100         for (; cur; cur.forwardChar())
101                 if (cur.inTexted() &&
102                     match(cur.paragraph(), cur.pos(), find_del))
103                         return true;
104         return false;
105 }
106
107
108 bool findBackwards(DocIterator & cur, MatchString const & match,
109                  bool find_del = true)
110 {
111         while (cur) {
112                 cur.backwardChar();
113                 if (cur.inTexted() &&
114                     match(cur.paragraph(), cur.pos(), find_del))
115                         return true;
116         }
117         return false;
118 }
119
120
121 bool findChange(DocIterator & cur, bool next)
122 {
123         if (!next)
124                 cur.backwardPos();
125         for (; cur; next ? cur.forwardPos() : cur.backwardPos())
126                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
127                         if (!next)
128                                 // if we search backwards, take a step forward
129                                 // to correctly set the anchor
130                                 cur.forwardPos();
131                         return true;
132                 }
133
134         return false;
135 }
136
137
138 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
139 {
140         if (str.empty()) {
141                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
142                 return false;
143         }
144         return true;
145 }
146
147
148 bool find(BufferView * bv, docstring const & searchstr,
149         bool cs, bool mw, bool fw, bool find_del = true)
150 {
151         if (!searchAllowed(bv, searchstr))
152                 return false;
153
154         DocIterator cur = bv->cursor();
155
156         MatchString const match(searchstr, cs, mw);
157
158         bool found = fw ? findForward(cur, match, find_del) :
159                           findBackwards(cur, match, find_del);
160
161         if (found)
162                 bv->putSelectionAt(cur, searchstr.length(), !fw);
163
164         return found;
165 }
166
167
168 int replaceAll(BufferView * bv,
169                docstring const & searchstr, docstring const & replacestr,
170                bool cs, bool mw)
171 {
172         Buffer & buf = bv->buffer();
173
174         if (!searchAllowed(bv, searchstr) || buf.isReadonly())
175                 return 0;
176
177         MatchString const match(searchstr, cs, mw);
178         int num = 0;
179
180         int const rsize = replacestr.size();
181         int const ssize = searchstr.size();
182
183         Cursor cur(*bv);
184         cur.setCursor(doc_iterator_begin(&buf));
185         while (findForward(cur, match, false)) {
186                 // Backup current cursor position and font.
187                 pos_type const pos = cur.pos();
188                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
189                 cur.recordUndo();
190                 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
191                                                             buf.params().trackChanges);
192                 cur.paragraph().insert(pos, replacestr, font,
193                                        Change(buf.params().trackChanges ?
194                                               Change::INSERTED : Change::UNCHANGED));
195                 for (int i = 0; i < rsize + striked; ++i)
196                         cur.forwardChar();
197                 ++num;
198         }
199
200         buf.updateLabels();
201         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
202         if (num)
203                 buf.markDirty();
204         return num;
205 }
206
207
208 bool stringSelected(BufferView * bv, docstring & searchstr,
209                     bool cs, bool mw, bool fw)
210 {
211         // if nothing selected and searched string is empty, this
212         // means that we want to search current word at cursor position.
213         if (!bv->cursor().selection() && searchstr.empty()) {
214                 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
215                 searchstr = bv->cursor().selectionAsString(false);
216                 return true;
217         }
218
219         // if nothing selected or selection does not equal search
220         // string search and select next occurance and return
221         docstring const & str1 = searchstr;
222         docstring const str2 = bv->cursor().selectionAsString(false);
223         if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
224                 find(bv, searchstr, cs, mw, fw);
225                 return false;
226         }
227
228         return true;
229 }
230
231
232 int replace(BufferView * bv, docstring & searchstr,
233             docstring const & replacestr, bool cs, bool mw, bool fw)
234 {
235         if (!stringSelected(bv, searchstr, cs, mw, fw))
236                 return 0;
237
238         if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
239                 return 0;
240
241         Cursor & cur = bv->cursor();
242         cap::replaceSelectionWithString(cur, replacestr, fw);
243         bv->buffer().markDirty();
244         find(bv, searchstr, cs, mw, fw, false);
245         bv->buffer().updateMacros();
246         bv->processUpdateFlags(Update::Force | Update::FitCursor);
247
248         return 1;
249 }
250
251 } // namespace anon
252
253
254 docstring const find2string(docstring const & search,
255                          bool casesensitive, bool matchword, bool forward)
256 {
257         odocstringstream ss;
258         ss << search << '\n'
259            << int(casesensitive) << ' '
260            << int(matchword) << ' '
261            << int(forward);
262         return ss.str();
263 }
264
265
266 docstring const replace2string(docstring const & replace,
267         docstring const & search, bool casesensitive, bool matchword,
268         bool all, bool forward)
269 {
270         odocstringstream ss;
271         ss << replace << '\n'
272            << search << '\n'
273            << int(casesensitive) << ' '
274            << int(matchword) << ' '
275            << int(all) << ' '
276            << int(forward);
277         return ss.str();
278 }
279
280
281 bool find(BufferView * bv, FuncRequest const & ev)
282 {
283         if (!bv || ev.action != LFUN_WORD_FIND)
284                 return false;
285
286         //lyxerr << "find called, cmd: " << ev << endl;
287
288         // data is of the form
289         // "<search>
290         //  <casesensitive> <matchword> <forward>"
291         docstring search;
292         docstring howto = split(ev.argument(), search, '\n');
293
294         bool casesensitive = parse_bool(howto);
295         bool matchword     = parse_bool(howto);
296         bool forward       = parse_bool(howto);
297
298         return find(bv, search, casesensitive, matchword, forward);
299 }
300
301
302 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
303 {
304         if (!bv || ev.action != LFUN_WORD_REPLACE)
305                 return;
306
307         // data is of the form
308         // "<search>
309         //  <replace>
310         //  <casesensitive> <matchword> <all> <forward>"
311         docstring search;
312         docstring rplc;
313         docstring howto = split(ev.argument(), rplc, '\n');
314         howto = split(howto, search, '\n');
315
316         bool casesensitive = parse_bool(howto);
317         bool matchword     = parse_bool(howto);
318         bool all           = parse_bool(howto);
319         bool forward       = parse_bool(howto);
320
321         if (!has_deleted) {
322                 int const replace_count = all
323                         ? replaceAll(bv, search, rplc, casesensitive, matchword)
324                         : replace(bv, search, rplc, casesensitive, matchword, forward);
325
326                 Buffer & buf = bv->buffer();
327                 if (replace_count == 0) {
328                         // emit message signal.
329                         buf.message(_("String not found!"));
330                 } else {
331                         if (replace_count == 1) {
332                                 // emit message signal.
333                                 buf.message(_("String has been replaced."));
334                         } else {
335                                 docstring str = convert<docstring>(replace_count);
336                                 str += _(" strings have been replaced.");
337                                 // emit message signal.
338                                 buf.message(str);
339                         }
340                 }
341         } else {
342                 // if we have deleted characters, we do not replace at all, but
343                 // rather search for the next occurence
344                 if (find(bv, search, casesensitive, matchword, forward))
345                         bv->showCursor();
346                 else
347                         bv->message(_("String not found!"));
348         }
349 }
350
351
352 bool findNextChange(BufferView * bv)
353 {
354         return findChange(bv, true);
355 }
356
357
358 bool findPreviousChange(BufferView * bv)
359 {
360         return findChange(bv, false);
361 }
362
363
364 bool findChange(BufferView * bv, bool next)
365 {
366         if (bv->cursor().selection()) {
367                 // set the cursor at the beginning or at the end of the selection
368                 // before searching. Otherwise, the current change will be found.
369                 if (next != (bv->cursor().top() > bv->cursor().anchor()))
370                         bv->cursor().setCursorToAnchor();
371         }
372
373         DocIterator cur = bv->cursor();
374
375         // Are we within a change ? Then first search forward (backward),
376         // clear the selection and search the other way around (see the end
377         // of this function). This will avoid changes to be selected half.
378         bool search_both_sides = false;
379         if (cur.pos() > 1) {
380                 Change change_next_pos
381                         = cur.paragraph().lookupChange(cur.pos());
382                 Change change_prev_pos
383                         = cur.paragraph().lookupChange(cur.pos() - 1);
384                 if (change_next_pos.isSimilarTo(change_prev_pos))
385                         search_both_sides = true;
386         }
387
388         if (!findChange(cur, next))
389                 return false;
390
391         bv->cursor().setCursor(cur);
392         bv->cursor().resetAnchor();
393
394         if (!next)
395                 // take a step into the change
396                 cur.backwardPos();
397
398         Change orig_change = cur.paragraph().lookupChange(cur.pos());
399
400         CursorSlice & tip = cur.top();
401         if (next) {
402                 for (; !tip.at_end(); tip.forwardPos()) {
403                         Change change = tip.paragraph().lookupChange(tip.pos());
404                         if (change != orig_change)
405                                 break;
406                 }
407         } else {
408                 for (; !tip.at_begin();) {
409                         tip.backwardPos();
410                         Change change = tip.paragraph().lookupChange(tip.pos());
411                         if (change != orig_change) {
412                                 // take a step forward to correctly set the selection
413                                 tip.forwardPos();
414                                 break;
415                         }
416                 }
417         }
418
419         // Now put cursor to end of selection:
420         bv->cursor().setCursor(cur);
421         bv->cursor().setSelection();
422
423         if (search_both_sides) {
424                 bv->cursor().setSelection(false);
425                 findChange(bv, !next);
426         }
427
428         return true;
429 }
430
431 namespace {
432
433 typedef vector<pair<string, string> > Escapes;
434
435 /// A map of symbols and their escaped equivalent needed within a regex.
436 Escapes const & get_regexp_escapes()
437 {
438         static Escapes escape_map;
439         if (escape_map.empty()) {
440                 escape_map.push_back(pair<string, string>("\\", "\\\\"));
441                 escape_map.push_back(pair<string, string>("^", "\\^"));
442                 escape_map.push_back(pair<string, string>("$", "\\$"));
443                 escape_map.push_back(pair<string, string>("{", "\\{"));
444                 escape_map.push_back(pair<string, string>("}", "\\}"));
445                 escape_map.push_back(pair<string, string>("[", "\\["));
446                 escape_map.push_back(pair<string, string>("]", "\\]"));
447                 escape_map.push_back(pair<string, string>("(", "\\("));
448                 escape_map.push_back(pair<string, string>(")", "\\)"));
449                 escape_map.push_back(pair<string, string>("+", "\\+"));
450                 escape_map.push_back(pair<string, string>("*", "\\*"));
451                 escape_map.push_back(pair<string, string>(".", "\\."));
452         }
453         return escape_map;
454 }
455
456 /// A map of lyx escaped strings and their unescaped equivalent.
457 Escapes const & get_lyx_unescapes() {
458         static Escapes escape_map;
459         if (escape_map.empty()) {
460                 escape_map.push_back(pair<string, string>("{*}", "*"));
461                 escape_map.push_back(pair<string, string>("{[}", "["));
462                 escape_map.push_back(pair<string, string>("\\$", "$"));
463                 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
464                 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
465                 escape_map.push_back(pair<string, string>("\\sim ", "~"));
466                 escape_map.push_back(pair<string, string>("\\^", "^"));
467         }
468         return escape_map;
469 }
470
471 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
472  ** the found occurrence were escaped.
473  **/
474 string apply_escapes(string s, Escapes const & escape_map)
475 {
476         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
477         Escapes::const_iterator it;
478         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
479 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
480                 unsigned int pos = 0;
481                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
482                         s.replace(pos, it->first.length(), it->second);
483 //                      LYXERR(Debug::FIND, "After escape: " << s);
484                         pos += it->second.length();
485 //                      LYXERR(Debug::FIND, "pos: " << pos);
486                 }
487         }
488         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
489         return s;
490 }
491
492 /** Return the position of the closing brace matching the open one at s[pos],
493  ** or s.size() if not found.
494  **/
495 size_t find_matching_brace(string const & s, size_t pos)
496 {
497         LASSERT(s[pos] == '{', /* */);
498         int open_braces = 1;
499         for (++pos; pos < s.size(); ++pos) {
500                 if (s[pos] == '\\')
501                         ++pos;
502                 else if (s[pos] == '{')
503                         ++open_braces;
504                 else if (s[pos] == '}') {
505                         --open_braces;
506                         if (open_braces == 0)
507                                 return pos;
508                 }
509         }
510         return s.size();
511 }
512
513 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
514 string escape_for_regex(string s)
515 {
516         size_t pos = 0;
517         while (pos < s.size()) {
518                         size_t new_pos = s.find("\\regexp{", pos);
519                         if (new_pos == string::npos)
520                                         new_pos = s.size();
521                         LYXERR(Debug::FIND, "new_pos: " << new_pos);
522                         string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
523                         LYXERR(Debug::FIND, "t      : " << t);
524                         t = apply_escapes(t, get_regexp_escapes());
525                         s.replace(pos, new_pos - pos, t);
526                         new_pos = pos + t.size();
527                         LYXERR(Debug::FIND, "Regexp after escaping: " << s);
528                         LYXERR(Debug::FIND, "new_pos: " << new_pos);
529                         if (new_pos == s.size())
530                                         break;
531                         size_t end_pos = find_matching_brace(s, new_pos + 7);
532                         LYXERR(Debug::FIND, "end_pos: " << end_pos);
533                         t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
534                         LYXERR(Debug::FIND, "t      : " << t);
535                         if (end_pos == s.size()) {
536                                         s.replace(new_pos, end_pos - new_pos, t);
537                                         pos = s.size();
538                                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
539                                         break;
540                         }
541                         s.replace(new_pos, end_pos + 1 - new_pos, t);
542                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
543                         pos = new_pos + t.size();
544                         LYXERR(Debug::FIND, "pos: " << pos);
545         }
546         return s;
547 }
548
549 /// Wrapper for boost::regex_replace with simpler interface
550 bool regex_replace(string const & s, string & t, string const & searchstr,
551         string const & replacestr)
552 {
553         boost::regex e(searchstr);
554         ostringstream oss;
555         ostream_iterator<char, char> it(oss);
556         boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
557         // tolerate t and s be references to the same variable
558         bool rv = (s != oss.str());
559         t = oss.str();
560         return rv;
561 }
562
563 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
564  **
565  ** Verify that closed braces exactly match open braces. This avoids that, for example,
566  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
567  **
568  ** @param unmatched
569  ** Number of open braces that must remain open at the end for the verification to succeed.
570  **/
571 bool braces_match(string::const_iterator const & beg,
572         string::const_iterator const & end, int unmatched = 0)
573 {
574         int open_pars = 0;
575         string::const_iterator it = beg;
576         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
577         for (; it != end; ++it) {
578                 // Skip escaped braces in the count
579                 if (*it == '\\') {
580                         ++it;
581                         if (it == end)
582                                 break;
583                 } else if (*it == '{') {
584                         ++open_pars;
585                 } else if (*it == '}') {
586                         if (open_pars == 0) {
587                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
588                                 return false;
589                         } else
590                                 --open_pars;
591                 }
592         }
593         if (open_pars != unmatched) {
594           LYXERR(Debug::FIND, "Found " << open_pars 
595                  << " instead of " << unmatched 
596                  << " unmatched open braces at the end of count");
597                         return false;
598         }
599         LYXERR(Debug::FIND, "Braces match as expected");
600         return true;
601 }
602
603 /** The class performing a match between a position in the document and the FindAdvOptions.
604  **/
605 class MatchStringAdv {
606 public:
607         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
608
609         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
610          ** constructor as opt.search, under the opt.* options settings.
611          **
612          ** @param at_begin
613          **     If set, then match is searched only against beginning of text starting at cur.
614          **     If unset, then match is searched anywhere in text starting at cur.
615          **
616          ** @return
617          ** The length of the matching text, or zero if no match was found.
618          **/
619         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
620
621 public:
622         /// buffer
623         lyx::Buffer * p_buf;
624         /// first buffer on which search was started
625         lyx::Buffer * const p_first_buf;
626         /// options
627         FindAndReplaceOptions const & opt;
628
629 private:
630         /** Normalize a stringified or latexified LyX paragraph.
631          **
632          ** Normalize means:
633          ** <ul>
634          **   <li>if search is not casesensitive, then lowercase the string;
635          **   <li>remove any newline at begin or end of the string;
636          **   <li>replace any newline in the middle of the string with a simple space;
637          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
638          ** </ul>
639          **
640          ** @todo Normalization should also expand macros, if the corresponding
641          ** search option was checked.
642          **/
643         string normalize(docstring const & s) const;
644         // normalized string to search
645         string par_as_string;
646         // regular expression to use for searching
647         boost::regex regexp;
648         // same as regexp, but prefixed with a ".*"
649         boost::regex regexp2;
650         // unmatched open braces in the search string/regexp
651         int open_braces;
652         // number of (.*?) subexpressions added at end of search regexp for closing
653         // environments, math mode, styles, etc...
654         int close_wildcards;
655 };
656
657
658 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
659         : p_buf(&buf), p_first_buf(&buf), opt(opt)
660 {
661         par_as_string = normalize(opt.search);
662         open_braces = 0;
663         close_wildcards = 0;
664
665         if (! opt.regexp) {
666                 // Remove trailing closure of math, macros and environments, so to catch parts of them.
667                 do {
668                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
669                         if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
670                                         continue;
671                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
672                                         continue;
673                         // @todo need to account for open square braces as well ?
674                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
675                                         continue;
676                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
677                                         continue;
678                         if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
679                                 ++open_braces;
680                                 continue;
681                         }
682                         break;
683                 } while (true);
684                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
685                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
686                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
687         } else {
688                 par_as_string = escape_for_regex(par_as_string);
689                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
690                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
691                 if (
692                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
693                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
694                                 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
695                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
696                                 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
697                                 || regex_replace(par_as_string, par_as_string, 
698                                         "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
699                                 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
700                                 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
701                 ) {
702                         ++close_wildcards;
703                 }
704                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
705                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
706                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
707                 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
708                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
709                 // If entered regexp must match at begin of searched string buffer
710                 regexp = boost::regex(string("\\`") + par_as_string);
711                 // If entered regexp may match wherever in searched string buffer
712                 regexp2 = boost::regex(string("\\`.*") + par_as_string);
713         }
714 }
715
716
717 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
718 {
719         docstring docstr = stringifyFromForSearch(opt, cur, len);
720         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
721         string str = normalize(docstr);
722         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
723         if (! opt.regexp) {
724                 if (at_begin) {
725                         if (str.substr(0, par_as_string.size()) == par_as_string)
726                                 return par_as_string.size();
727                 } else {
728                         size_t pos = str.find(par_as_string);
729                         if (pos != string::npos)
730                                 return par_as_string.size();
731                 }
732         } else {
733                 // Try all possible regexp matches, 
734                 //until one that verifies the braces match test is found
735                 boost::regex const *p_regexp = at_begin ? &regexp : &regexp2;
736                 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
737                 boost::sregex_iterator re_it_end;
738                 for (; re_it != re_it_end; ++re_it) {
739                         boost::match_results<string::const_iterator> const & m = *re_it;
740                         // Check braces on the segment that matched the entire regexp expression,
741                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
742                         if (! braces_match(m[0].first, m[0].second, open_braces))
743                                 return 0;
744                         // Check braces on segments that matched all (.*?) subexpressions.
745                         for (size_t i = 1; i < m.size(); ++i)
746                                 if (! braces_match(m[i].first, m[i].second))
747                                         return false;
748                         // Exclude from the returned match length any length 
749                         // due to close wildcards added at end of regexp
750                         if (close_wildcards == 0)
751                                 return m[0].second - m[0].first;
752                         else
753                                 return m[m.size() - close_wildcards].first - m[0].first;
754                 }
755         }
756         return 0;
757 }
758
759
760 string MatchStringAdv::normalize(docstring const & s) const
761 {
762         string t;
763         if (! opt.casesensitive)
764                 t = lyx::to_utf8(lowercase(s));
765         else
766                 t = lyx::to_utf8(s);
767         // Remove \n at begin
768         while (t.size() > 0 && t[0] == '\n')
769                 t = t.substr(1);
770         // Remove \n at end
771         while (t.size() > 0 && t[t.size() - 1] == '\n')
772                 t = t.substr(0, t.size() - 1);
773         size_t pos;
774         // Replace all other \n with spaces
775         while ((pos = t.find("\n")) != string::npos)
776                 t.replace(pos, 1, " ");
777         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
778         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
779         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
780                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
781         return t;
782 }
783
784
785 docstring stringifyFromCursor(DocIterator const & cur, int len)
786 {
787         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
788         if (cur.inTexted()) {
789                         Paragraph const & par = cur.paragraph();
790                         // TODO what about searching beyond/across paragraph breaks ?
791                         // TODO Try adding a AS_STR_INSERTS as last arg
792                         pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
793                                 int(par.size()) : cur.pos() + len;
794                         OutputParams runparams(&cur.buffer()->params().encoding());
795                         odocstringstream os;
796                         runparams.nice = true;
797                         runparams.flavor = OutputParams::LATEX;
798                         runparams.linelen = 100000; //lyxrc.plaintext_linelen;
799                         // No side effect of file copying and image conversion
800                         runparams.dryrun = true;
801                         LYXERR(Debug::FIND, "Stringifying with cur: " 
802                                 << cur << ", from pos: " << cur.pos() << ", end: " << end);
803                         return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
804         } else if (cur.inMathed()) {
805                         odocstringstream os;
806                         CursorSlice cs = cur.top();
807                         MathData md = cs.cell();
808                         MathData::const_iterator it_end = 
809                                 ( ( len == -1 || cs.pos() + len > int(md.size()) )
810                                         ? md.end() : md.begin() + cs.pos() + len );
811                         for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
812                                         os << *it;
813                         return os.str();
814         }
815         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
816         return docstring();
817 }
818
819
820 /** Computes the LaTeX export of buf starting from cur and ending len positions
821  * after cur, if len is positive, or at the paragraph or innermost inset end
822  * if len is -1.
823  */
824 docstring latexifyFromCursor(DocIterator const & cur, int len)
825 {
826         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
827         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
828                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
829         Buffer const & buf = *cur.buffer();
830         LASSERT(buf.isLatex(), /* */);
831
832         TexRow texrow;
833         odocstringstream ods;
834         OutputParams runparams(&buf.params().encoding());
835         runparams.nice = false;
836         runparams.flavor = OutputParams::LATEX;
837         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
838         // No side effect of file copying and image conversion
839         runparams.dryrun = true;
840
841         if (cur.inTexted()) {
842                         // @TODO what about searching beyond/across paragraph breaks ?
843                         ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
844                         for (int i = 0; i < cur.pit(); ++i)
845                                         ++pit;
846 //              ParagraphList::const_iterator pit_end = pit;
847 //              ++pit_end;
848 //              lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
849                 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
850                         ? pit->size() : cur.pos() + len;
851                 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
852                         cur.pos(), endpos);
853                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
854         } else if (cur.inMathed()) {
855                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
856                 for (int s = cur.depth() - 1; s >= 0; --s) {
857                                 CursorSlice const & cs = cur[s];
858                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
859                                                 WriteStream ws(ods);
860                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
861                                                 break;
862                                 }
863                 }
864
865                 CursorSlice const & cs = cur.top();
866                 MathData md = cs.cell();
867                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
868                         ? md.end() : md.begin() + cs.pos() + len );
869                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
870                                 ods << *it;
871
872                 // MathData md = cur.cell();
873                 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
874                 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
875                 //      MathAtom const & ma = *it;
876                 //      ma.nucleus()->latex(buf, ods, runparams);
877                 // }
878
879                 // Retrieve the math environment type, and add '$' or '$]'
880                 // or others (\end{equation}) accordingly
881                 for (int s = cur.depth() - 1; s >= 0; --s) {
882                         CursorSlice const & cs = cur[s];
883                         InsetMath * inset = cs.asInsetMath();
884                         if (inset && inset->asHullInset()) {
885                                 WriteStream ws(ods);
886                                 inset->asHullInset()->footer_write(ws);
887                                 break;
888                         }
889                 }
890                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
891         } else {
892                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
893         }
894         return ods.str();
895 }
896
897
898 /** Finalize an advanced find operation, advancing the cursor to the innermost
899  ** position that matches, plus computing the length of the matching text to
900  ** be selected
901  **/
902 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
903 {
904         // Search the foremost position that matches (avoids find of entire math
905         // inset when match at start of it)
906         size_t d;
907         DocIterator old_cur(cur.buffer());
908         do {
909                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
910                 d = cur.depth();
911                 old_cur = cur;
912                 cur.forwardPos();
913         } while (cur && cur.depth() > d && match(cur) > 0);
914         cur = old_cur;
915         LASSERT(match(cur) > 0, /* */);
916         LYXERR(Debug::FIND, "Ok");
917
918         // Compute the match length
919         int len = 1;
920         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
921         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
922                 ++len;
923                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
924         }
925         // Length of matched text (different from len param)
926         int old_len = match(cur, len);
927         int new_len;
928         // Greedy behaviour while matching regexps
929         while ((new_len = match(cur, len + 1)) > old_len) {
930                 ++len;
931                 old_len = new_len;
932                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
933         }
934         return len;
935 }
936
937
938 /** Switch p_buf to point to next document buffer.
939  **
940  ** Return true if restarted from master-document buffer.
941  **
942  ** @note
943  ** Not using p_buf->allRelatives() here, because I'm not sure
944  ** whether or not the returned order is independent of p_buf.
945  **/
946 bool next_document_buffer(Buffer * & p_buf) {
947         Buffer *p_master = p_buf;
948         Buffer *p_old;
949         do {
950                 p_old = p_master;
951                 p_master = const_cast<Buffer *>(p_master->masterBuffer());
952                 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
953         } while (p_master != p_old);
954         LASSERT(p_master != NULL, /**/);
955         std::vector<Buffer *> v_children;
956         /* Root master added as first buffer in the vector */
957         v_children.push_back(p_master);
958         p_master->getChildren(v_children, true);
959         LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
960         std::vector<Buffer *>::const_iterator it = std::find(v_children.begin(), v_children.end(), p_buf);
961         LASSERT(it != v_children.end(), /**/)
962         ++it;
963         if (it == v_children.end()) {
964                 p_buf = *v_children.begin();
965                 return true;
966         }
967         p_buf = *it;
968         return false;
969 }
970
971
972 /** Switch p_buf to point to previous document buffer.
973  **
974  ** Return true if restarted from last child buffer.
975  **
976  ** @note
977  ** Not using p_buf->allRelatives() here, because I'm not sure
978  ** whether or not the returned order is independent of p_buf.
979  **/
980 bool prev_document_buffer(Buffer * & p_buf) {
981         Buffer *p_master = p_buf;
982         Buffer *p_old;
983         do {
984                 p_old = p_master;
985                 p_master = const_cast<Buffer *>(p_master->masterBuffer());
986                 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
987         } while (p_master != p_old);
988         LASSERT(p_master != NULL, /**/);
989         std::vector<Buffer *> v_children;
990         /* Root master added as first buffer in the vector */
991         v_children.push_back(p_master);
992         p_master->getChildren(v_children, true);
993         LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
994         std::vector<Buffer *>::const_iterator it = std::find(v_children.begin(), v_children.end(), p_buf);
995         LASSERT(it != v_children.end(), /**/)
996         if (it == v_children.begin()) {
997                 it = v_children.end();
998                 --it;
999                 p_buf = *it;
1000                 return true;
1001         }
1002         --it;
1003         p_buf = *it;
1004         return false;
1005 }
1006
1007
1008 /// Finds forward
1009 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1010 {
1011         if (!cur)
1012                 return 0;
1013         int wrap_answer = -1;
1014         do {
1015                 while (cur && !match(cur, -1, false)) {
1016                         if (cur.pit() < cur.lastpit())
1017                                 cur.forwardPar();
1018                         else {
1019                                 cur.forwardPos();
1020                         }
1021                 }
1022                 for (; cur; cur.forwardPos()) {
1023                         if (match(cur))
1024                                 return findAdvFinalize(cur, match);
1025                 }
1026                 // No match has been found in current buffer
1027                 bool prompt = false;
1028                 if (match.opt.scope == FindAndReplaceOptions::S_BUFFER) {
1029                         prompt = true;
1030                 } else if (match.opt.scope == FindAndReplaceOptions::S_DOCUMENT) {
1031                         prompt = next_document_buffer(match.p_buf);
1032                 } else {
1033                         /* Unimplemented scope */
1034                         LASSERT(false, /**/);
1035                 }
1036                 if (prompt) {
1037                         if (wrap_answer != -1)
1038                                 break;
1039                         wrap_answer = frontend::Alert::prompt(
1040                                 _("Wrap search?"),
1041                                 _("End of document/scope reached while searching forward.\n"
1042                                         "\n"
1043                                         "Continue searching from beginning?"),
1044                                 0, 1, _("&Yes"), _("&No"));
1045                 }
1046                 cur.clear();
1047                 cur.push_back(CursorSlice(match.p_buf->inset()));
1048         } while (wrap_answer != 1);
1049         return 0;
1050 }
1051
1052 /// Find the most backward consecutive match within same paragraph while searching backwards.
1053 void findMostBackwards(DocIterator & cur, MatchStringAdv const & match, int & len) {
1054         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1055         len = findAdvFinalize(cur, match);
1056         if (cur != cur_begin) {
1057                 Inset & inset = cur.inset();
1058                 int old_len;
1059                 DocIterator old_cur;
1060                 DocIterator dit2;
1061                 do {
1062                         old_cur = cur;
1063                         old_len = len;
1064                         cur.backwardPos();
1065                         LYXERR(Debug::FIND, "findMostBackwards(): old_cur=" 
1066                                 << old_cur << ", old_len=" << len << ", cur=" << cur);
1067                         dit2 = cur;
1068                 } while (cur != cur_begin && &cur.inset() == &inset && match(cur)
1069                          && (len = findAdvFinalize(dit2, match)) > old_len);
1070                 cur = old_cur;
1071                 len = old_len;
1072         }
1073         LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1074 }
1075
1076 /// Finds backwards
1077 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1078         if (! cur)
1079                 return 0;
1080         // Backup of original position (for restoring it in case match not found)
1081         DocIterator cur_orig(cur);
1082         // Position beyond which match is not considered
1083         // (set to end of document after wrap-around question)
1084         DocIterator cur_orig2(cur);
1085         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1086 /*      if (match(cur_orig)) */
1087 /*              findAdvFinalize(cur_orig, match); */
1088         int wrap_answer = 0;
1089         bool found_match;
1090         do {
1091                 bool pit_changed = false;
1092                 found_match = false;
1093                 // Search in current par occurs from start to end, 
1094                 // but in next loop match is discarded if pos > original pos
1095                 cur.pos() = 0;
1096                 found_match = match(cur, -1, false);
1097                 LYXERR(Debug::FIND, "findBackAdv0: found_match=" << found_match << ", cur: " << cur);
1098                 while (cur != cur_begin) {
1099                         if (found_match)
1100                                 break;
1101                         if (cur.pit() > 0)
1102                                 --cur.pit();
1103                         else
1104                                 cur.backwardPos();
1105                         pit_changed = true;
1106                         // Search in previous pars occurs from start to end
1107                         cur.pos() = 0;
1108                         found_match = match(cur, -1, false);
1109                         LYXERR(Debug::FIND, "findBackAdv1: found_match=" 
1110                                 << found_match << ", cur: " << cur);
1111                 }
1112                 if (pit_changed)
1113                         cur.pos() = cur.lastpos();
1114                 else
1115                         cur.pos() = cur_orig2.pos();
1116                 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1117                 DocIterator cur_prev_iter;
1118                 if (found_match) {
1119                         while (true) {
1120                                 found_match=match(cur);
1121                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1122                                         << found_match << ", cur: " << cur);
1123                                 if (found_match) {
1124                                         int len;
1125                                         findMostBackwards(cur, match, len);
1126                                         if (&cur.inset() != &cur_orig2.inset()
1127                                             || !(cur.pit() == cur_orig2.pit())
1128                                             || cur.pos() < cur_orig2.pos())
1129                                                 return len;
1130                                 }
1131                                 // Prevent infinite loop at begin of document
1132                                 if (cur == cur_begin || cur == cur_prev_iter)
1133                                         break;
1134                                 cur_prev_iter = cur;
1135                                 cur.backwardPos();
1136                         };
1137                 }
1138                 // No match has been found in current buffer
1139                 bool prompt = false;
1140                 if (match.opt.scope == FindAndReplaceOptions::S_BUFFER) {
1141                         prompt = true;
1142                 } else if (match.opt.scope == FindAndReplaceOptions::S_DOCUMENT) {
1143                         prompt = prev_document_buffer(match.p_buf);
1144                 } else {
1145                         /* Unimplemented scope */
1146                         LASSERT(false, /**/);
1147                 }
1148                 if (prompt) {
1149                         wrap_answer = frontend::Alert::prompt(
1150                                 _("Wrap search?"),
1151                                 _("Beginning of document/scope reached while searching backwards\n"
1152                                   "\n"
1153                                   "Continue searching from end?"),
1154                                 0, 1, _("&Yes"), _("&No"));
1155                 }
1156                 cur = doc_iterator_end(match.p_buf);
1157                 cur.backwardPos();
1158                 LYXERR(Debug::FIND, "findBackAdv5: cur: " << cur);
1159                 cur_orig2 = cur;
1160         } while (wrap_answer == 0);
1161         cur = cur_orig;
1162         return 0;
1163 }
1164
1165
1166 } // anonym namespace
1167
1168
1169 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1170         DocIterator const & cur, int len)
1171 {
1172         if (!opt.ignoreformat)
1173                 return latexifyFromCursor(cur, len);
1174         else
1175                 return stringifyFromCursor(cur, len);
1176 }
1177
1178
1179 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1180         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1181         bool regexp, docstring const & replace, bool keep_case,
1182         SearchScope scope)
1183         : search(search), casesensitive(casesensitive), matchword(matchword),
1184         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1185         regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1186 {
1187 }
1188
1189
1190 /** Checks if the supplied character is lower-case */
1191 static bool isLowerCase(char_type ch) {
1192         return lowercase(ch) == ch;
1193 }
1194
1195
1196 /** Checks if the supplied character is upper-case */
1197 static bool isUpperCase(char_type ch) {
1198         return uppercase(ch) == ch;
1199 }
1200
1201
1202 /** Check if 'len' letters following cursor are all non-lowercase */
1203 static bool allNonLowercase(DocIterator const & cur, int len) {
1204         pos_type end_pos = cur.pos() + len;
1205         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1206                 if (isLowerCase(cur.paragraph().getChar(pos)))
1207                         return false;
1208         return true;
1209 }
1210
1211
1212 /** Check if first letter is upper case and second one is lower case */
1213 static bool firstUppercase(DocIterator const & cur) {
1214         char_type ch1, ch2;
1215         if (cur.pos() >= cur.lastpos() - 1) {
1216                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1217                 return false;
1218         }
1219         ch1 = cur.paragraph().getChar(cur.pos());
1220         ch2 = cur.paragraph().getChar(cur.pos()+1);
1221         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1222         LYXERR(Debug::FIND, "firstUppercase(): "
1223                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1224                << ch2 << "(" << char(ch2) << ")"
1225                << ", result=" << result << ", cur=" << cur);
1226         return result;
1227 }
1228
1229
1230 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1231  **
1232  ** \fixme What to do with possible further paragraphs in replace buffer ?
1233  **/
1234 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1235         ParagraphList::iterator pit = buffer.paragraphs().begin();
1236         pos_type right = pos_type(1);
1237         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1238         right = pit->size() + 1;
1239         pit->changeCase(buffer.params(), right, right, others_case);
1240 }
1241
1242
1243 /// Perform a FindAdv operation.
1244 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1245 {
1246         DocIterator cur = bv->cursor();
1247         int match_len = 0;
1248
1249         if (opt.search.empty()) {
1250                         bv->message(_("Search text is empty!"));
1251                         return false;
1252         }
1253 //      if (! bv->buffer()) {
1254 //              bv->message(_("No open document !"));
1255 //              return false;
1256 //      }
1257
1258         MatchStringAdv matchAdv(bv->buffer(), opt);
1259         try {
1260                 if (opt.forward)
1261                                 match_len = findForwardAdv(cur, matchAdv);
1262                 else
1263                                 match_len = findBackwardsAdv(cur, matchAdv);
1264         } catch (...) {
1265                 // This may only be raised by boost::regex()
1266                 bv->message(_("Invalid regular expression!"));
1267                 return false;
1268         }
1269
1270         if (match_len == 0) {
1271                 bv->message(_("Match not found!"));
1272                 return false;
1273         }
1274
1275         LYXERR(Debug::FIND, "Putting selection at buf=" << matchAdv.p_buf
1276                 << "cur=" << cur << " with len: " << match_len);
1277
1278         theApp()->currentWindow()->selectDocumentBuffer(matchAdv.p_buf);
1279         bv = theApp()->currentWindow()->documentBufferView();
1280
1281         bv->putSelectionAt(cur, match_len, ! opt.forward);
1282         if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING))) {
1283                 bv->message(_("Match found !"));
1284         } else {
1285                 string lyx = to_utf8(opt.replace);
1286                 // FIXME: Seems so stupid to me to rebuild a buffer here,
1287                 // when we already have one (replace_work_area_.buffer())
1288                 Buffer repl_buffer("", false);
1289                 repl_buffer.setUnnamed(true);
1290                 if (repl_buffer.readString(lyx)) {
1291                         if (opt.keep_case && match_len >= 2) {
1292                                 if (cur.inTexted()) {
1293                                         if (firstUppercase(cur))
1294                                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1295                                         else if (allNonLowercase(cur, match_len))
1296                                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1297                                 }
1298                         }
1299                         cap::cutSelection(bv->cursor(), false, false);
1300                         if (! cur.inMathed()) {
1301                                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1302                                 cap::pasteParagraphList(bv->cursor(), repl_buffer.paragraphs(),
1303                                                         repl_buffer.params().documentClassPtr(),
1304                                                         bv->buffer().errorList("Paste"));
1305                         } else {
1306                                 odocstringstream ods;
1307                                 OutputParams runparams(&repl_buffer.params().encoding());
1308                                 runparams.nice = false;
1309                                 runparams.flavor = OutputParams::LATEX;
1310                                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1311                                 runparams.dryrun = true;
1312                                 TexRow texrow;
1313                                 TeXOnePar(repl_buffer, repl_buffer.text(), 
1314                                           repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1315                                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1316                                 docstring repl_latex = ods.str();
1317                                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1318                                 string s;
1319                                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1320                                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1321                                 repl_latex = from_utf8(s);
1322                                 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1323                                 bv->cursor().niceInsert(repl_latex);
1324                         }
1325                         bv->putSelectionAt(cur, repl_buffer.paragraphs().begin()->size(), ! opt.forward);
1326                         bv->message(_("Match found and replaced !"));
1327                 } else
1328                         LASSERT(false, /**/);
1329                 // dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1330         }
1331
1332         return true;
1333 }
1334
1335
1336 void findAdv(BufferView * bv, FuncRequest const & ev)
1337 {
1338         if (!bv || ev.action != LFUN_WORD_FINDADV)
1339                 return;
1340
1341         FindAndReplaceOptions opt;
1342         istringstream iss(to_utf8(ev.argument()));
1343         iss >> opt;
1344         findAdv(bv, opt);
1345 }
1346
1347
1348 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1349 {
1350         os << to_utf8(opt.search) << "\nEOSS\n"
1351            << opt.casesensitive << ' '
1352            << opt.matchword << ' '
1353            << opt.forward << ' '
1354            << opt.expandmacros << ' '
1355            << opt.ignoreformat << ' '
1356            << opt.regexp << ' '
1357            << to_utf8(opt.replace) << "\nEOSS\n"
1358            << opt.keep_case << ' '
1359            << int(opt.scope);
1360
1361         LYXERR(Debug::FIND, "built: " << os.str());
1362
1363         return os;
1364 }
1365
1366 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1367 {
1368         LYXERR(Debug::FIND, "parsing");
1369         string s;
1370         string line;
1371         getline(is, line);
1372         while (line != "EOSS") {
1373                 if (! s.empty())
1374                                 s = s + "\n";
1375                 s = s + line;
1376                 if (is.eof())   // Tolerate malformed request
1377                                 break;
1378                 getline(is, line);
1379         }
1380         LYXERR(Debug::FIND, "searching for: '" << s << "'");
1381         opt.search = from_utf8(s);
1382         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1383         is.get();       // Waste space before replace string
1384         s = "";
1385         getline(is, line);
1386         while (line != "EOSS") {
1387                 if (! s.empty())
1388                                 s = s + "\n";
1389                 s = s + line;
1390                 if (is.eof())   // Tolerate malformed request
1391                                 break;
1392                 getline(is, line);
1393         }
1394         is >> opt.keep_case;
1395         int i;
1396         is >> i;
1397         opt.scope = FindAndReplaceOptions::SearchScope(i);
1398         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1399                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1400         LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1401         opt.replace = from_utf8(s);
1402         return is;
1403 }
1404
1405 } // lyx namespace