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