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