]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
The time_t type seems to be an unsigned type when compiling with MSVC.
[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, "(.*)[[:blank:]]\\'", "$1"))
795                                         continue;
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")
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                         odocstringstream os;
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                                         os << *it;
980                         return os.str();
981         }
982         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
983         return docstring();
984 }
985
986
987 /** Computes the LaTeX export of buf starting from cur and ending len positions
988  * after cur, if len is positive, or at the paragraph or innermost inset end
989  * if len is -1.
990  */
991 docstring latexifyFromCursor(DocIterator const & cur, int len)
992 {
993         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
994         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
995                 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
996         Buffer const & buf = *cur.buffer();
997         LASSERT(buf.params().isLatex(), /* */);
998
999         TexRow texrow;
1000         odocstringstream ods;
1001         otexstream os(ods, texrow);
1002         OutputParams runparams(&buf.params().encoding());
1003         runparams.nice = false;
1004         runparams.flavor = OutputParams::LATEX;
1005         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1006         // No side effect of file copying and image conversion
1007         runparams.dryrun = true;
1008
1009         if (cur.inTexted()) {
1010                 // @TODO what about searching beyond/across paragraph breaks ?
1011                 pos_type endpos = cur.paragraph().size();
1012                 if (len != -1 && endpos > cur.pos() + len)
1013                         endpos = cur.pos() + len;
1014                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1015                         string(), cur.pos(), endpos);
1016                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1017         } else if (cur.inMathed()) {
1018                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1019                 for (int s = cur.depth() - 1; s >= 0; --s) {
1020                                 CursorSlice const & cs = cur[s];
1021                                 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1022                                                 WriteStream ws(ods);
1023                                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1024                                                 break;
1025                                 }
1026                 }
1027
1028                 CursorSlice const & cs = cur.top();
1029                 MathData md = cs.cell();
1030                 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
1031                         ? md.end() : md.begin() + cs.pos() + len );
1032                 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
1033                                 ods << *it;
1034
1035                 // Retrieve the math environment type, and add '$' or '$]'
1036                 // or others (\end{equation}) accordingly
1037                 for (int s = cur.depth() - 1; s >= 0; --s) {
1038                         CursorSlice const & cs = cur[s];
1039                         InsetMath * inset = cs.asInsetMath();
1040                         if (inset && inset->asHullInset()) {
1041                                 WriteStream ws(ods);
1042                                 inset->asHullInset()->footer_write(ws);
1043                                 break;
1044                         }
1045                 }
1046                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1047         } else {
1048                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1049         }
1050         return ods.str();
1051 }
1052
1053
1054 /** Finalize an advanced find operation, advancing the cursor to the innermost
1055  ** position that matches, plus computing the length of the matching text to
1056  ** be selected
1057  **/
1058 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1059 {
1060         // Search the foremost position that matches (avoids find of entire math
1061         // inset when match at start of it)
1062         size_t d;
1063         DocIterator old_cur(cur.buffer());
1064         do {
1065                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1066                 d = cur.depth();
1067                 old_cur = cur;
1068                 cur.forwardPos();
1069         } while (cur && cur.depth() > d && match(cur) > 0);
1070         cur = old_cur;
1071         LASSERT(match(cur) > 0, /* */);
1072         LYXERR(Debug::FIND, "Ok");
1073
1074         // Compute the match length
1075         int len = 1;
1076         if (cur.pos() + len > cur.lastpos())
1077                 return 0;
1078         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1079         while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1080                 ++len;
1081                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1082         }
1083         // Length of matched text (different from len param)
1084         int old_len = match(cur, len);
1085         int new_len;
1086         // Greedy behaviour while matching regexps
1087         while ((new_len = match(cur, len + 1)) > old_len) {
1088                 ++len;
1089                 old_len = new_len;
1090                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1091         }
1092         return len;
1093 }
1094
1095
1096 /// Finds forward
1097 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1098 {
1099         if (!cur)
1100                 return 0;
1101         while (cur) {
1102                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1103                 if (match(cur, -1, false)) {
1104                         for (; cur; cur.forwardPos()) {
1105                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1106                                 if (match(cur)) {
1107                                         // Sometimes in finalize we understand it wasn't a match
1108                                         // and we need to continue the outest loop
1109                                         int len = findAdvFinalize(cur, match);
1110                                         if (len > 0)
1111                                                 return len;
1112                                 }
1113                         }
1114                         if (!cur)
1115                                 return 0;
1116                 }
1117                 if (cur.pit() < cur.lastpit()) {
1118                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1119                         cur.forwardPar();
1120                 } else {
1121                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1122                         cur.pos() = cur.lastpos();
1123                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1124                         cur.forwardPos();
1125                 }
1126         }
1127         return 0;
1128 }
1129
1130
1131 /// Find the most backward consecutive match within same paragraph while searching backwards.
1132 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1133 {
1134         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1135         DocIterator tmp_cur = cur;
1136         int len = findAdvFinalize(tmp_cur, match);
1137         Inset & inset = cur.inset();
1138         for (; cur != cur_begin; cur.backwardPos()) {
1139                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1140                 DocIterator new_cur = cur;
1141                 new_cur.backwardPos();
1142                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1143                         break;
1144                 int new_len = findAdvFinalize(new_cur, match);
1145                 if (new_len == len)
1146                         break;
1147                 len = new_len;
1148         }
1149         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1150         return len;
1151 }
1152
1153
1154 /// Finds backwards
1155 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1156         if (! cur)
1157                 return 0;
1158         // Backup of original position
1159         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1160         if (cur == cur_begin)
1161                 return 0;
1162         cur.backwardPos();
1163         DocIterator cur_orig(cur);
1164         bool found_match;
1165         bool pit_changed = false;
1166         found_match = false;
1167         do {
1168                 cur.pos() = 0;
1169                 found_match = match(cur, -1, false);
1170
1171                 if (found_match) {
1172                         if (pit_changed)
1173                                 cur.pos() = cur.lastpos();
1174                         else
1175                                 cur.pos() = cur_orig.pos();
1176                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1177                         DocIterator cur_prev_iter;
1178                         do {
1179                                 found_match = match(cur);
1180                                 LYXERR(Debug::FIND, "findBackAdv3: found_match=" 
1181                                        << found_match << ", cur: " << cur);
1182                                 if (found_match)
1183                                         return findMostBackwards(cur, match);
1184
1185                                 // Stop if begin of document reached
1186                                 if (cur == cur_begin)
1187                                         break;
1188                                 cur_prev_iter = cur;
1189                                 cur.backwardPos();
1190                         } while (true);
1191                 }
1192                 if (cur == cur_begin)
1193                         break;
1194                 if (cur.pit() > 0)
1195                         --cur.pit();
1196                 else
1197                         cur.backwardPos();
1198                 pit_changed = true;
1199         } while (true);
1200         return 0;
1201 }
1202
1203
1204 } // anonym namespace
1205
1206
1207 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1208         DocIterator const & cur, int len)
1209 {
1210         LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1211         if (!opt.ignoreformat)
1212                 return latexifyFromCursor(cur, len);
1213         else
1214                 return stringifyFromCursor(cur, len);
1215 }
1216
1217
1218 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & find_buf_name, bool casesensitive,
1219         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1220         docstring const & repl_buf_name, bool keep_case,
1221         SearchScope scope)
1222         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1223         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1224         repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1225 {
1226 }
1227
1228
1229 namespace {
1230
1231
1232 /** Check if 'len' letters following cursor are all non-lowercase */
1233 static bool allNonLowercase(DocIterator const & cur, int len) {
1234         pos_type end_pos = cur.pos() + len;
1235         for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1236                 if (isLowerCase(cur.paragraph().getChar(pos)))
1237                         return false;
1238         return true;
1239 }
1240
1241
1242 /** Check if first letter is upper case and second one is lower case */
1243 static bool firstUppercase(DocIterator const & cur) {
1244         char_type ch1, ch2;
1245         if (cur.pos() >= cur.lastpos() - 1) {
1246                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1247                 return false;
1248         }
1249         ch1 = cur.paragraph().getChar(cur.pos());
1250         ch2 = cur.paragraph().getChar(cur.pos()+1);
1251         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1252         LYXERR(Debug::FIND, "firstUppercase(): "
1253                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2=" 
1254                << ch2 << "(" << char(ch2) << ")"
1255                << ", result=" << result << ", cur=" << cur);
1256         return result;
1257 }
1258
1259
1260 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1261  **
1262  ** \fixme What to do with possible further paragraphs in replace buffer ?
1263  **/
1264 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1265         ParagraphList::iterator pit = buffer.paragraphs().begin();
1266         pos_type right = pos_type(1);
1267         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1268         right = pit->size() + 1;
1269         pit->changeCase(buffer.params(), right, right, others_case);
1270 }
1271 } // anon namespace
1272
1273 ///
1274 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1275 {
1276         Cursor & cur = bv->cursor();
1277         if (opt.repl_buf_name == docstring())
1278                 return;
1279
1280         DocIterator sel_beg = cur.selectionBegin();
1281         DocIterator sel_end = cur.selectionEnd();
1282         if (&sel_beg.inset() != &sel_end.inset()
1283             || sel_beg.pit() != sel_end.pit())
1284                 return;
1285         int sel_len = sel_end.pos() - sel_beg.pos();
1286         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1287                << ", sel_len: " << sel_len << endl);
1288         if (sel_len == 0)
1289                 return;
1290         LASSERT(sel_len > 0, /**/);
1291
1292         if (!matchAdv(sel_beg, sel_len))
1293                 return;
1294
1295         // Build a copy of the replace buffer, adapted to the KeepCase option
1296         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1297         ostringstream oss;
1298         repl_buffer_orig.write(oss);
1299         string lyx = oss.str();
1300         Buffer repl_buffer("", false);
1301         repl_buffer.setUnnamed(true);
1302         LASSERT(repl_buffer.readString(lyx), /**/);
1303         if (opt.keep_case && sel_len >= 2) {
1304                 if (cur.inTexted()) {
1305                         if (firstUppercase(cur))
1306                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1307                         else if (allNonLowercase(cur, sel_len))
1308                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1309                 }
1310         }
1311         cap::cutSelection(cur, false, false);
1312         if (!cur.inMathed()) {
1313                 repl_buffer.changeLanguage(
1314                         repl_buffer.language(),
1315                         cur.getFont().language());
1316                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1317                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1318                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1319                                         repl_buffer.params().documentClassPtr(),
1320                                         bv->buffer().errorList("Paste"));
1321                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1322                 sel_len = repl_buffer.paragraphs().begin()->size();
1323         } else {
1324                 TexRow texrow;
1325                 odocstringstream ods;
1326                 otexstream os(ods, texrow);
1327                 OutputParams runparams(&repl_buffer.params().encoding());
1328                 runparams.nice = false;
1329                 runparams.flavor = OutputParams::LATEX;
1330                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1331                 runparams.dryrun = true;
1332                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1333                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1334                 docstring repl_latex = ods.str();
1335                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1336                 string s;
1337                 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1338                 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1339                 repl_latex = from_utf8(s);
1340                 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1341                 sel_len = cur.niceInsert(repl_latex);
1342         }
1343         if (cur.pos() >= sel_len)
1344                 cur.pos() -= sel_len;
1345         else
1346                 cur.pos() = 0;
1347         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << sel_len);
1348         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1349         bv->processUpdateFlags(Update::Force);
1350         bv->buffer().updatePreviews();
1351 }
1352
1353
1354 /// Perform a FindAdv operation.
1355 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1356 {
1357         DocIterator cur;
1358         int match_len = 0;
1359
1360         try {
1361                 MatchStringAdv matchAdv(bv->buffer(), opt);
1362                 findAdvReplace(bv, opt, matchAdv);
1363                 cur = bv->cursor();
1364                 if (opt.forward)
1365                                 match_len = findForwardAdv(cur, matchAdv);
1366                 else
1367                                 match_len = findBackwardsAdv(cur, matchAdv);
1368         } catch (...) {
1369                 // This may only be raised by lyx::regex()
1370                 bv->message(_("Invalid regular expression!"));
1371                 return false;
1372         }
1373
1374         if (match_len == 0) {
1375                 bv->message(_("Match not found!"));
1376                 return false;
1377         }
1378
1379         bv->message(_("Match found!"));
1380
1381         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1382         bv->putSelectionAt(cur, match_len, !opt.forward);
1383
1384         return true;
1385 }
1386
1387
1388 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1389 {
1390         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1391            << opt.casesensitive << ' '
1392            << opt.matchword << ' '
1393            << opt.forward << ' '
1394            << opt.expandmacros << ' '
1395            << opt.ignoreformat << ' '
1396            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1397            << opt.keep_case << ' '
1398            << int(opt.scope);
1399
1400         LYXERR(Debug::FIND, "built: " << os.str());
1401
1402         return os;
1403 }
1404
1405
1406 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1407 {
1408         LYXERR(Debug::FIND, "parsing");
1409         string s;
1410         string line;
1411         getline(is, line);
1412         while (line != "EOSS") {
1413                 if (! s.empty())
1414                                 s = s + "\n";
1415                 s = s + line;
1416                 if (is.eof())   // Tolerate malformed request
1417                                 break;
1418                 getline(is, line);
1419         }
1420         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1421         opt.find_buf_name = from_utf8(s);
1422         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1423         is.get();       // Waste space before replace string
1424         s = "";
1425         getline(is, line);
1426         while (line != "EOSS") {
1427                 if (! s.empty())
1428                                 s = s + "\n";
1429                 s = s + line;
1430                 if (is.eof())   // Tolerate malformed request
1431                                 break;
1432                 getline(is, line);
1433         }
1434         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1435         opt.repl_buf_name = from_utf8(s);
1436         is >> opt.keep_case;
1437         int i;
1438         is >> i;
1439         opt.scope = FindAndReplaceOptions::SearchScope(i);
1440         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1441                    << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);
1442         return is;
1443 }
1444
1445 } // lyx namespace