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