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