]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
Fix #10778 (issue with CJK and language nesting)
[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(BufferView * bv, Cursor & cur, bool const check_wrap)
421 {
422         for (; cur; cur.forwardPos())
423                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
424                         return true;
425
426         if (check_wrap) {
427                 DocIterator cur_orig(bv->cursor());
428                 docstring q = _("End of file reached while searching forward.\n"
429                           "Continue searching from the beginning?");
430                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
431                         q, 0, 1, _("&Yes"), _("&No"));
432                 if (wrap_answer == 0) {
433                         bv->cursor().clear();
434                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
435                         bv->clearSelection();
436                         cur.setCursor(bv->cursor().selectionBegin());
437                         if (findNextChange(bv, cur, false))
438                                 return true;
439                 }
440                 bv->cursor().setCursor(cur_orig);
441         }
442
443         return false;
444 }
445
446
447 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
448 {
449         for (cur.backwardPos(); cur; cur.backwardPos()) {
450                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
451                         return true;
452         }
453
454         if (check_wrap) {
455                 DocIterator cur_orig(bv->cursor());
456                 docstring q = _("Beginning of file reached while searching backward.\n"
457                           "Continue searching from the end?");
458                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
459                         q, 0, 1, _("&Yes"), _("&No"));
460                 if (wrap_answer == 0) {
461                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
462                         bv->cursor().backwardPos();
463                         bv->clearSelection();
464                         cur.setCursor(bv->cursor().selectionBegin());
465                         if (findPreviousChange(bv, cur, false))
466                                 return true;
467                 }
468                 bv->cursor().setCursor(cur_orig);
469         }
470
471         return false;
472 }
473
474
475 bool selectChange(Cursor & cur, bool forward)
476 {
477         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
478                 return false;
479         Change ch = cur.paragraph().lookupChange(cur.pos());
480
481         CursorSlice tip1 = cur.top();
482         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
483                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
484                 if (!ch2.isSimilarTo(ch))
485                         break;
486         }
487         CursorSlice tip2 = cur.top();
488         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
489                 tip2.backwardPos();
490                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
491                 if (!ch2.isSimilarTo(ch)) {
492                         // take a step forward to correctly set the selection
493                         tip2.forwardPos();
494                         break;
495                 }
496         }
497         if (forward)
498                 swap(tip1, tip2);
499         cur.top() = tip1;
500         cur.bv().mouseSetCursor(cur, false);
501         cur.top() = tip2;
502         cur.bv().mouseSetCursor(cur, true);
503         return true;
504 }
505
506
507 namespace {
508
509
510 bool findChange(BufferView * bv, bool forward)
511 {
512         Cursor cur(*bv);
513         cur.setCursor(forward ? bv->cursor().selectionEnd()
514                       : bv->cursor().selectionBegin());
515         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
516         return selectChange(cur, forward);
517 }
518
519 }
520
521 bool findNextChange(BufferView * bv)
522 {
523         return findChange(bv, true);
524 }
525
526
527 bool findPreviousChange(BufferView * bv)
528 {
529         return findChange(bv, false);
530 }
531
532
533
534 namespace {
535
536 typedef vector<pair<string, string> > Escapes;
537
538 /// A map of symbols and their escaped equivalent needed within a regex.
539 /// @note Beware of order
540 Escapes const & get_regexp_escapes()
541 {
542         typedef std::pair<std::string, std::string> P;
543
544         static Escapes escape_map;
545         if (escape_map.empty()) {
546                 escape_map.push_back(P("$", "_x_$"));
547                 escape_map.push_back(P("{", "_x_{"));
548                 escape_map.push_back(P("}", "_x_}"));
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("\\", "(?:\\\\|\\\\backslash)"));
557                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
558                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
559                 escape_map.push_back(P("_x_", "\\"));
560         }
561         return escape_map;
562 }
563
564 /// A map of lyx escaped strings and their unescaped equivalent.
565 Escapes const & get_lyx_unescapes()
566 {
567         typedef std::pair<std::string, std::string> P;
568
569         static Escapes escape_map;
570         if (escape_map.empty()) {
571                 escape_map.push_back(P("\\%", "%"));
572                 escape_map.push_back(P("\\mathcircumflex ", "^"));
573                 escape_map.push_back(P("\\mathcircumflex", "^"));
574                 escape_map.push_back(P("\\backslash ", "\\"));
575                 escape_map.push_back(P("\\backslash", "\\"));
576                 escape_map.push_back(P("\\\\{", "_x_<"));
577                 escape_map.push_back(P("\\\\}", "_x_>"));
578                 escape_map.push_back(P("\\sim ", "~"));
579                 escape_map.push_back(P("\\sim", "~"));
580         }
581         return escape_map;
582 }
583
584 /// A map of escapes turning a regexp matching text to one matching latex.
585 Escapes const & get_regexp_latex_escapes()
586 {
587         typedef std::pair<std::string, std::string> P;
588
589         static Escapes escape_map;
590         if (escape_map.empty()) {
591                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
592                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
593                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
594                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
595                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
596                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
597                 escape_map.push_back(P("%", "\\\\\\%"));
598         }
599         return escape_map;
600 }
601
602 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
603  ** the found occurrence were escaped.
604  **/
605 string apply_escapes(string s, Escapes const & escape_map)
606 {
607         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
608         Escapes::const_iterator it;
609         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
610 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
611                 unsigned int pos = 0;
612                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
613                         s.replace(pos, it->first.length(), it->second);
614                         LYXERR(Debug::FIND, "After escape: " << s);
615                         pos += it->second.length();
616 //                      LYXERR(Debug::FIND, "pos: " << pos);
617                 }
618         }
619         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
620         return s;
621 }
622
623
624 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
625 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
626 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
627 string escape_for_regex(string s, bool match_latex)
628 {
629         size_t pos = 0;
630         while (pos < s.size()) {
631                 size_t new_pos = s.find("\\regexp{", pos);
632                 if (new_pos == string::npos)
633                         new_pos = s.size();
634                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
635                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
636                 LYXERR(Debug::FIND, "t [lyx]: " << t);
637                 t = apply_escapes(t, get_regexp_escapes());
638                 LYXERR(Debug::FIND, "t [rxp]: " << t);
639                 s.replace(pos, new_pos - pos, t);
640                 new_pos = pos + t.size();
641                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
642                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
643                 if (new_pos == s.size())
644                         break;
645                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
646                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
647                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
648                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
649                 LYXERR(Debug::FIND, "t in regexp      : " << t);
650                 t = apply_escapes(t, get_lyx_unescapes());
651                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
652                 if (match_latex) {
653                         t = apply_escapes(t, get_regexp_latex_escapes());
654                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
655                 }
656                 if (end_pos == s.size()) {
657                         s.replace(new_pos, end_pos - new_pos, t);
658                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
659                         break;
660                 }
661                 s.replace(new_pos, end_pos + 13 - new_pos, t);
662                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
663                 pos = new_pos + t.size();
664                 LYXERR(Debug::FIND, "pos: " << pos);
665         }
666         return s;
667 }
668
669
670 /// Wrapper for lyx::regex_replace with simpler interface
671 bool regex_replace(string const & s, string & t, string const & searchstr,
672                    string const & replacestr)
673 {
674         lyx::regex e(searchstr);
675         ostringstream oss;
676         ostream_iterator<char, char> it(oss);
677         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
678         // tolerate t and s be references to the same variable
679         bool rv = (s != oss.str());
680         t = oss.str();
681         return rv;
682 }
683
684
685 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
686  **
687  ** Verify that closed braces exactly match open braces. This avoids that, for example,
688  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
689  **
690  ** @param unmatched
691  ** Number of open braces that must remain open at the end for the verification to succeed.
692  **/
693 bool braces_match(string::const_iterator const & beg,
694                   string::const_iterator const & end,
695                   int unmatched = 0)
696 {
697         int open_pars = 0;
698         string::const_iterator it = beg;
699         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
700         for (; it != end; ++it) {
701                 // Skip escaped braces in the count
702                 if (*it == '\\') {
703                         ++it;
704                         if (it == end)
705                                 break;
706                 } else if (*it == '{') {
707                         ++open_pars;
708                 } else if (*it == '}') {
709                         if (open_pars == 0) {
710                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
711                                 return false;
712                         } else
713                                 --open_pars;
714                 }
715         }
716         if (open_pars != unmatched) {
717                 LYXERR(Debug::FIND, "Found " << open_pars
718                        << " instead of " << unmatched
719                        << " unmatched open braces at the end of count");
720                 return false;
721         }
722         LYXERR(Debug::FIND, "Braces match as expected");
723         return true;
724 }
725
726
727 /** The class performing a match between a position in the document and the FindAdvOptions.
728  **/
729 class MatchStringAdv {
730 public:
731         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
732
733         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
734          ** constructor as opt.search, under the opt.* options settings.
735          **
736          ** @param at_begin
737          **     If set, then match is searched only against beginning of text starting at cur.
738          **     If unset, then match is searched anywhere in text starting at cur.
739          **
740          ** @return
741          ** The length of the matching text, or zero if no match was found.
742          **/
743         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
744
745 public:
746         /// buffer
747         lyx::Buffer * p_buf;
748         /// first buffer on which search was started
749         lyx::Buffer * const p_first_buf;
750         /// options
751         FindAndReplaceOptions const & opt;
752
753 private:
754         /// Auxiliary find method (does not account for opt.matchword)
755         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
756
757         /** Normalize a stringified or latexified LyX paragraph.
758          **
759          ** Normalize means:
760          ** <ul>
761          **   <li>if search is not casesensitive, then lowercase the string;
762          **   <li>remove any newline at begin or end of the string;
763          **   <li>replace any newline in the middle of the string with a simple space;
764          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
765          ** </ul>
766          **
767          ** @todo Normalization should also expand macros, if the corresponding
768          ** search option was checked.
769          **/
770         string normalize(docstring const & s, bool hack_braces) const;
771         // normalized string to search
772         string par_as_string;
773         // regular expression to use for searching
774         lyx::regex regexp;
775         // same as regexp, but prefixed with a ".*"
776         lyx::regex regexp2;
777         // leading format material as string
778         string lead_as_string;
779         // par_as_string after removal of lead_as_string
780         string par_as_string_nolead;
781         // unmatched open braces in the search string/regexp
782         int open_braces;
783         // number of (.*?) subexpressions added at end of search regexp for closing
784         // environments, math mode, styles, etc...
785         int close_wildcards;
786         // Are we searching with regular expressions ?
787         bool use_regexp;
788 };
789
790
791 static docstring buffer_to_latex(Buffer & buffer)
792 {
793         OutputParams runparams(&buffer.params().encoding());
794         TexRow texrow(false);
795         odocstringstream ods;
796         otexstream os(ods, texrow);
797         runparams.nice = true;
798         runparams.flavor = OutputParams::LATEX;
799         runparams.linelen = 80; //lyxrc.plaintext_linelen;
800         // No side effect of file copying and image conversion
801         runparams.dryrun = true;
802         pit_type const endpit = buffer.paragraphs().size();
803         for (pit_type pit = 0; pit != endpit; ++pit) {
804                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
805                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
806         }
807         return ods.str();
808 }
809
810
811 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
812 {
813         docstring str;
814         if (!opt.ignoreformat) {
815                 str = buffer_to_latex(buffer);
816         } else {
817                 OutputParams runparams(&buffer.params().encoding());
818                 runparams.nice = true;
819                 runparams.flavor = OutputParams::LATEX;
820                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
821                 runparams.dryrun = true;
822                 runparams.for_search = true;
823                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
824                         Paragraph const & par = buffer.paragraphs().at(pit);
825                         LYXERR(Debug::FIND, "Adding to search string: '"
826                                << par.asString(pos_type(0), par.size(),
827                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
828                                                &runparams)
829                                << "'");
830                         str += par.asString(pos_type(0), par.size(),
831                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
832                                             &runparams);
833                 }
834         }
835         return str;
836 }
837
838
839 /// Return separation pos between the leading material and the rest
840 static size_t identifyLeading(string const & s)
841 {
842         string t = s;
843         // @TODO Support \item[text]
844         while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
845                || regex_replace(t, t, "^\\$", "")
846                || regex_replace(t, t, "^\\\\\\[ ", "")
847                || regex_replace(t, t, "^\\\\item ", "")
848                || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
849                 LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
850         return s.find(t);
851 }
852
853
854 // Remove trailing closure of math, macros and environments, so to catch parts of them.
855 static int identifyClosing(string & t)
856 {
857         int open_braces = 0;
858         do {
859                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
860                 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
861                         continue;
862                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
863                         continue;
864                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
865                         continue;
866                 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
867                         ++open_braces;
868                         continue;
869                 }
870                 break;
871         } while (true);
872         return open_braces;
873 }
874
875
876 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
877         : p_buf(&buf), p_first_buf(&buf), opt(opt)
878 {
879         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
880         docstring const & ds = stringifySearchBuffer(find_buf, opt);
881         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
882         // When using regexp, braces are hacked already by escape_for_regex()
883         par_as_string = normalize(ds, !use_regexp);
884         open_braces = 0;
885         close_wildcards = 0;
886
887         size_t lead_size = 0;
888         if (opt.ignoreformat) {
889                 if (!use_regexp) {
890                         // if par_as_string_nolead were emty,
891                         // the following call to findAux will always *find* the string
892                         // in the checked data, and thus always using the slow
893                         // examining of the current text part.
894                         par_as_string_nolead = par_as_string;
895                 }
896         } else {
897                 lead_size = identifyLeading(par_as_string);
898                 lead_as_string = par_as_string.substr(0, lead_size);
899                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
900         }
901
902         if (!use_regexp) {
903                 open_braces = identifyClosing(par_as_string);
904                 identifyClosing(par_as_string_nolead);
905                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
906                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
907         } else {
908                 string lead_as_regexp;
909                 if (lead_size > 0) {
910                         // @todo No need to search for \regexp{} insets in leading material
911                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
912                         par_as_string = par_as_string_nolead;
913                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
914                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
915                 }
916                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
917                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
918                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
919                 if (
920                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
921                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
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 '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
925                         || regex_replace(par_as_string, par_as_string,
926                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
927                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
928                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
929                         ) {
930                         ++close_wildcards;
931                 }
932                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
933                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
934                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
935                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
936                 // If entered regexp must match at begin of searched string buffer
937                 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
938                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
939                 regexp = lyx::regex(regexp_str);
940
941                 // If entered regexp may match wherever in searched string buffer
942                 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
943                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
944                 regexp2 = lyx::regex(regexp2_str);
945         }
946 }
947
948
949 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
950 {
951         if (at_begin &&
952                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
953                 return 0;
954         docstring docstr = stringifyFromForSearch(opt, cur, len);
955         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
956         string str = normalize(docstr, true);
957         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
958         if (! use_regexp) {
959                 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
960                 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
961                 if (at_begin) {
962                         LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
963                         if (str.substr(0, par_as_string.size()) == par_as_string)
964                                 return par_as_string.size();
965                 } else {
966                         size_t pos = str.find(par_as_string_nolead);
967                         if (pos != string::npos)
968                                 return par_as_string.size();
969                 }
970         } else {
971                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
972                 // Try all possible regexp matches,
973                 //until one that verifies the braces match test is found
974                 regex const *p_regexp = at_begin ? &regexp : &regexp2;
975                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
976                 sregex_iterator re_it_end;
977                 for (; re_it != re_it_end; ++re_it) {
978                         match_results<string::const_iterator> const & m = *re_it;
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                         // Check braces on segments that matched all (.*?) subexpressions,
984                         // except the last "padding" one inserted by lyx.
985                         for (size_t i = 1; i < m.size() - 1; ++i)
986                                 if (!braces_match(m[i].first, m[i].second))
987                                         return false;
988                         // Exclude from the returned match length any length
989                         // due to close wildcards added at end of regexp
990                         if (close_wildcards == 0)
991                                 return m[0].second - m[0].first;
992                         else
993                                 return m[m.size() - close_wildcards].first - m[0].first;
994                 }
995         }
996         return 0;
997 }
998
999
1000 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1001 {
1002         int res = findAux(cur, len, at_begin);
1003         LYXERR(Debug::FIND,
1004                "res=" << res << ", at_begin=" << at_begin
1005                << ", matchword=" << opt.matchword
1006                << ", inTexted=" << cur.inTexted());
1007         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1008                 return res;
1009         Paragraph const & par = cur.paragraph();
1010         bool ws_left = (cur.pos() > 0)
1011                 ? par.isWordSeparator(cur.pos() - 1)
1012                 : true;
1013         bool ws_right = (cur.pos() + res < par.size())
1014                 ? par.isWordSeparator(cur.pos() + res)
1015                 : true;
1016         LYXERR(Debug::FIND,
1017                "cur.pos()=" << cur.pos() << ", res=" << res
1018                << ", separ: " << ws_left << ", " << ws_right
1019                << endl);
1020         if (ws_left && ws_right)
1021                 return res;
1022         return 0;
1023 }
1024
1025
1026 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1027 {
1028         string t;
1029         if (! opt.casesensitive)
1030                 t = lyx::to_utf8(lowercase(s));
1031         else
1032                 t = lyx::to_utf8(s);
1033         // Remove \n at begin
1034         while (!t.empty() && t[0] == '\n')
1035                 t = t.substr(1);
1036         // Remove \n at end
1037         while (!t.empty() && t[t.size() - 1] == '\n')
1038                 t = t.substr(0, t.size() - 1);
1039         size_t pos;
1040         // Replace all other \n with spaces
1041         while ((pos = t.find("\n")) != string::npos)
1042                 t.replace(pos, 1, " ");
1043         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1044         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1045         while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
1046                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1047
1048         // FIXME - check what preceeds the brace
1049         if (hack_braces) {
1050                 if (opt.ignoreformat)
1051                         while (regex_replace(t, t, "\\{", "_x_<")
1052                                || regex_replace(t, t, "\\}", "_x_>"))
1053                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1054                 else
1055                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1056                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1057                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1058         }
1059
1060         return t;
1061 }
1062
1063
1064 docstring stringifyFromCursor(DocIterator const & cur, int len)
1065 {
1066         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1067         if (cur.inTexted()) {
1068                 Paragraph const & par = cur.paragraph();
1069                 // TODO what about searching beyond/across paragraph breaks ?
1070                 // TODO Try adding a AS_STR_INSERTS as last arg
1071                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1072                         int(par.size()) : cur.pos() + len;
1073                 OutputParams runparams(&cur.buffer()->params().encoding());
1074                 runparams.nice = true;
1075                 runparams.flavor = OutputParams::LATEX;
1076                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1077                 // No side effect of file copying and image conversion
1078                 runparams.dryrun = true;
1079                 LYXERR(Debug::FIND, "Stringifying with cur: "
1080                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1081                 return par.asString(cur.pos(), end,
1082                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1083                         &runparams);
1084         } else if (cur.inMathed()) {
1085                 docstring s;
1086                 CursorSlice cs = cur.top();
1087                 MathData md = cs.cell();
1088                 MathData::const_iterator it_end =
1089                         (( len == -1 || cs.pos() + len > int(md.size()))
1090                          ? md.end()
1091                          : md.begin() + cs.pos() + len );
1092                 for (MathData::const_iterator it = md.begin() + cs.pos();
1093                      it != it_end; ++it)
1094                         s = s + asString(*it);
1095                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1096                 return s;
1097         }
1098         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1099         return docstring();
1100 }
1101
1102
1103 /** Computes the LaTeX export of buf starting from cur and ending len positions
1104  * after cur, if len is positive, or at the paragraph or innermost inset end
1105  * if len is -1.
1106  */
1107 docstring latexifyFromCursor(DocIterator const & cur, int len)
1108 {
1109         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1110         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1111                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1112         Buffer const & buf = *cur.buffer();
1113         LBUFERR(buf.params().isLatex());
1114
1115         TexRow texrow(false);
1116         odocstringstream ods;
1117         otexstream os(ods, texrow);
1118         OutputParams runparams(&buf.params().encoding());
1119         runparams.nice = false;
1120         runparams.flavor = OutputParams::LATEX;
1121         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1122         // No side effect of file copying and image conversion
1123         runparams.dryrun = true;
1124
1125         if (cur.inTexted()) {
1126                 // @TODO what about searching beyond/across paragraph breaks ?
1127                 pos_type endpos = cur.paragraph().size();
1128                 if (len != -1 && endpos > cur.pos() + len)
1129                         endpos = cur.pos() + len;
1130                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1131                           string(), cur.pos(), endpos);
1132                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1133         } else if (cur.inMathed()) {
1134                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1135                 for (int s = cur.depth() - 1; s >= 0; --s) {
1136                         CursorSlice const & cs = cur[s];
1137                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1138                                 WriteStream ws(os);
1139                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1140                                 break;
1141                         }
1142                 }
1143
1144                 CursorSlice const & cs = cur.top();
1145                 MathData md = cs.cell();
1146                 MathData::const_iterator it_end =
1147                         ((len == -1 || cs.pos() + len > int(md.size()))
1148                          ? md.end()
1149                          : md.begin() + cs.pos() + len);
1150                 for (MathData::const_iterator it = md.begin() + cs.pos();
1151                      it != it_end; ++it)
1152                         ods << asString(*it);
1153
1154                 // Retrieve the math environment type, and add '$' or '$]'
1155                 // or others (\end{equation}) accordingly
1156                 for (int s = cur.depth() - 1; s >= 0; --s) {
1157                         CursorSlice const & cs = cur[s];
1158                         InsetMath * inset = cs.asInsetMath();
1159                         if (inset && inset->asHullInset()) {
1160                                 WriteStream ws(os);
1161                                 inset->asHullInset()->footer_write(ws);
1162                                 break;
1163                         }
1164                 }
1165                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1166         } else {
1167                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1168         }
1169         return ods.str();
1170 }
1171
1172
1173 /** Finalize an advanced find operation, advancing the cursor to the innermost
1174  ** position that matches, plus computing the length of the matching text to
1175  ** be selected
1176  **/
1177 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1178 {
1179         // Search the foremost position that matches (avoids find of entire math
1180         // inset when match at start of it)
1181         size_t d;
1182         DocIterator old_cur(cur.buffer());
1183         do {
1184                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1185                 d = cur.depth();
1186                 old_cur = cur;
1187                 cur.forwardPos();
1188         } while (cur && cur.depth() > d && match(cur) > 0);
1189         cur = old_cur;
1190         LASSERT(match(cur) > 0, return 0);
1191         LYXERR(Debug::FIND, "Ok");
1192
1193         // Compute the match length
1194         int len = 1;
1195         if (cur.pos() + len > cur.lastpos())
1196                 return 0;
1197         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1198         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1199                 ++len;
1200                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1201         }
1202         // Length of matched text (different from len param)
1203         int old_len = match(cur, len);
1204         int new_len;
1205         // Greedy behaviour while matching regexps
1206         while ((new_len = match(cur, len + 1)) > old_len) {
1207                 ++len;
1208                 old_len = new_len;
1209                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1210         }
1211         return len;
1212 }
1213
1214
1215 /// Finds forward
1216 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1217 {
1218         if (!cur)
1219                 return 0;
1220         while (!theApp()->longOperationCancelled() && cur) {
1221                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1222                 int match_len = match(cur, -1, false);
1223                 LYXERR(Debug::FIND, "match_len: " << match_len);
1224                 if (match_len) {
1225                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1226                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1227                                 int match_len = match(cur);
1228                                 LYXERR(Debug::FIND, "match_len: " << match_len);
1229                                 if (match_len) {
1230                                         // Sometimes in finalize we understand it wasn't a match
1231                                         // and we need to continue the outest loop
1232                                         int len = findAdvFinalize(cur, match);
1233                                         if (len > 0)
1234                                                 return len;
1235                                 }
1236                         }
1237                         if (!cur)
1238                                 return 0;
1239                 }
1240                 if (cur.pit() < cur.lastpit()) {
1241                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1242                         cur.forwardPar();
1243                 } else {
1244                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1245                         cur.pos() = cur.lastpos();
1246                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1247                         cur.forwardPos();
1248                 }
1249         }
1250         return 0;
1251 }
1252
1253
1254 /// Find the most backward consecutive match within same paragraph while searching backwards.
1255 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1256 {
1257         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1258         DocIterator tmp_cur = cur;
1259         int len = findAdvFinalize(tmp_cur, match);
1260         Inset & inset = cur.inset();
1261         for (; cur != cur_begin; cur.backwardPos()) {
1262                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1263                 DocIterator new_cur = cur;
1264                 new_cur.backwardPos();
1265                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1266                         break;
1267                 int new_len = findAdvFinalize(new_cur, match);
1268                 if (new_len == len)
1269                         break;
1270                 len = new_len;
1271         }
1272         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1273         return len;
1274 }
1275
1276
1277 /// Finds backwards
1278 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1279 {
1280         if (! cur)
1281                 return 0;
1282         // Backup of original position
1283         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1284         if (cur == cur_begin)
1285                 return 0;
1286         cur.backwardPos();
1287         DocIterator cur_orig(cur);
1288         bool pit_changed = false;
1289         do {
1290                 cur.pos() = 0;
1291                 bool found_match = match(cur, -1, false);
1292
1293                 if (found_match) {
1294                         if (pit_changed)
1295                                 cur.pos() = cur.lastpos();
1296                         else
1297                                 cur.pos() = cur_orig.pos();
1298                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1299                         DocIterator cur_prev_iter;
1300                         do {
1301                                 found_match = match(cur);
1302                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1303                                        << found_match << ", cur: " << cur);
1304                                 if (found_match)
1305                                         return findMostBackwards(cur, match);
1306
1307                                 // Stop if begin of document reached
1308                                 if (cur == cur_begin)
1309                                         break;
1310                                 cur_prev_iter = cur;
1311                                 cur.backwardPos();
1312                         } while (true);
1313                 }
1314                 if (cur == cur_begin)
1315                         break;
1316                 if (cur.pit() > 0)
1317                         --cur.pit();
1318                 else
1319                         cur.backwardPos();
1320                 pit_changed = true;
1321         } while (!theApp()->longOperationCancelled());
1322         return 0;
1323 }
1324
1325
1326 } // anonym namespace
1327
1328
1329 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1330                                  DocIterator const & cur, int len)
1331 {
1332         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1333                 return docstring());
1334         if (!opt.ignoreformat)
1335                 return latexifyFromCursor(cur, len);
1336         else
1337                 return stringifyFromCursor(cur, len);
1338 }
1339
1340
1341 FindAndReplaceOptions::FindAndReplaceOptions(
1342         docstring const & find_buf_name, bool casesensitive,
1343         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1344         docstring const & repl_buf_name, bool keep_case,
1345         SearchScope scope, SearchRestriction restr)
1346         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1347           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1348           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1349 {
1350 }
1351
1352
1353 namespace {
1354
1355
1356 /** Check if 'len' letters following cursor are all non-lowercase */
1357 static bool allNonLowercase(Cursor const & cur, int len)
1358 {
1359         pos_type beg_pos = cur.selectionBegin().pos();
1360         pos_type end_pos = cur.selectionBegin().pos() + len;
1361         if (len > cur.lastpos() + 1 - beg_pos) {
1362                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1363                 len = cur.lastpos() + 1 - beg_pos;
1364                 end_pos = beg_pos + len;
1365         }
1366         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1367                 if (isLowerCase(cur.paragraph().getChar(pos)))
1368                         return false;
1369         return true;
1370 }
1371
1372
1373 /** Check if first letter is upper case and second one is lower case */
1374 static bool firstUppercase(Cursor const & cur)
1375 {
1376         char_type ch1, ch2;
1377         pos_type pos = cur.selectionBegin().pos();
1378         if (pos >= cur.lastpos() - 1) {
1379                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1380                 return false;
1381         }
1382         ch1 = cur.paragraph().getChar(pos);
1383         ch2 = cur.paragraph().getChar(pos + 1);
1384         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1385         LYXERR(Debug::FIND, "firstUppercase(): "
1386                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1387                << ch2 << "(" << char(ch2) << ")"
1388                << ", result=" << result << ", cur=" << cur);
1389         return result;
1390 }
1391
1392
1393 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1394  **
1395  ** \fixme What to do with possible further paragraphs in replace buffer ?
1396  **/
1397 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1398 {
1399         ParagraphList::iterator pit = buffer.paragraphs().begin();
1400         LASSERT(pit->size() >= 1, /**/);
1401         pos_type right = pos_type(1);
1402         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1403         right = pit->size();
1404         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1405 }
1406
1407 } // anon namespace
1408
1409 ///
1410 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1411 {
1412         Cursor & cur = bv->cursor();
1413         if (opt.repl_buf_name == docstring())
1414                 return;
1415
1416         DocIterator sel_beg = cur.selectionBegin();
1417         DocIterator sel_end = cur.selectionEnd();
1418         if (&sel_beg.inset() != &sel_end.inset()
1419             || sel_beg.pit() != sel_end.pit()
1420             || sel_beg.idx() != sel_end.idx())
1421                 return;
1422         int sel_len = sel_end.pos() - sel_beg.pos();
1423         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1424                << ", sel_len: " << sel_len << endl);
1425         if (sel_len == 0)
1426                 return;
1427         LASSERT(sel_len > 0, return);
1428
1429         if (!matchAdv(sel_beg, sel_len))
1430                 return;
1431
1432         // Build a copy of the replace buffer, adapted to the KeepCase option
1433         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1434         ostringstream oss;
1435         repl_buffer_orig.write(oss);
1436         string lyx = oss.str();
1437         Buffer repl_buffer("", false);
1438         repl_buffer.setUnnamed(true);
1439         LASSERT(repl_buffer.readString(lyx), return);
1440         if (opt.keep_case && sel_len >= 2) {
1441                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1442                 if (cur.inTexted()) {
1443                         if (firstUppercase(cur))
1444                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1445                         else if (allNonLowercase(cur, sel_len))
1446                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1447                 }
1448         }
1449         cap::cutSelection(cur, false, false);
1450         if (cur.inTexted()) {
1451                 repl_buffer.changeLanguage(
1452                         repl_buffer.language(),
1453                         cur.getFont().language());
1454                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1455                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1456                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1457                                         repl_buffer.params().documentClassPtr(),
1458                                         bv->buffer().errorList("Paste"));
1459                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1460                 sel_len = repl_buffer.paragraphs().begin()->size();
1461         } else if (cur.inMathed()) {
1462                 TexRow texrow(false);
1463                 odocstringstream ods;
1464                 otexstream os(ods, texrow);
1465                 OutputParams runparams(&repl_buffer.params().encoding());
1466                 runparams.nice = false;
1467                 runparams.flavor = OutputParams::LATEX;
1468                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1469                 runparams.dryrun = true;
1470                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1471                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1472                 docstring repl_latex = ods.str();
1473                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1474                 string s;
1475                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1476                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1477                 repl_latex = from_utf8(s);
1478                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1479                 MathData ar(cur.buffer());
1480                 asArray(repl_latex, ar, Parse::NORMAL);
1481                 cur.insert(ar);
1482                 sel_len = ar.size();
1483                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1484         }
1485         if (cur.pos() >= sel_len)
1486                 cur.pos() -= sel_len;
1487         else
1488                 cur.pos() = 0;
1489         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1490         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1491         bv->processUpdateFlags(Update::Force);
1492 }
1493
1494
1495 /// Perform a FindAdv operation.
1496 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1497 {
1498         DocIterator cur;
1499         int match_len = 0;
1500
1501         try {
1502                 MatchStringAdv matchAdv(bv->buffer(), opt);
1503                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1504                 if (length > 0)
1505                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1506                 findAdvReplace(bv, opt, matchAdv);
1507                 cur = bv->cursor();
1508                 if (opt.forward)
1509                         match_len = findForwardAdv(cur, matchAdv);
1510                 else
1511                         match_len = findBackwardsAdv(cur, matchAdv);
1512         } catch (...) {
1513                 // This may only be raised by lyx::regex()
1514                 bv->message(_("Invalid regular expression!"));
1515                 return false;
1516         }
1517
1518         if (match_len == 0) {
1519                 bv->message(_("Match not found!"));
1520                 return false;
1521         }
1522
1523         bv->message(_("Match found!"));
1524
1525         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1526         bv->putSelectionAt(cur, match_len, !opt.forward);
1527
1528         return true;
1529 }
1530
1531
1532 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1533 {
1534         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1535            << opt.casesensitive << ' '
1536            << opt.matchword << ' '
1537            << opt.forward << ' '
1538            << opt.expandmacros << ' '
1539            << opt.ignoreformat << ' '
1540            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1541            << opt.keep_case << ' '
1542            << int(opt.scope) << ' '
1543            << int(opt.restr);
1544
1545         LYXERR(Debug::FIND, "built: " << os.str());
1546
1547         return os;
1548 }
1549
1550
1551 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1552 {
1553         LYXERR(Debug::FIND, "parsing");
1554         string s;
1555         string line;
1556         getline(is, line);
1557         while (line != "EOSS") {
1558                 if (! s.empty())
1559                         s = s + "\n";
1560                 s = s + line;
1561                 if (is.eof())   // Tolerate malformed request
1562                         break;
1563                 getline(is, line);
1564         }
1565         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1566         opt.find_buf_name = from_utf8(s);
1567         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1568         is.get();       // Waste space before replace string
1569         s = "";
1570         getline(is, line);
1571         while (line != "EOSS") {
1572                 if (! s.empty())
1573                         s = s + "\n";
1574                 s = s + line;
1575                 if (is.eof())   // Tolerate malformed request
1576                         break;
1577                 getline(is, line);
1578         }
1579         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1580         opt.repl_buf_name = from_utf8(s);
1581         is >> opt.keep_case;
1582         int i;
1583         is >> i;
1584         opt.scope = FindAndReplaceOptions::SearchScope(i);
1585         is >> i;
1586         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1587
1588         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1589                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1590                << opt.scope << ' ' << opt.restr);
1591         return is;
1592 }
1593
1594 } // lyx namespace