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