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