]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Fix setting Interlingua as GUI language
[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 "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "LyX.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "TexRow.h"
34 #include "Text.h"
35
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
38
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
44
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
52
53 #include "support/regex.h"
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, int>
74 {
75 public:
76         MatchString(docstring const & str, bool cs, bool mw)
77                 : str(str), case_sens(cs), whole_words(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         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
83         {
84                 return par.find(str, case_sens, whole_words, pos, del);
85         }
86
87 private:
88         // search string
89         docstring str;
90         // case sensitive
91         bool case_sens;
92         // match whole words only
93         bool whole_words;
94 };
95
96
97 int findForward(DocIterator & cur, MatchString const & match,
98                 bool find_del = true)
99 {
100         for (; cur; cur.forwardChar())
101                 if (cur.inTexted()) {
102                         int len = match(cur.paragraph(), cur.pos(), find_del);
103                         if (len > 0)
104                                 return len;
105                 }
106         return 0;
107 }
108
109
110 int findBackwards(DocIterator & cur, MatchString const & match,
111                   bool find_del = true)
112 {
113         while (cur) {
114                 cur.backwardChar();
115                 if (cur.inTexted()) {
116                         int len = match(cur.paragraph(), cur.pos(), find_del);
117                         if (len > 0)
118                                 return len;
119                 }
120         }
121         return 0;
122 }
123
124
125 bool searchAllowed(docstring const & str)
126 {
127         if (str.empty()) {
128                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
129                 return false;
130         }
131         return true;
132 }
133
134
135 bool findOne(BufferView * bv, docstring const & searchstr,
136              bool case_sens, bool whole, bool forward, bool find_del = true)
137 {
138         if (!searchAllowed(searchstr))
139                 return false;
140
141         DocIterator cur = forward 
142                 ? bv->cursor().selectionEnd() 
143                 : bv->cursor().selectionBegin();
144
145         MatchString const match(searchstr, case_sens, whole);
146
147         int match_len = forward
148                 ? findForward(cur, match, find_del)
149                 : findBackwards(cur, match, find_del);
150
151         if (match_len > 0)
152                 bv->putSelectionAt(cur, match_len, !forward);
153
154         return match_len > 0;
155 }
156
157
158 int replaceAll(BufferView * bv,
159                docstring const & searchstr, docstring const & replacestr,
160                bool case_sens, bool whole)
161 {
162         Buffer & buf = bv->buffer();
163
164         if (!searchAllowed(searchstr) || buf.isReadonly())
165                 return 0;
166
167         DocIterator cur_orig(bv->cursor());
168
169         MatchString const match(searchstr, case_sens, whole);
170         int num = 0;
171
172         int const rsize = replacestr.size();
173         int const ssize = searchstr.size();
174
175         Cursor cur(*bv);
176         cur.setCursor(doc_iterator_begin(&buf));
177         int match_len = findForward(cur, match, false);
178         while (match_len > 0) {
179                 // Backup current cursor position and font.
180                 pos_type const pos = cur.pos();
181                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
182                 cur.recordUndo();
183                 int striked = ssize -
184                         cur.paragraph().eraseChars(pos, pos + match_len,
185                                                    buf.params().track_changes);
186                 cur.paragraph().insert(pos, replacestr, font,
187                                        Change(buf.params().track_changes
188                                               ? Change::INSERTED
189                                               : Change::UNCHANGED));
190                 for (int i = 0; i < rsize + striked; ++i)
191                         cur.forwardChar();
192                 ++num;
193                 match_len = findForward(cur, match, false);
194         }
195
196         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
197
198         cur_orig.fixIfBroken();
199         bv->setCursor(cur_orig);
200
201         return num;
202 }
203
204
205 // the idea here is that we are going to replace the string that
206 // is selected IF it is the search string. 
207 // if there is a selection, but it is not the search string, then
208 // we basically ignore it. (FIXME We ought to replace only within
209 // the selection.)
210 // if there is no selection, then:
211 //  (i) if some search string has been provided, then we find it.
212 //      (think of how the dialog works when you hit "replace" the
213 //      first time.) 
214 // (ii) if no search string has been provided, then we treat the
215 //      word the cursor is in as the search string. (why? i have no
216 //      idea.) but this only works in text?
217 //
218 // returns the number of replacements made (one, if any) and 
219 // whether anything at all was done.
220 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
221                            docstring const & replacestr, bool case_sens,
222                            bool whole, bool forward, bool findnext)
223 {
224         Cursor & cur = bv->cursor();
225         if (!cur.selection()) {
226                 // no selection, non-empty search string: find it
227                 if (!searchstr.empty()) {
228                         findOne(bv, searchstr, case_sens, whole, forward);
229                         return make_pair(true, 0);
230                 }
231                 // empty search string
232                 if (!cur.inTexted())
233                         // bail in math
234                         return make_pair(false, 0);
235                 // select current word and treat it as the search string.
236                 // This causes a minor bug as undo will restore this selection,
237                 // which the user did not create (#8986).
238                 cur.innerText()->selectWord(cur, WHOLE_WORD);
239                 searchstr = cur.selectionAsString(false);
240         }
241         
242         // if we still don't have a search string, report the error
243         // and abort.
244         if (!searchAllowed(searchstr))
245                 return make_pair(false, 0);
246         
247         bool have_selection = cur.selection();
248         docstring const selected = cur.selectionAsString(false);
249         bool match = 
250                 case_sens
251                 ? searchstr == selected
252                 : compare_no_case(searchstr, selected) == 0;
253
254         // no selection or current selection is not search word:
255         // just find the search word
256         if (!have_selection || !match) {
257                 findOne(bv, searchstr, case_sens, whole, forward);
258                 return make_pair(true, 0);
259         }
260
261         // we're now actually ready to replace. if the buffer is
262         // read-only, we can't, though.
263         if (bv->buffer().isReadonly())
264                 return make_pair(false, 0);
265
266         cap::replaceSelectionWithString(cur, replacestr);
267         if (forward) {
268                 cur.pos() += replacestr.length();
269                 LASSERT(cur.pos() <= cur.lastpos(),
270                         cur.pos() = cur.lastpos());
271         }
272         if (findnext)
273                 findOne(bv, searchstr, case_sens, whole, forward, false);
274
275         return make_pair(true, 1);
276 }
277
278 } // namespace anon
279
280
281 docstring const find2string(docstring const & search,
282                             bool casesensitive, bool matchword, bool forward)
283 {
284         odocstringstream ss;
285         ss << search << '\n'
286            << int(casesensitive) << ' '
287            << int(matchword) << ' '
288            << int(forward);
289         return ss.str();
290 }
291
292
293 docstring const replace2string(docstring const & replace,
294                                docstring const & search,
295                                bool casesensitive, bool matchword,
296                                bool all, bool forward, bool findnext)
297 {
298         odocstringstream ss;
299         ss << replace << '\n'
300            << search << '\n'
301            << int(casesensitive) << ' '
302            << int(matchword) << ' '
303            << int(all) << ' '
304            << int(forward) << ' '
305            << int(findnext);
306         return ss.str();
307 }
308
309
310 bool lyxfind(BufferView * bv, FuncRequest const & ev)
311 {
312         if (!bv || ev.action() != LFUN_WORD_FIND)
313                 return false;
314
315         //lyxerr << "find called, cmd: " << ev << endl;
316
317         // data is of the form
318         // "<search>
319         //  <casesensitive> <matchword> <forward>"
320         docstring search;
321         docstring howto = split(ev.argument(), search, '\n');
322
323         bool casesensitive = parse_bool(howto);
324         bool matchword     = parse_bool(howto);
325         bool forward       = parse_bool(howto);
326
327         return findOne(bv, search, casesensitive, matchword, forward);
328 }
329
330
331 bool lyxreplace(BufferView * bv, 
332                 FuncRequest const & ev, bool has_deleted)
333 {
334         if (!bv || ev.action() != LFUN_WORD_REPLACE)
335                 return false;
336
337         // data is of the form
338         // "<search>
339         //  <replace>
340         //  <casesensitive> <matchword> <all> <forward> <findnext>"
341         docstring search;
342         docstring rplc;
343         docstring howto = split(ev.argument(), rplc, '\n');
344         howto = split(howto, search, '\n');
345
346         bool casesensitive = parse_bool(howto);
347         bool matchword     = parse_bool(howto);
348         bool all           = parse_bool(howto);
349         bool forward       = parse_bool(howto);
350         bool findnext      = howto.empty() ? true : parse_bool(howto);
351
352         int replace_count = 0;
353         bool update = false;
354
355         if (!has_deleted) {
356                 if (all) {
357                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
358                         update = replace_count > 0;
359                 } else {
360                         pair<bool, int> rv =
361                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
362                         update = rv.first;
363                         replace_count = rv.second;
364                 }
365
366                 Buffer const & buf = bv->buffer();
367                 if (!update) {
368                         // emit message signal.
369                         buf.message(_("String not found."));
370                 } else {
371                         if (replace_count == 0) {
372                                 buf.message(_("String found."));
373                         } else if (replace_count == 1) {
374                                 buf.message(_("String has been replaced."));
375                         } else {
376                                 docstring const str = 
377                                         bformat(_("%1$d strings have been replaced."), replace_count);
378                                 buf.message(str);
379                         }
380                 }
381         } else if (findnext) {
382                 // if we have deleted characters, we do not replace at all, but
383                 // rather search for the next occurence
384                 if (findOne(bv, search, casesensitive, matchword, forward))
385                         update = true;
386                 else
387                         bv->message(_("String not found."));
388         }
389         return update;
390 }
391
392
393 bool findNextChange(DocIterator & cur)
394 {
395         for (; cur; cur.forwardPos())
396                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
397                         return true;
398         return false;
399 }
400
401
402 bool findPreviousChange(DocIterator & cur)
403 {
404         for (cur.backwardPos(); cur; cur.backwardPos()) {
405                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
406                         return true;
407         }
408         return false;
409 }
410
411
412 bool selectChange(Cursor & cur, bool forward)
413 {
414         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
415                 return false;
416         Change ch = cur.paragraph().lookupChange(cur.pos());
417
418         CursorSlice tip1 = cur.top();
419         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
420                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
421                 if (!ch2.isSimilarTo(ch))
422                         break;
423         }
424         CursorSlice tip2 = cur.top();
425         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
426                 tip2.backwardPos();
427                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
428                 if (!ch2.isSimilarTo(ch)) {
429                         // take a step forward to correctly set the selection
430                         tip2.forwardPos();
431                         break;
432                 }
433         }
434         if (forward)
435                 swap(tip1, tip2);
436         cur.top() = tip1;
437         cur.bv().mouseSetCursor(cur, false);
438         cur.top() = tip2;
439         cur.bv().mouseSetCursor(cur, true);
440         return true;
441 }
442
443
444 namespace {
445
446
447 bool findChange(BufferView * bv, bool forward)
448 {
449         Cursor cur(*bv);
450         cur.setCursor(forward ? bv->cursor().selectionEnd()
451                       : bv->cursor().selectionBegin());
452         forward ? findNextChange(cur) : findPreviousChange(cur);
453         return selectChange(cur, forward);
454 }
455
456 }
457
458 bool findNextChange(BufferView * bv)
459 {
460         return findChange(bv, true);
461 }
462
463
464 bool findPreviousChange(BufferView * bv)
465 {
466         return findChange(bv, false);
467 }
468
469
470
471 namespace {
472
473 typedef vector<pair<string, string> > Escapes;
474
475 /// A map of symbols and their escaped equivalent needed within a regex.
476 /// @note Beware of order
477 Escapes const & get_regexp_escapes()
478 {
479         typedef std::pair<std::string, std::string> P;
480
481         static Escapes escape_map;
482         if (escape_map.empty()) {
483                 escape_map.push_back(P("$", "_x_$"));
484                 escape_map.push_back(P("{", "_x_{"));
485                 escape_map.push_back(P("}", "_x_}"));
486                 escape_map.push_back(P("[", "_x_["));
487                 escape_map.push_back(P("]", "_x_]"));
488                 escape_map.push_back(P("(", "_x_("));
489                 escape_map.push_back(P(")", "_x_)"));
490                 escape_map.push_back(P("+", "_x_+"));
491                 escape_map.push_back(P("*", "_x_*"));
492                 escape_map.push_back(P(".", "_x_."));
493                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
494                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
495                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
496                 escape_map.push_back(P("_x_", "\\"));
497         }
498         return escape_map;
499 }
500
501 /// A map of lyx escaped strings and their unescaped equivalent.
502 Escapes const & get_lyx_unescapes()
503 {
504         typedef std::pair<std::string, std::string> P;
505
506         static Escapes escape_map;
507         if (escape_map.empty()) {
508                 escape_map.push_back(P("\\%", "%"));
509                 escape_map.push_back(P("\\mathcircumflex ", "^"));
510                 escape_map.push_back(P("\\mathcircumflex", "^"));
511                 escape_map.push_back(P("\\backslash ", "\\"));
512                 escape_map.push_back(P("\\backslash", "\\"));
513                 escape_map.push_back(P("\\\\{", "_x_<"));
514                 escape_map.push_back(P("\\\\}", "_x_>"));
515                 escape_map.push_back(P("\\sim ", "~"));
516                 escape_map.push_back(P("\\sim", "~"));
517         }
518         return escape_map;
519 }
520
521 /// A map of escapes turning a regexp matching text to one matching latex.
522 Escapes const & get_regexp_latex_escapes()
523 {
524         typedef std::pair<std::string, std::string> P;
525
526         static Escapes escape_map;
527         if (escape_map.empty()) {
528                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
529                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
530                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
531                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
532                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
533                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
534                 escape_map.push_back(P("%", "\\\\\\%"));
535         }
536         return escape_map;
537 }
538
539 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
540  ** the found occurrence were escaped.
541  **/
542 string apply_escapes(string s, Escapes const & escape_map)
543 {
544         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
545         Escapes::const_iterator it;
546         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
547 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
548                 unsigned int pos = 0;
549                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
550                         s.replace(pos, it->first.length(), it->second);
551                         LYXERR(Debug::FIND, "After escape: " << s);
552                         pos += it->second.length();
553 //                      LYXERR(Debug::FIND, "pos: " << pos);
554                 }
555         }
556         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
557         return s;
558 }
559
560
561 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
562 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
563 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
564 string escape_for_regex(string s, bool match_latex)
565 {
566         size_t pos = 0;
567         while (pos < s.size()) {
568                 size_t new_pos = s.find("\\regexp{", pos);
569                 if (new_pos == string::npos)
570                         new_pos = s.size();
571                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
572                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
573                 LYXERR(Debug::FIND, "t [lyx]: " << t);
574                 t = apply_escapes(t, get_regexp_escapes());
575                 LYXERR(Debug::FIND, "t [rxp]: " << t);
576                 s.replace(pos, new_pos - pos, t);
577                 new_pos = pos + t.size();
578                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
579                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
580                 if (new_pos == s.size())
581                         break;
582                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
583                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
584                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
585                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
586                 LYXERR(Debug::FIND, "t in regexp      : " << t);
587                 t = apply_escapes(t, get_lyx_unescapes());
588                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
589                 if (match_latex) {
590                         t = apply_escapes(t, get_regexp_latex_escapes());
591                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
592                 }
593                 if (end_pos == s.size()) {
594                         s.replace(new_pos, end_pos - new_pos, t);
595                         pos = s.size();
596                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
597                         break;
598                 }
599                 s.replace(new_pos, end_pos + 13 - new_pos, t);
600                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
601                 pos = new_pos + t.size();
602                 LYXERR(Debug::FIND, "pos: " << pos);
603         }
604         return s;
605 }
606
607
608 /// Wrapper for lyx::regex_replace with simpler interface
609 bool regex_replace(string const & s, string & t, string const & searchstr,
610                    string const & replacestr)
611 {
612         lyx::regex e(searchstr);
613         ostringstream oss;
614         ostream_iterator<char, char> it(oss);
615         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
616         // tolerate t and s be references to the same variable
617         bool rv = (s != oss.str());
618         t = oss.str();
619         return rv;
620 }
621
622
623 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
624  **
625  ** Verify that closed braces exactly match open braces. This avoids that, for example,
626  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
627  **
628  ** @param unmatched
629  ** Number of open braces that must remain open at the end for the verification to succeed.
630  **/
631 bool braces_match(string::const_iterator const & beg,
632                   string::const_iterator const & end,
633                   int unmatched = 0)
634 {
635         int open_pars = 0;
636         string::const_iterator it = beg;
637         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
638         for (; it != end; ++it) {
639                 // Skip escaped braces in the count
640                 if (*it == '\\') {
641                         ++it;
642                         if (it == end)
643                                 break;
644                 } else if (*it == '{') {
645                         ++open_pars;
646                 } else if (*it == '}') {
647                         if (open_pars == 0) {
648                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
649                                 return false;
650                         } else
651                                 --open_pars;
652                 }
653         }
654         if (open_pars != unmatched) {
655                 LYXERR(Debug::FIND, "Found " << open_pars 
656                        << " instead of " << unmatched 
657                        << " unmatched open braces at the end of count");
658                 return false;
659         }
660         LYXERR(Debug::FIND, "Braces match as expected");
661         return true;
662 }
663
664
665 /** The class performing a match between a position in the document and the FindAdvOptions.
666  **/
667 class MatchStringAdv {
668 public:
669         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
670
671         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
672          ** constructor as opt.search, under the opt.* options settings.
673          **
674          ** @param at_begin
675          **     If set, then match is searched only against beginning of text starting at cur.
676          **     If unset, then match is searched anywhere in text starting at cur.
677          **
678          ** @return
679          ** The length of the matching text, or zero if no match was found.
680          **/
681         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
682
683 public:
684         /// buffer
685         lyx::Buffer * p_buf;
686         /// first buffer on which search was started
687         lyx::Buffer * const p_first_buf;
688         /// options
689         FindAndReplaceOptions const & opt;
690
691 private:
692         /// Auxiliary find method (does not account for opt.matchword)
693         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
694
695         /** Normalize a stringified or latexified LyX paragraph.
696          **
697          ** Normalize means:
698          ** <ul>
699          **   <li>if search is not casesensitive, then lowercase the string;
700          **   <li>remove any newline at begin or end of the string;
701          **   <li>replace any newline in the middle of the string with a simple space;
702          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
703          ** </ul>
704          **
705          ** @todo Normalization should also expand macros, if the corresponding
706          ** search option was checked.
707          **/
708         string normalize(docstring const & s, bool hack_braces) const;
709         // normalized string to search
710         string par_as_string;
711         // regular expression to use for searching
712         lyx::regex regexp;
713         // same as regexp, but prefixed with a ".*"
714         lyx::regex regexp2;
715         // leading format material as string
716         string lead_as_string;
717         // par_as_string after removal of lead_as_string
718         string par_as_string_nolead;
719         // unmatched open braces in the search string/regexp
720         int open_braces;
721         // number of (.*?) subexpressions added at end of search regexp for closing
722         // environments, math mode, styles, etc...
723         int close_wildcards;
724         // Are we searching with regular expressions ?
725         bool use_regexp;
726 };
727
728
729 static docstring buffer_to_latex(Buffer & buffer) 
730 {
731         OutputParams runparams(&buffer.params().encoding());
732         TexRow texrow;
733         odocstringstream ods;
734         otexstream os(ods, texrow);
735         runparams.nice = true;
736         runparams.flavor = OutputParams::LATEX;
737         runparams.linelen = 80; //lyxrc.plaintext_linelen;
738         // No side effect of file copying and image conversion
739         runparams.dryrun = true;
740         pit_type const endpit = buffer.paragraphs().size();
741         for (pit_type pit = 0; pit != endpit; ++pit) {
742                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
743                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
744         }
745         return ods.str();
746 }
747
748
749 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
750 {
751         docstring str;
752         if (!opt.ignoreformat) {
753                 str = buffer_to_latex(buffer);
754         } else {
755                 OutputParams runparams(&buffer.params().encoding());
756                 runparams.nice = true;
757                 runparams.flavor = OutputParams::LATEX;
758                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
759                 runparams.dryrun = true;
760                 runparams.for_search = true;
761                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
762                         Paragraph const & par = buffer.paragraphs().at(pit);
763                         LYXERR(Debug::FIND, "Adding to search string: '"
764                                << par.asString(pos_type(0), par.size(),
765                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
766                                                &runparams)
767                                << "'");
768                         str += par.asString(pos_type(0), par.size(),
769                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
770                                             &runparams);
771                 }
772         }
773         return str;
774 }
775
776
777 /// Return separation pos between the leading material and the rest
778 static size_t identifyLeading(string const & s)
779 {
780         string t = s;
781         // @TODO Support \item[text]
782         while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
783                || regex_replace(t, t, "^\\$", "")
784                || regex_replace(t, t, "^\\\\\\[ ", "")
785                || regex_replace(t, t, "^\\\\item ", "")
786                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
787                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
788         return s.find(t);
789 }
790
791
792 // Remove trailing closure of math, macros and environments, so to catch parts of them.
793 static int identifyClosing(string & t)
794 {
795         int open_braces = 0;
796         do {
797                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
798                 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
799                         continue;
800                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
801                         continue;
802                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
803                         continue;
804                 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
805                         ++open_braces;
806                         continue;
807                 }
808                 break;
809         } while (true);
810         return open_braces;
811 }
812
813
814 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
815         : p_buf(&buf), p_first_buf(&buf), opt(opt)
816 {
817         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
818         docstring const & ds = stringifySearchBuffer(find_buf, opt);
819         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
820         // When using regexp, braces are hacked already by escape_for_regex()
821         par_as_string = normalize(ds, !use_regexp);
822         open_braces = 0;
823         close_wildcards = 0;
824
825         size_t lead_size = 0;
826         if (opt.ignoreformat) {
827                 if (!use_regexp) {
828                         // if par_as_string_nolead were emty, 
829                         // the following call to findAux will always *find* the string
830                         // in the checked data, and thus always using the slow
831                         // examining of the current text part.
832                         par_as_string_nolead = par_as_string;
833                 }
834         }
835         else {
836                 lead_size = identifyLeading(par_as_string);
837                 lead_as_string = par_as_string.substr(0, lead_size);
838                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
839         }
840
841         if (!use_regexp) {
842                 open_braces = identifyClosing(par_as_string);
843                 identifyClosing(par_as_string_nolead);
844                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
845                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
846         } else {
847                 string lead_as_regexp;
848                 if (lead_size > 0) {
849                         // @todo No need to search for \regexp{} insets in leading material
850                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
851                         par_as_string = par_as_string_nolead;
852                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
853                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
854                 }
855                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
856                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
857                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
858                 if (
859                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
860                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
861                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
862                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
863                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
864                         || regex_replace(par_as_string, par_as_string,
865                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
866                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
867                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
868                         ) {
869                         ++close_wildcards;
870                 }
871                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
872                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
873                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
874                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
875                 // If entered regexp must match at begin of searched string buffer
876                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
877                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
878                 regexp = lyx::regex(regexp_str);
879
880                 // If entered regexp may match wherever in searched string buffer
881                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
882                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
883                 regexp2 = lyx::regex(regexp2_str);
884         }
885 }
886
887
888 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
889 {
890         if (at_begin &&
891                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
892                 return 0;
893         docstring docstr = stringifyFromForSearch(opt, cur, len);
894         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
895         string str = normalize(docstr, true);
896         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
897         if (! use_regexp) {
898                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
899                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
900                 if (at_begin) {
901                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
902                         if (str.substr(0, par_as_string.size()) == par_as_string)
903                                 return par_as_string.size();
904                 } else {
905                         size_t pos = str.find(par_as_string_nolead);
906                         if (pos != string::npos)
907                                 return par_as_string.size();
908                 }
909         } else {
910                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
911                 // Try all possible regexp matches, 
912                 //until one that verifies the braces match test is found
913                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
914                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
915                 sregex_iterator re_it_end;
916                 for (; re_it != re_it_end; ++re_it) {
917                         match_results<string::const_iterator> const & m = *re_it;
918                         // Check braces on the segment that matched the entire regexp expression,
919                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
920                         if (!braces_match(m[0].first, m[0].second, open_braces))
921                                 return 0;
922                         // Check braces on segments that matched all (.*?) subexpressions,
923                         // except the last "padding" one inserted by lyx.
924                         for (size_t i = 1; i < m.size() - 1; ++i)
925                                 if (!braces_match(m[i].first, m[i].second))
926                                         return false;
927                         // Exclude from the returned match length any length 
928                         // due to close wildcards added at end of regexp
929                         if (close_wildcards == 0)
930                                 return m[0].second - m[0].first;
931                         else
932                                 return m[m.size() - close_wildcards].first - m[0].first;
933                 }
934         }
935         return 0;
936 }
937
938
939 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
940 {
941         int res = findAux(cur, len, at_begin);
942         LYXERR(Debug::FIND,
943                "res=" << res << ", at_begin=" << at_begin
944                << ", matchword=" << opt.matchword
945                << ", inTexted=" << cur.inTexted());
946         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
947                 return res;
948         Paragraph const & par = cur.paragraph();
949         bool ws_left = (cur.pos() > 0)
950                 ? par.isWordSeparator(cur.pos() - 1)
951                 : true;
952         bool ws_right = (cur.pos() + res < par.size())
953                 ? par.isWordSeparator(cur.pos() + res)
954                 : true;
955         LYXERR(Debug::FIND,
956                "cur.pos()=" << cur.pos() << ", res=" << res
957                << ", separ: " << ws_left << ", " << ws_right
958                << endl);
959         if (ws_left && ws_right)
960                 return res;
961         return 0;
962 }
963
964
965 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
966 {
967         string t;
968         if (! opt.casesensitive)
969                 t = lyx::to_utf8(lowercase(s));
970         else
971                 t = lyx::to_utf8(s);
972         // Remove \n at begin
973         while (!t.empty() && t[0] == '\n')
974                 t = t.substr(1);
975         // Remove \n at end
976         while (!t.empty() && t[t.size() - 1] == '\n')
977                 t = t.substr(0, t.size() - 1);
978         size_t pos;
979         // Replace all other \n with spaces
980         while ((pos = t.find("\n")) != string::npos)
981                 t.replace(pos, 1, " ");
982         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
983         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
984         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
985                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
986
987         // FIXME - check what preceeds the brace
988         if (hack_braces) {
989                 if (opt.ignoreformat)
990                         while (regex_replace(t, t, "\\{", "_x_<")
991                                || regex_replace(t, t, "\\}", "_x_>"))
992                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
993                 else
994                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
995                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
996                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
997         }
998
999         return t;
1000 }
1001
1002
1003 docstring stringifyFromCursor(DocIterator const & cur, int len)
1004 {
1005         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1006         if (cur.inTexted()) {
1007                 Paragraph const & par = cur.paragraph();
1008                 // TODO what about searching beyond/across paragraph breaks ?
1009                 // TODO Try adding a AS_STR_INSERTS as last arg
1010                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1011                         int(par.size()) : cur.pos() + len;
1012                 OutputParams runparams(&cur.buffer()->params().encoding());
1013                 odocstringstream os;
1014                 runparams.nice = true;
1015                 runparams.flavor = OutputParams::LATEX;
1016                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1017                 // No side effect of file copying and image conversion
1018                 runparams.dryrun = true;
1019                 LYXERR(Debug::FIND, "Stringifying with cur: "
1020                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1021                 return par.asString(cur.pos(), end,
1022                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1023                         &runparams);
1024         } else if (cur.inMathed()) {
1025                 docstring s;
1026                 CursorSlice cs = cur.top();
1027                 MathData md = cs.cell();
1028                 MathData::const_iterator it_end =
1029                         (( len == -1 || cs.pos() + len > int(md.size()))
1030                          ? md.end()
1031                          : md.begin() + cs.pos() + len );
1032                 for (MathData::const_iterator it = md.begin() + cs.pos();
1033                      it != it_end; ++it)
1034                         s = s + asString(*it);
1035                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1036                 return s;
1037         }
1038         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1039         return docstring();
1040 }
1041
1042
1043 /** Computes the LaTeX export of buf starting from cur and ending len positions
1044  * after cur, if len is positive, or at the paragraph or innermost inset end
1045  * if len is -1.
1046  */
1047 docstring latexifyFromCursor(DocIterator const & cur, int len)
1048 {
1049         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1050         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1051                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1052         Buffer const & buf = *cur.buffer();
1053         LBUFERR(buf.params().isLatex());
1054
1055         TexRow texrow;
1056         odocstringstream ods;
1057         otexstream os(ods, texrow);
1058         OutputParams runparams(&buf.params().encoding());
1059         runparams.nice = false;
1060         runparams.flavor = OutputParams::LATEX;
1061         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1062         // No side effect of file copying and image conversion
1063         runparams.dryrun = true;
1064
1065         if (cur.inTexted()) {
1066                 // @TODO what about searching beyond/across paragraph breaks ?
1067                 pos_type endpos = cur.paragraph().size();
1068                 if (len != -1 && endpos > cur.pos() + len)
1069                         endpos = cur.pos() + len;
1070                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1071                           string(), cur.pos(), endpos);
1072                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1073         } else if (cur.inMathed()) {
1074                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1075                 for (int s = cur.depth() - 1; s >= 0; --s) {
1076                         CursorSlice const & cs = cur[s];
1077                         if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1078                                 WriteStream ws(ods);
1079                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1080                                 break;
1081                         }
1082                 }
1083
1084                 CursorSlice const & cs = cur.top();
1085                 MathData md = cs.cell();
1086                 MathData::const_iterator it_end =
1087                         ((len == -1 || cs.pos() + len > int(md.size()))
1088                          ? md.end()
1089                          : md.begin() + cs.pos() + len);
1090                 for (MathData::const_iterator it = md.begin() + cs.pos();
1091                      it != it_end; ++it)
1092                         ods << asString(*it);
1093
1094                 // Retrieve the math environment type, and add '$' or '$]'
1095                 // or others (\end{equation}) accordingly
1096                 for (int s = cur.depth() - 1; s >= 0; --s) {
1097                         CursorSlice const & cs = cur[s];
1098                         InsetMath * inset = cs.asInsetMath();
1099                         if (inset && inset->asHullInset()) {
1100                                 WriteStream ws(ods);
1101                                 inset->asHullInset()->footer_write(ws);
1102                                 break;
1103                         }
1104                 }
1105                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1106         } else {
1107                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1108         }
1109         return ods.str();
1110 }
1111
1112
1113 /** Finalize an advanced find operation, advancing the cursor to the innermost
1114  ** position that matches, plus computing the length of the matching text to
1115  ** be selected
1116  **/
1117 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1118 {
1119         // Search the foremost position that matches (avoids find of entire math
1120         // inset when match at start of it)
1121         size_t d;
1122         DocIterator old_cur(cur.buffer());
1123         do {
1124                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1125                 d = cur.depth();
1126                 old_cur = cur;
1127                 cur.forwardPos();
1128         } while (cur && cur.depth() > d && match(cur) > 0);
1129         cur = old_cur;
1130         LASSERT(match(cur) > 0, return 0);
1131         LYXERR(Debug::FIND, "Ok");
1132
1133         // Compute the match length
1134         int len = 1;
1135         if (cur.pos() + len > cur.lastpos())
1136                 return 0;
1137         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1138         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1139                 ++len;
1140                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1141         }
1142         // Length of matched text (different from len param)
1143         int old_len = match(cur, len);
1144         int new_len;
1145         // Greedy behaviour while matching regexps
1146         while ((new_len = match(cur, len + 1)) > old_len) {
1147                 ++len;
1148                 old_len = new_len;
1149                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1150         }
1151         return len;
1152 }
1153
1154
1155 /// Finds forward
1156 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1157 {
1158         if (!cur)
1159                 return 0;
1160         while (!theApp()->longOperationCancelled() && cur) {
1161                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1162                 int match_len = match(cur, -1, false);
1163                 LYXERR(Debug::FIND, "match_len: " << match_len);
1164                 if (match_len) {
1165                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1166                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1167                                 int match_len = match(cur);
1168                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1169                                 if (match_len) {
1170                                         // Sometimes in finalize we understand it wasn't a match
1171                                         // and we need to continue the outest loop
1172                                         int len = findAdvFinalize(cur, match);
1173                                         if (len > 0)
1174                                                 return len;
1175                                 }
1176                         }
1177                         if (!cur)
1178                                 return 0;
1179                 }
1180                 if (cur.pit() < cur.lastpit()) {
1181                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1182                         cur.forwardPar();
1183                 } else {
1184                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1185                         cur.pos() = cur.lastpos();
1186                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1187                         cur.forwardPos();
1188                 }
1189         }
1190         return 0;
1191 }
1192
1193
1194 /// Find the most backward consecutive match within same paragraph while searching backwards.
1195 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1196 {
1197         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1198         DocIterator tmp_cur = cur;
1199         int len = findAdvFinalize(tmp_cur, match);
1200         Inset & inset = cur.inset();
1201         for (; cur != cur_begin; cur.backwardPos()) {
1202                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1203                 DocIterator new_cur = cur;
1204                 new_cur.backwardPos();
1205                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1206                         break;
1207                 int new_len = findAdvFinalize(new_cur, match);
1208                 if (new_len == len)
1209                         break;
1210                 len = new_len;
1211         }
1212         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1213         return len;
1214 }
1215
1216
1217 /// Finds backwards
1218 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1219 {
1220         if (! cur)
1221                 return 0;
1222         // Backup of original position
1223         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1224         if (cur == cur_begin)
1225                 return 0;
1226         cur.backwardPos();
1227         DocIterator cur_orig(cur);
1228         bool found_match;
1229         bool pit_changed = false;
1230         found_match = false;
1231         do {
1232                 cur.pos() = 0;
1233                 found_match = match(cur, -1, false);
1234
1235                 if (found_match) {
1236                         if (pit_changed)
1237                                 cur.pos() = cur.lastpos();
1238                         else
1239                                 cur.pos() = cur_orig.pos();
1240                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1241                         DocIterator cur_prev_iter;
1242                         do {
1243                                 found_match = match(cur);
1244                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1245                                        << found_match << ", cur: " << cur);
1246                                 if (found_match)
1247                                         return findMostBackwards(cur, match);
1248
1249                                 // Stop if begin of document reached
1250                                 if (cur == cur_begin)
1251                                         break;
1252                                 cur_prev_iter = cur;
1253                                 cur.backwardPos();
1254                         } while (true);
1255                 }
1256                 if (cur == cur_begin)
1257                         break;
1258                 if (cur.pit() > 0)
1259                         --cur.pit();
1260                 else
1261                         cur.backwardPos();
1262                 pit_changed = true;
1263         } while (!theApp()->longOperationCancelled());
1264         return 0;
1265 }
1266
1267
1268 } // anonym namespace
1269
1270
1271 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1272                                  DocIterator const & cur, int len)
1273 {
1274         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1275                 return docstring());
1276         if (!opt.ignoreformat)
1277                 return latexifyFromCursor(cur, len);
1278         else
1279                 return stringifyFromCursor(cur, len);
1280 }
1281
1282
1283 FindAndReplaceOptions::FindAndReplaceOptions(
1284         docstring const & find_buf_name, bool casesensitive,
1285         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1286         docstring const & repl_buf_name, bool keep_case,
1287         SearchScope scope, SearchRestriction restr)
1288         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1289           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1290           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1291 {
1292 }
1293
1294
1295 namespace {
1296
1297
1298 /** Check if 'len' letters following cursor are all non-lowercase */
1299 static bool allNonLowercase(Cursor const & cur, int len)
1300 {
1301         pos_type beg_pos = cur.selectionBegin().pos();
1302         pos_type end_pos = cur.selectionBegin().pos() + len;
1303         if (len > cur.lastpos() + 1 - beg_pos) {
1304                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1305                 len = cur.lastpos() + 1 - beg_pos;
1306         }
1307         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1308                 if (isLowerCase(cur.paragraph().getChar(pos)))
1309                         return false;
1310         return true;
1311 }
1312
1313
1314 /** Check if first letter is upper case and second one is lower case */
1315 static bool firstUppercase(Cursor const & cur)
1316 {
1317         char_type ch1, ch2;
1318         pos_type pos = cur.selectionBegin().pos();
1319         if (pos >= cur.lastpos() - 1) {
1320                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1321                 return false;
1322         }
1323         ch1 = cur.paragraph().getChar(pos);
1324         ch2 = cur.paragraph().getChar(pos + 1);
1325         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1326         LYXERR(Debug::FIND, "firstUppercase(): "
1327                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1328                << ch2 << "(" << char(ch2) << ")"
1329                << ", result=" << result << ", cur=" << cur);
1330         return result;
1331 }
1332
1333
1334 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1335  **
1336  ** \fixme What to do with possible further paragraphs in replace buffer ?
1337  **/
1338 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1339 {
1340         ParagraphList::iterator pit = buffer.paragraphs().begin();
1341         LASSERT(pit->size() >= 1, /**/);
1342         pos_type right = pos_type(1);
1343         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1344         right = pit->size();
1345         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1346 }
1347
1348 } // anon namespace
1349
1350 ///
1351 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1352 {
1353         Cursor & cur = bv->cursor();
1354         if (opt.repl_buf_name == docstring())
1355                 return;
1356
1357         DocIterator sel_beg = cur.selectionBegin();
1358         DocIterator sel_end = cur.selectionEnd();
1359         if (&sel_beg.inset() != &sel_end.inset()
1360             || sel_beg.pit() != sel_end.pit()
1361             || sel_beg.idx() != sel_end.idx())
1362                 return;
1363         int sel_len = sel_end.pos() - sel_beg.pos();
1364         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1365                << ", sel_len: " << sel_len << endl);
1366         if (sel_len == 0)
1367                 return;
1368         LASSERT(sel_len > 0, return);
1369
1370         if (!matchAdv(sel_beg, sel_len))
1371                 return;
1372
1373         // Build a copy of the replace buffer, adapted to the KeepCase option
1374         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1375         ostringstream oss;
1376         repl_buffer_orig.write(oss);
1377         string lyx = oss.str();
1378         Buffer repl_buffer("", false);
1379         repl_buffer.setUnnamed(true);
1380         LASSERT(repl_buffer.readString(lyx), return);
1381         if (opt.keep_case && sel_len >= 2) {
1382                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1383                 if (cur.inTexted()) {
1384                         if (firstUppercase(cur))
1385                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1386                         else if (allNonLowercase(cur, sel_len))
1387                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1388                 }
1389         }
1390         cap::cutSelection(cur, false, false);
1391         if (cur.inTexted()) {
1392                 repl_buffer.changeLanguage(
1393                         repl_buffer.language(),
1394                         cur.getFont().language());
1395                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1396                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1397                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1398                                         repl_buffer.params().documentClassPtr(),
1399                                         bv->buffer().errorList("Paste"));
1400                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1401                 sel_len = repl_buffer.paragraphs().begin()->size();
1402         } else if (cur.inMathed()) {
1403                 TexRow texrow;
1404                 odocstringstream ods;
1405                 otexstream os(ods, texrow);
1406                 OutputParams runparams(&repl_buffer.params().encoding());
1407                 runparams.nice = false;
1408                 runparams.flavor = OutputParams::LATEX;
1409                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1410                 runparams.dryrun = true;
1411                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1412                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1413                 docstring repl_latex = ods.str();
1414                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1415                 string s;
1416                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1417                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1418                 repl_latex = from_utf8(s);
1419                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1420                 MathData ar(cur.buffer());
1421                 asArray(repl_latex, ar, Parse::NORMAL);
1422                 cur.insert(ar);
1423                 sel_len = ar.size();
1424                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1425         }
1426         if (cur.pos() >= sel_len)
1427                 cur.pos() -= sel_len;
1428         else
1429                 cur.pos() = 0;
1430         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1431         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1432         bv->processUpdateFlags(Update::Force);
1433         bv->buffer().updatePreviews();
1434 }
1435
1436
1437 /// Perform a FindAdv operation.
1438 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1439 {
1440         DocIterator cur;
1441         int match_len = 0;
1442
1443         try {
1444                 MatchStringAdv matchAdv(bv->buffer(), opt);
1445                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1446                 if (length > 0)
1447                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1448                 findAdvReplace(bv, opt, matchAdv);
1449                 cur = bv->cursor();
1450                 if (opt.forward)
1451                         match_len = findForwardAdv(cur, matchAdv);
1452                 else
1453                         match_len = findBackwardsAdv(cur, matchAdv);
1454         } catch (...) {
1455                 // This may only be raised by lyx::regex()
1456                 bv->message(_("Invalid regular expression!"));
1457                 return false;
1458         }
1459
1460         if (match_len == 0) {
1461                 bv->message(_("Match not found!"));
1462                 return false;
1463         }
1464
1465         bv->message(_("Match found!"));
1466
1467         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1468         bv->putSelectionAt(cur, match_len, !opt.forward);
1469
1470         return true;
1471 }
1472
1473
1474 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1475 {
1476         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1477            << opt.casesensitive << ' '
1478            << opt.matchword << ' '
1479            << opt.forward << ' '
1480            << opt.expandmacros << ' '
1481            << opt.ignoreformat << ' '
1482            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1483            << opt.keep_case << ' '
1484            << int(opt.scope) << ' '
1485            << int(opt.restr);
1486
1487         LYXERR(Debug::FIND, "built: " << os.str());
1488
1489         return os;
1490 }
1491
1492
1493 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1494 {
1495         LYXERR(Debug::FIND, "parsing");
1496         string s;
1497         string line;
1498         getline(is, line);
1499         while (line != "EOSS") {
1500                 if (! s.empty())
1501                         s = s + "\n";
1502                 s = s + line;
1503                 if (is.eof())   // Tolerate malformed request
1504                         break;
1505                 getline(is, line);
1506         }
1507         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1508         opt.find_buf_name = from_utf8(s);
1509         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1510         is.get();       // Waste space before replace string
1511         s = "";
1512         getline(is, line);
1513         while (line != "EOSS") {
1514                 if (! s.empty())
1515                         s = s + "\n";
1516                 s = s + line;
1517                 if (is.eof())   // Tolerate malformed request
1518                         break;
1519                 getline(is, line);
1520         }
1521         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1522         opt.repl_buf_name = from_utf8(s);
1523         is >> opt.keep_case;
1524         int i;
1525         is >> i;
1526         opt.scope = FindAndReplaceOptions::SearchScope(i);
1527         is >> i;
1528         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1529
1530         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1531                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1532                << opt.scope << ' ' << opt.restr);
1533         return is;
1534 }
1535
1536 } // lyx namespace