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