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