]> git.lyx.org Git - features.git/blob - src/lyxfind.cpp
cbb9289c8a5a947ecc8b2f00255e9f728fd21a89
[features.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/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
53
54 #include "support/regex.h"
55 #include <map>
56
57 using namespace std;
58 using namespace lyx::support;
59
60 namespace lyx {
61
62 namespace {
63
64 bool parse_bool(docstring & howto)
65 {
66         if (howto.empty())
67                 return false;
68         docstring var;
69         howto = split(howto, var, ' ');
70         return var == "1";
71 }
72
73
74 class MatchString : public binary_function<Paragraph, pos_type, int>
75 {
76 public:
77         MatchString(docstring const & str, bool cs, bool mw)
78                 : str(str), case_sens(cs), whole_words(mw)
79         {}
80
81         // returns true if the specified string is at the specified position
82         // del specifies whether deleted strings in ct mode will be considered
83         int operator()(Paragraph const & par, pos_type pos, bool del = true) const
84         {
85                 return par.find(str, case_sens, whole_words, pos, del);
86         }
87
88 private:
89         // search string
90         docstring str;
91         // case sensitive
92         bool case_sens;
93         // match whole words only
94         bool whole_words;
95 };
96
97
98 int findForward(DocIterator & cur, MatchString const & match,
99                 bool find_del = true)
100 {
101         for (; cur; cur.forwardChar())
102                 if (cur.inTexted()) {
103                         int len = match(cur.paragraph(), cur.pos(), find_del);
104                         if (len > 0)
105                                 return len;
106                 }
107         return 0;
108 }
109
110
111 int findBackwards(DocIterator & cur, MatchString const & match,
112                   bool find_del = true)
113 {
114         while (cur) {
115                 cur.backwardChar();
116                 if (cur.inTexted()) {
117                         int len = match(cur.paragraph(), cur.pos(), find_del);
118                         if (len > 0)
119                                 return len;
120                 }
121         }
122         return 0;
123 }
124
125
126 bool searchAllowed(docstring const & str)
127 {
128         if (str.empty()) {
129                 frontend::Alert::error(_("Search error"), _("Search string is empty"));
130                 return false;
131         }
132         return true;
133 }
134
135
136 bool findOne(BufferView * bv, docstring const & searchstr,
137              bool case_sens, bool whole, bool forward,
138              bool find_del = true, bool check_wrap = false)
139 {
140         if (!searchAllowed(searchstr))
141                 return false;
142
143         DocIterator cur = forward
144                 ? bv->cursor().selectionEnd()
145                 : bv->cursor().selectionBegin();
146
147         MatchString const match(searchstr, case_sens, whole);
148
149         int match_len = forward
150                 ? findForward(cur, match, find_del)
151                 : findBackwards(cur, match, find_del);
152
153         if (match_len > 0)
154                 bv->putSelectionAt(cur, match_len, !forward);
155         else if (check_wrap) {
156                 DocIterator cur_orig(bv->cursor());
157                 docstring q;
158                 if (forward)
159                         q = _("End of file reached while searching forward.\n"
160                           "Continue searching from the beginning?");
161                 else
162                         q = _("Beginning of file reached while searching backward.\n"
163                           "Continue searching from the end?");
164                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
165                         q, 0, 1, _("&Yes"), _("&No"));
166                 if (wrap_answer == 0) {
167                         if (forward) {
168                                 bv->cursor().clear();
169                                 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
170                         } else {
171                                 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
172                                 bv->cursor().backwardPos();
173                         }
174                         bv->clearSelection();
175                         if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
176                                 return true;
177                 }
178                 bv->cursor().setCursor(cur_orig);
179                 return false;
180         }
181
182         return match_len > 0;
183 }
184
185
186 int replaceAll(BufferView * bv,
187                docstring const & searchstr, docstring const & replacestr,
188                bool case_sens, bool whole)
189 {
190         Buffer & buf = bv->buffer();
191
192         if (!searchAllowed(searchstr) || buf.isReadonly())
193                 return 0;
194
195         DocIterator cur_orig(bv->cursor());
196
197         MatchString const match(searchstr, case_sens, whole);
198         int num = 0;
199
200         int const rsize = replacestr.size();
201         int const ssize = searchstr.size();
202
203         Cursor cur(*bv);
204         cur.setCursor(doc_iterator_begin(&buf));
205         int match_len = findForward(cur, match, false);
206         while (match_len > 0) {
207                 // Backup current cursor position and font.
208                 pos_type const pos = cur.pos();
209                 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
210                 cur.recordUndo();
211                 int striked = ssize -
212                         cur.paragraph().eraseChars(pos, pos + match_len,
213                                                    buf.params().track_changes);
214                 cur.paragraph().insert(pos, replacestr, font,
215                                        Change(buf.params().track_changes
216                                               ? Change::INSERTED
217                                               : Change::UNCHANGED));
218                 for (int i = 0; i < rsize + striked; ++i)
219                         cur.forwardChar();
220                 ++num;
221                 match_len = findForward(cur, match, false);
222         }
223
224         bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
225
226         cur_orig.fixIfBroken();
227         bv->setCursor(cur_orig);
228
229         return num;
230 }
231
232
233 // the idea here is that we are going to replace the string that
234 // is selected IF it is the search string.
235 // if there is a selection, but it is not the search string, then
236 // we basically ignore it. (FIXME We ought to replace only within
237 // the selection.)
238 // if there is no selection, then:
239 //  (i) if some search string has been provided, then we find it.
240 //      (think of how the dialog works when you hit "replace" the
241 //      first time.)
242 // (ii) if no search string has been provided, then we treat the
243 //      word the cursor is in as the search string. (why? i have no
244 //      idea.) but this only works in text?
245 //
246 // returns the number of replacements made (one, if any) and
247 // whether anything at all was done.
248 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
249                            docstring const & replacestr, bool case_sens,
250                            bool whole, bool forward, bool findnext)
251 {
252         Cursor & cur = bv->cursor();
253         bool found = false;
254         if (!cur.selection()) {
255                 // no selection, non-empty search string: find it
256                 if (!searchstr.empty()) {
257                         found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
258                         return make_pair(found, 0);
259                 }
260                 // empty search string
261                 if (!cur.inTexted())
262                         // bail in math
263                         return make_pair(false, 0);
264                 // select current word and treat it as the search string.
265                 // This causes a minor bug as undo will restore this selection,
266                 // which the user did not create (#8986).
267                 cur.innerText()->selectWord(cur, WHOLE_WORD);
268                 searchstr = cur.selectionAsString(false);
269         }
270
271         // if we still don't have a search string, report the error
272         // and abort.
273         if (!searchAllowed(searchstr))
274                 return make_pair(false, 0);
275
276         bool have_selection = cur.selection();
277         docstring const selected = cur.selectionAsString(false);
278         bool match =
279                 case_sens
280                 ? searchstr == selected
281                 : compare_no_case(searchstr, selected) == 0;
282
283         // no selection or current selection is not search word:
284         // just find the search word
285         if (!have_selection || !match) {
286                 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
287                 return make_pair(found, 0);
288         }
289
290         // we're now actually ready to replace. if the buffer is
291         // read-only, we can't, though.
292         if (bv->buffer().isReadonly())
293                 return make_pair(false, 0);
294
295         cap::replaceSelectionWithString(cur, replacestr);
296         if (forward) {
297                 cur.pos() += replacestr.length();
298                 LASSERT(cur.pos() <= cur.lastpos(),
299                         cur.pos() = cur.lastpos());
300         }
301         if (findnext)
302                 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
303
304         return make_pair(true, 1);
305 }
306
307 } // namespace
308
309
310 docstring const find2string(docstring const & search,
311                             bool casesensitive, bool matchword, bool forward)
312 {
313         odocstringstream ss;
314         ss << search << '\n'
315            << int(casesensitive) << ' '
316            << int(matchword) << ' '
317            << int(forward);
318         return ss.str();
319 }
320
321
322 docstring const replace2string(docstring const & replace,
323                                docstring const & search,
324                                bool casesensitive, bool matchword,
325                                bool all, bool forward, bool findnext)
326 {
327         odocstringstream ss;
328         ss << replace << '\n'
329            << search << '\n'
330            << int(casesensitive) << ' '
331            << int(matchword) << ' '
332            << int(all) << ' '
333            << int(forward) << ' '
334            << int(findnext);
335         return ss.str();
336 }
337
338
339 bool lyxfind(BufferView * bv, FuncRequest const & ev)
340 {
341         if (!bv || ev.action() != LFUN_WORD_FIND)
342                 return false;
343
344         //lyxerr << "find called, cmd: " << ev << endl;
345
346         // data is of the form
347         // "<search>
348         //  <casesensitive> <matchword> <forward>"
349         docstring search;
350         docstring howto = split(ev.argument(), search, '\n');
351
352         bool casesensitive = parse_bool(howto);
353         bool matchword     = parse_bool(howto);
354         bool forward       = parse_bool(howto);
355
356         return findOne(bv, search, casesensitive, matchword, forward, true, true);
357 }
358
359
360 bool lyxreplace(BufferView * bv,
361                 FuncRequest const & ev, bool has_deleted)
362 {
363         if (!bv || ev.action() != LFUN_WORD_REPLACE)
364                 return false;
365
366         // data is of the form
367         // "<search>
368         //  <replace>
369         //  <casesensitive> <matchword> <all> <forward> <findnext>"
370         docstring search;
371         docstring rplc;
372         docstring howto = split(ev.argument(), rplc, '\n');
373         howto = split(howto, search, '\n');
374
375         bool casesensitive = parse_bool(howto);
376         bool matchword     = parse_bool(howto);
377         bool all           = parse_bool(howto);
378         bool forward       = parse_bool(howto);
379         bool findnext      = howto.empty() ? true : parse_bool(howto);
380
381         bool update = false;
382
383         if (!has_deleted) {
384                 int replace_count = 0;
385                 if (all) {
386                         replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
387                         update = replace_count > 0;
388                 } else {
389                         pair<bool, int> rv =
390                                 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
391                         update = rv.first;
392                         replace_count = rv.second;
393                 }
394
395                 Buffer const & buf = bv->buffer();
396                 if (!update) {
397                         // emit message signal.
398                         buf.message(_("String not found."));
399                 } else {
400                         if (replace_count == 0) {
401                                 buf.message(_("String found."));
402                         } else if (replace_count == 1) {
403                                 buf.message(_("String has been replaced."));
404                         } else {
405                                 docstring const str =
406                                         bformat(_("%1$d strings have been replaced."), replace_count);
407                                 buf.message(str);
408                         }
409                 }
410         } else if (findnext) {
411                 // if we have deleted characters, we do not replace at all, but
412                 // rather search for the next occurence
413                 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
414                         update = true;
415                 else
416                         bv->message(_("String not found."));
417         }
418         return update;
419 }
420
421
422 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
423 {
424         for (; cur; cur.forwardPos())
425                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
426                         return true;
427
428         if (check_wrap) {
429                 DocIterator cur_orig(bv->cursor());
430                 docstring q = _("End of file reached while searching forward.\n"
431                           "Continue searching from the beginning?");
432                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
433                         q, 0, 1, _("&Yes"), _("&No"));
434                 if (wrap_answer == 0) {
435                         bv->cursor().clear();
436                         bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
437                         bv->clearSelection();
438                         cur.setCursor(bv->cursor().selectionBegin());
439                         if (findNextChange(bv, cur, false))
440                                 return true;
441                 }
442                 bv->cursor().setCursor(cur_orig);
443         }
444
445         return false;
446 }
447
448
449 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
450 {
451         for (cur.backwardPos(); cur; cur.backwardPos()) {
452                 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
453                         return true;
454         }
455
456         if (check_wrap) {
457                 DocIterator cur_orig(bv->cursor());
458                 docstring q = _("Beginning of file reached while searching backward.\n"
459                           "Continue searching from the end?");
460                 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
461                         q, 0, 1, _("&Yes"), _("&No"));
462                 if (wrap_answer == 0) {
463                         bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
464                         bv->cursor().backwardPos();
465                         bv->clearSelection();
466                         cur.setCursor(bv->cursor().selectionBegin());
467                         if (findPreviousChange(bv, cur, false))
468                                 return true;
469                 }
470                 bv->cursor().setCursor(cur_orig);
471         }
472
473         return false;
474 }
475
476
477 bool selectChange(Cursor & cur, bool forward)
478 {
479         if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
480                 return false;
481         Change ch = cur.paragraph().lookupChange(cur.pos());
482
483         CursorSlice tip1 = cur.top();
484         for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
485                 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
486                 if (!ch2.isSimilarTo(ch))
487                         break;
488         }
489         CursorSlice tip2 = cur.top();
490         for (; tip2.pit() > 0 || tip2.pos() > 0;) {
491                 tip2.backwardPos();
492                 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
493                 if (!ch2.isSimilarTo(ch)) {
494                         // take a step forward to correctly set the selection
495                         tip2.forwardPos();
496                         break;
497                 }
498         }
499         if (forward)
500                 swap(tip1, tip2);
501         cur.top() = tip1;
502         cur.bv().mouseSetCursor(cur, false);
503         cur.top() = tip2;
504         cur.bv().mouseSetCursor(cur, true);
505         return true;
506 }
507
508
509 namespace {
510
511
512 bool findChange(BufferView * bv, bool forward)
513 {
514         Cursor cur(*bv);
515         cur.setCursor(forward ? bv->cursor().selectionEnd()
516                       : bv->cursor().selectionBegin());
517         forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
518         return selectChange(cur, forward);
519 }
520
521 } // namespace
522
523 bool findNextChange(BufferView * bv)
524 {
525         return findChange(bv, true);
526 }
527
528
529 bool findPreviousChange(BufferView * bv)
530 {
531         return findChange(bv, false);
532 }
533
534
535
536 namespace {
537
538 typedef vector<pair<string, string> > Escapes;
539
540 /// A map of symbols and their escaped equivalent needed within a regex.
541 /// @note Beware of order
542 Escapes const & get_regexp_escapes()
543 {
544         typedef std::pair<std::string, std::string> P;
545
546         static Escapes escape_map;
547         if (escape_map.empty()) {
548                 escape_map.push_back(P("$", "_x_$"));
549                 escape_map.push_back(P("{", "_x_{"));
550                 escape_map.push_back(P("}", "_x_}"));
551                 escape_map.push_back(P("[", "_x_["));
552                 escape_map.push_back(P("]", "_x_]"));
553                 escape_map.push_back(P("(", "_x_("));
554                 escape_map.push_back(P(")", "_x_)"));
555                 escape_map.push_back(P("+", "_x_+"));
556                 escape_map.push_back(P("*", "_x_*"));
557                 escape_map.push_back(P(".", "_x_."));
558                 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
559                 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
560                 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
561                 escape_map.push_back(P("_x_", "\\"));
562         }
563         return escape_map;
564 }
565
566 /// A map of lyx escaped strings and their unescaped equivalent.
567 Escapes const & get_lyx_unescapes()
568 {
569         typedef std::pair<std::string, std::string> P;
570
571         static Escapes escape_map;
572         if (escape_map.empty()) {
573                 escape_map.push_back(P("\\%", "%"));
574                 escape_map.push_back(P("\\mathcircumflex ", "^"));
575                 escape_map.push_back(P("\\mathcircumflex", "^"));
576                 escape_map.push_back(P("\\backslash ", "\\"));
577                 escape_map.push_back(P("\\backslash", "\\"));
578                 escape_map.push_back(P("\\\\{", "_x_<"));
579                 escape_map.push_back(P("\\\\}", "_x_>"));
580                 escape_map.push_back(P("\\sim ", "~"));
581                 escape_map.push_back(P("\\sim", "~"));
582         }
583         return escape_map;
584 }
585
586 /// A map of escapes turning a regexp matching text to one matching latex.
587 Escapes const & get_regexp_latex_escapes()
588 {
589         typedef std::pair<std::string, std::string> P;
590
591         static Escapes escape_map;
592         if (escape_map.empty()) {
593                 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
594                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
595                 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
596                 escape_map.push_back(P("\\[", "\\{\\[\\}"));
597                 escape_map.push_back(P("\\]", "\\{\\]\\}"));
598                 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
599                 escape_map.push_back(P("%", "\\\\\\%"));
600         }
601         return escape_map;
602 }
603
604 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
605  ** the found occurrence were escaped.
606  **/
607 string apply_escapes(string s, Escapes const & escape_map)
608 {
609         LYXERR(Debug::FIND, "Escaping: '" << s << "'");
610         Escapes::const_iterator it;
611         for (it = escape_map.begin(); it != escape_map.end(); ++it) {
612 //              LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
613                 unsigned int pos = 0;
614                 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
615                         s.replace(pos, it->first.length(), it->second);
616                         LYXERR(Debug::FIND, "After escape: " << s);
617                         pos += it->second.length();
618 //                      LYXERR(Debug::FIND, "pos: " << pos);
619                 }
620         }
621         LYXERR(Debug::FIND, "Escaped : '" << s << "'");
622         return s;
623 }
624
625
626 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
627 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
628 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
629 string escape_for_regex(string s, bool match_latex)
630 {
631         size_t pos = 0;
632         while (pos < s.size()) {
633                 size_t new_pos = s.find("\\regexp{", pos);
634                 if (new_pos == string::npos)
635                         new_pos = s.size();
636                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
637                 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
638                 LYXERR(Debug::FIND, "t [lyx]: " << t);
639                 t = apply_escapes(t, get_regexp_escapes());
640                 LYXERR(Debug::FIND, "t [rxp]: " << t);
641                 s.replace(pos, new_pos - pos, t);
642                 new_pos = pos + t.size();
643                 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
644                 LYXERR(Debug::FIND, "new_pos: " << new_pos);
645                 if (new_pos == s.size())
646                         break;
647                 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
648                 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
649                 LYXERR(Debug::FIND, "end_pos: " << end_pos);
650                 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
651                 LYXERR(Debug::FIND, "t in regexp      : " << t);
652                 t = apply_escapes(t, get_lyx_unescapes());
653                 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
654                 if (match_latex) {
655                         t = apply_escapes(t, get_regexp_latex_escapes());
656                         LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
657                 }
658                 if (end_pos == s.size()) {
659                         s.replace(new_pos, end_pos - new_pos, t);
660                         LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
661                         break;
662                 }
663                 s.replace(new_pos, end_pos + 13 - new_pos, t);
664                 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
665                 pos = new_pos + t.size();
666                 LYXERR(Debug::FIND, "pos: " << pos);
667         }
668         return s;
669 }
670
671
672 /// Wrapper for lyx::regex_replace with simpler interface
673 bool regex_replace(string const & s, string & t, string const & searchstr,
674                    string const & replacestr)
675 {
676         lyx::regex e(searchstr, regex_constants::ECMAScript);
677         ostringstream oss;
678         ostream_iterator<char, char> it(oss);
679         lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
680         // tolerate t and s be references to the same variable
681         bool rv = (s != oss.str());
682         t = oss.str();
683         return rv;
684 }
685
686
687 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
688  **
689  ** Verify that closed braces exactly match open braces. This avoids that, for example,
690  ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
691  **
692  ** @param unmatched
693  ** Number of open braces that must remain open at the end for the verification to succeed.
694  **/
695 bool braces_match(string::const_iterator const & beg,
696                   string::const_iterator const & end,
697                   int unmatched = 0)
698 {
699         int open_pars = 0;
700         string::const_iterator it = beg;
701         LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
702         for (; it != end; ++it) {
703                 // Skip escaped braces in the count
704                 if (*it == '\\') {
705                         ++it;
706                         if (it == end)
707                                 break;
708                 } else if (*it == '{') {
709                         ++open_pars;
710                 } else if (*it == '}') {
711                         if (open_pars == 0) {
712                                 LYXERR(Debug::FIND, "Found unmatched closed brace");
713                                 return false;
714                         } else
715                                 --open_pars;
716                 }
717         }
718         if (open_pars != unmatched) {
719                 LYXERR(Debug::FIND, "Found " << open_pars
720                        << " instead of " << unmatched
721                        << " unmatched open braces at the end of count");
722                 return false;
723         }
724         LYXERR(Debug::FIND, "Braces match as expected");
725         return true;
726 }
727
728
729 /** The class performing a match between a position in the document and the FindAdvOptions.
730  **/
731 class MatchStringAdv {
732 public:
733         MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
734
735         /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
736          ** constructor as opt.search, under the opt.* options settings.
737          **
738          ** @param at_begin
739          **     If set, then match is searched only against beginning of text starting at cur.
740          **     If unset, then match is searched anywhere in text starting at cur.
741          **
742          ** @return
743          ** The length of the matching text, or zero if no match was found.
744          **/
745         int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
746
747 public:
748         /// buffer
749         lyx::Buffer * p_buf;
750         /// first buffer on which search was started
751         lyx::Buffer * const p_first_buf;
752         /// options
753         FindAndReplaceOptions const & opt;
754
755 private:
756         /// Auxiliary find method (does not account for opt.matchword)
757         int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
758
759         /** Normalize a stringified or latexified LyX paragraph.
760          **
761          ** Normalize means:
762          ** <ul>
763          **   <li>if search is not casesensitive, then lowercase the string;
764          **   <li>remove any newline at begin or end of the string;
765          **   <li>replace any newline in the middle of the string with a simple space;
766          **   <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
767          ** </ul>
768          **
769          ** @todo Normalization should also expand macros, if the corresponding
770          ** search option was checked.
771          **/
772         string normalize(docstring const & s, bool hack_braces) const;
773         // normalized string to search
774         string par_as_string;
775         // regular expression to use for searching
776         lyx::regex regexp;
777         // same as regexp, but prefixed with a ".*"
778         lyx::regex regexp2;
779         // leading format material as string
780         string lead_as_string;
781         // par_as_string after removal of lead_as_string
782         string par_as_string_nolead;
783         // unmatched open braces in the search string/regexp
784         int open_braces;
785         // number of (.*?) subexpressions added at end of search regexp for closing
786         // environments, math mode, styles, etc...
787         int close_wildcards;
788         // Are we searching with regular expressions ?
789         bool use_regexp;
790 };
791
792
793 static docstring buffer_to_latex(Buffer & buffer)
794 {
795         OutputParams runparams(&buffer.params().encoding());
796         odocstringstream ods;
797         otexstream os(ods);
798         runparams.nice = true;
799         runparams.flavor = OutputParams::LATEX;
800         runparams.linelen = 80; //lyxrc.plaintext_linelen;
801         // No side effect of file copying and image conversion
802         runparams.dryrun = true;
803         runparams.for_search = true;
804         pit_type const endpit = buffer.paragraphs().size();
805         for (pit_type pit = 0; pit != endpit; ++pit) {
806                 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
807                 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
808         }
809         return ods.str();
810 }
811
812
813 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
814 {
815         docstring str;
816         if (!opt.ignoreformat) {
817                 str = buffer_to_latex(buffer);
818         } else {
819                 OutputParams runparams(&buffer.params().encoding());
820                 runparams.nice = true;
821                 runparams.flavor = OutputParams::LATEX;
822                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
823                 runparams.dryrun = true;
824                 runparams.for_search = true;
825                 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
826                         Paragraph const & par = buffer.paragraphs().at(pit);
827                         LYXERR(Debug::FIND, "Adding to search string: '"
828                                << par.asString(pos_type(0), par.size(),
829                                                AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
830                                                &runparams)
831                                << "'");
832                         str += par.asString(pos_type(0), par.size(),
833                                             AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
834                                             &runparams);
835                 }
836         }
837         return str;
838 }
839
840
841 /// Return separation pos between the leading material and the rest
842 static size_t identifyLeading(string const & s)
843 {
844         string t = s;
845         // @TODO Support \item[text]
846         // Kornel: Added textsl, textsf, textit, texttt and noun
847         // + allow to seach for colored text too
848         while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)\\{", "")
849                || regex_replace(t, t, REGEX_BOS "\\$", "")
850                || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
851                || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
852                || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
853                ;
854         LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
855         return s.find(t);
856 }
857
858 typedef map<string, bool> Features;
859
860 static Features identifyFeatures(string const & s)
861 {
862         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
863         static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)$");
864         smatch sub;
865         bool displ = true;
866         Features info;
867
868         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
869                 sub = *it;
870                 if (displ) {
871                         if (sub.str(1).compare("regexp") == 0) {
872                                 displ = false;
873                                 continue;
874                         }
875                         string token = sub.str(1);
876                         smatch sub2;
877                         if (regex_match(token, sub2, valid)) {
878                                 info[token] = true;
879                         }
880                         else {
881                                 // ignore
882                         }
883                 }
884                 else {
885                         if (sub.str(1).compare("endregexp") == 0) {
886                                 displ = true;
887                                 continue;
888                         }
889                 }
890         }
891         return(info);
892 }
893
894 static int findclosing(string p, int start, int end)
895 {
896         int skip = 0;
897         int depth = 0;
898         for (int i = start; i < end; i += 1 + skip) {
899                 char c;
900                 c = p[i];
901                 skip = 0;
902                 if (c == '\\') skip = 1;
903                 else if (c == '{') depth++;
904                 else if (c == '}') {
905                         if (depth == 0) return(i);
906                         --depth;
907                 }
908         }
909         return(-1);
910 }
911
912
913 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
914 {
915         static string langstart = "\\foreignlanguage{";
916         static int llen = langstart.length();
917         static bool removefirstlang = false;
918         static Features regex_f;
919         static int missed = 0;
920         static bool regex_with_format = false;
921
922         int parlen = par.length();
923         string result = par;
924
925         while ((parlen > 0) && (par[parlen-1] == '\n')) {
926                 parlen--;
927         }
928         if (from_regex) {
929                 missed = 0;
930                 if (withformat) {
931                         regex_f = identifyFeatures(par);
932                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
933                                 string a = it->first;
934                                 regex_with_format = true;
935                                 // LYXERR0("Identified regex format:" << a);
936                         }
937
938                 }
939         } else if (regex_with_format) {
940                 Features info = identifyFeatures(par);
941                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
942                         string a = it->first;
943                         bool b = it->second;
944                         if (b && ! info[a]) {
945                                 missed++;
946                                 // LYXERR0("Missed(" << missed << ", srclen = " << parlen );
947                                 return("");
948                         }
949                 }
950         }
951         else {
952                 // LYXERR0("No regex formats");
953         }
954         if (par.compare(0, llen, langstart) == 0) {
955                 if (from_regex) {
956                         removefirstlang = false;
957                 }
958                 int i = findclosing(par, llen, par.length());
959                 if (removefirstlang) {
960                         if (i < 0)
961                                 result = "";
962                         else {
963                                 int closepos = findclosing(par, i+2, par.length());
964                                 if (closepos > 0) {
965                                         result = par.substr(i+2, closepos-i-2) + par.substr(closepos+1, parlen - closepos-1);
966                                 }
967                                 else {
968                                         result = par.substr(i+2, parlen-i-2);
969                                 }
970                         }
971                 }
972                 else if (i > 0) {
973                         // skip '}{' after the language spec
974                         int closepos = findclosing(par, i+2, par.length());
975                         size_t insertpos = par.find(langstart, i+2);
976                         if (closepos < 0) {
977                                 if (insertpos == string::npos) {
978                                         // there are no closing in par, and no next lang spec
979                                         result = par.substr(0, parlen) + "}";
980                                 }
981                                 else {
982                                         // Add '}' at insertpos only, because closing is missing
983                                         result = par.substr(0,insertpos) + "}" + par.substr(insertpos, parlen-insertpos);
984                                 }
985                         }
986                         else if ((size_t) closepos > insertpos) {
987                                 // Add '}' at insertpos and remove from closepos if closepos > insertpos
988                                 result = par.substr(0,insertpos) + "}" + par.substr(insertpos, closepos - insertpos) + par.substr(closepos+1, parlen -closepos-1);
989                         }
990                 }
991                 else {
992                         result = par;
993                         // For i == 0, it is empty language spec
994                         // and for i < 0 it is Error
995                 }
996         }
997         else {
998                 if (from_regex) {
999                         removefirstlang = true;
1000                 }
1001         }
1002         // remove possible \inputencoding entries
1003         while (regex_replace(result, result, "\\\\inputencoding\\{[^\\}]*}", ""))
1004                 ;
1005         // Either not found language spec,or is single and closed spec or empty
1006         return(result);
1007 }
1008
1009
1010 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1011 static int identifyClosing(string & t)
1012 {
1013         int open_braces = 0;
1014         do {
1015                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1016                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1017                         continue;
1018                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1019                         continue;
1020                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1021                         continue;
1022                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1023                         ++open_braces;
1024                         continue;
1025                 }
1026                 break;
1027         } while (true);
1028         return open_braces;
1029 }
1030
1031
1032 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1033         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1034 {
1035         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1036         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1037         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1038         // When using regexp, braces are hacked already by escape_for_regex()
1039         par_as_string = normalize(ds, !use_regexp);
1040         open_braces = 0;
1041         close_wildcards = 0;
1042
1043         size_t lead_size = 0;
1044         // correct the language settings
1045         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1046         if (opt.ignoreformat) {
1047                 if (!use_regexp) {
1048                         // if par_as_string_nolead were emty,
1049                         // the following call to findAux will always *find* the string
1050                         // in the checked data, and thus always using the slow
1051                         // examining of the current text part.
1052                         par_as_string_nolead = par_as_string;
1053                 }
1054         } else {
1055                 lead_size = identifyLeading(par_as_string);
1056                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1057                 lead_as_string = par_as_string.substr(0, lead_size);
1058                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1059         }
1060
1061         if (!use_regexp) {
1062                 open_braces = identifyClosing(par_as_string);
1063                 identifyClosing(par_as_string_nolead);
1064                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1065                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1066         } else {
1067                 string lead_as_regexp;
1068                 if (lead_size > 0) {
1069                         // @todo No need to search for \regexp{} insets in leading material
1070                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1071                         par_as_string = par_as_string_nolead;
1072                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1073                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1074                 }
1075                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1076                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1077                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1078                 if (
1079                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1080                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1081                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1082                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1083                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1084                         || regex_replace(par_as_string, par_as_string,
1085                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1086                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1087                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1088                         ) {
1089                         ++close_wildcards;
1090                 }
1091                 if (!opt.ignoreformat) {
1092                         // Remove extra '\}' at end
1093                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1094                                 open_braces++;
1095                         }
1096                         // save '\.'
1097                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1098                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1099                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1100                         // replace '[^...]' with '[^...\}\{\\]'
1101                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1102                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1103                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1104                         // restore '\.'
1105                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1106                 }
1107                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1108                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1109                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
1110                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1111
1112                 // If entered regexp must match at begin of searched string buffer
1113                 // Kornel: Added parentheses to use $1 for size of the leading string
1114                 string regexp_str;
1115                 string regexp2_str;
1116                 {
1117                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1118                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
1119                         // so the convert has no effect in that case
1120                         for (int i = 8; i > 0; --i) {
1121                                 string orig = "\\\\" + std::to_string(i);
1122                                 string dest = "\\" + std::to_string(i+1);
1123                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
1124                         }
1125                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1126                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1127                 }
1128                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1129                 regexp = lyx::regex(regexp_str);
1130
1131                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1132                 regexp2 = lyx::regex(regexp2_str);
1133         }
1134 }
1135
1136
1137 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1138 {
1139         if (at_begin &&
1140                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1141                 return 0;
1142
1143         docstring docstr = stringifyFromForSearch(opt, cur, len);
1144         string str = normalize(docstr, true);
1145         if (str.empty()) return(-1);
1146         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
1147         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1148
1149         if (use_regexp) {
1150                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1151                 regex const *p_regexp;
1152                 regex_constants::match_flag_type flags;
1153                 if (at_begin) {
1154                         flags = regex_constants::match_continuous;
1155                         p_regexp = &regexp;
1156                 } else {
1157                         flags = regex_constants::match_default;
1158                         p_regexp = &regexp2;
1159                 }
1160                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1161                 if (re_it == sregex_iterator())
1162                         return 0;
1163                 match_results<string::const_iterator> const & m = *re_it;
1164
1165                 if (0) { // Kornel Benko: DO NOT CHECKK
1166                         // Check braces on the segment that matched the entire regexp expression,
1167                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
1168                         if (!braces_match(m[0].first, m[0].second, open_braces))
1169                                 return 0;
1170                 }
1171
1172                 // Check braces on segments that matched all (.*?) subexpressions,
1173                 // except the last "padding" one inserted by lyx.
1174                 for (size_t i = 1; i < m.size() - 1; ++i)
1175                         if (!braces_match(m[i].first, m[i].second, open_braces))
1176                                 return 0;
1177
1178                 // Exclude from the returned match length any length
1179                 // due to close wildcards added at end of regexp
1180                 // and also the length of the leading (e.g. '\emph{')
1181                 //
1182                 // Whole found string, including the leading: m[0].second - m[0].first
1183                 // Size of the leading string: m[1].second - m[1].first
1184                 int leadingsize = 0;
1185                 if (m.size() > 1)
1186                         leadingsize = m[1].second - m[1].first;
1187                 int result;
1188                 if (close_wildcards == 0)
1189                         result = m[0].second - m[0].first;
1190
1191                 else
1192                         result =  m[m.size() - close_wildcards].first - m[0].first;
1193
1194                 if (result > leadingsize)
1195                         result -= leadingsize;
1196                 else
1197                         result = 0;
1198                 return(result);
1199         }
1200
1201         // else !use_regexp: but all code paths above return
1202         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1203                                  << par_as_string << "', str='" << str << "'");
1204         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1205                                  << lead_as_string << "', par_as_string_nolead='"
1206                                  << par_as_string_nolead << "'");
1207
1208         if (at_begin) {
1209                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1210                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1211                 if (str.substr(0, par_as_string.size()) == par_as_string)
1212                         return par_as_string.size();
1213         } else {
1214                 size_t pos = str.find(par_as_string_nolead);
1215                 if (pos != string::npos)
1216                         return par_as_string.size();
1217         }
1218         return 0;
1219 }
1220
1221
1222 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1223 {
1224         int res = findAux(cur, len, at_begin);
1225         LYXERR(Debug::FIND,
1226                "res=" << res << ", at_begin=" << at_begin
1227                << ", matchword=" << opt.matchword
1228                << ", inTexted=" << cur.inTexted());
1229         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1230                 return res;
1231         Paragraph const & par = cur.paragraph();
1232         bool ws_left = (cur.pos() > 0)
1233                 ? par.isWordSeparator(cur.pos() - 1)
1234                 : true;
1235         bool ws_right = (cur.pos() + res < par.size())
1236                 ? par.isWordSeparator(cur.pos() + res)
1237                 : true;
1238         LYXERR(Debug::FIND,
1239                "cur.pos()=" << cur.pos() << ", res=" << res
1240                << ", separ: " << ws_left << ", " << ws_right
1241                << endl);
1242         if (ws_left && ws_right)
1243                 return res;
1244         return 0;
1245 }
1246
1247
1248 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1249 {
1250         string t;
1251         if (! opt.casesensitive)
1252                 t = lyx::to_utf8(lowercase(s));
1253         else
1254                 t = lyx::to_utf8(s);
1255         // Remove \n at begin
1256         while (!t.empty() && t[0] == '\n')
1257                 t = t.substr(1);
1258         // Remove \n at end
1259         while (!t.empty() && t[t.size() - 1] == '\n')
1260                 t = t.substr(0, t.size() - 1);
1261         size_t pos;
1262         // Replace all other \n with spaces
1263         while ((pos = t.find("\n")) != string::npos)
1264                 t.replace(pos, 1, " ");
1265         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1266         // Kornel: Added textsl, textsf, textit, texttt and noun
1267         // + allow to seach for colored text too
1268         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1269         while (regex_replace(t, t, "\\\\((emph|noun|text(bf|sl|sf|it|tt|color\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)(\\{\\})+", ""))
1270                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1271
1272         while (regex_replace(t, t, "\\\\foreignlanguage\\{[a-z]+\\}(\\{(\\\\item )?\\})+", ""));
1273         // FIXME - check what preceeds the brace
1274         if (hack_braces) {
1275                 if (opt.ignoreformat)
1276                         while (regex_replace(t, t, "\\{", "_x_<")
1277                                || regex_replace(t, t, "\\}", "_x_>"))
1278                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1279                 else
1280                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1281                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1282                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1283         }
1284
1285         return t;
1286 }
1287
1288
1289 docstring stringifyFromCursor(DocIterator const & cur, int len)
1290 {
1291         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1292         if (cur.inTexted()) {
1293                 Paragraph const & par = cur.paragraph();
1294                 // TODO what about searching beyond/across paragraph breaks ?
1295                 // TODO Try adding a AS_STR_INSERTS as last arg
1296                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1297                         int(par.size()) : cur.pos() + len;
1298                 OutputParams runparams(&cur.buffer()->params().encoding());
1299                 runparams.nice = true;
1300                 runparams.flavor = OutputParams::LATEX;
1301                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1302                 // No side effect of file copying and image conversion
1303                 runparams.dryrun = true;
1304                 LYXERR(Debug::FIND, "Stringifying with cur: "
1305                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1306                 return par.asString(cur.pos(), end,
1307                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1308                         &runparams);
1309         } else if (cur.inMathed()) {
1310                 docstring s;
1311                 CursorSlice cs = cur.top();
1312                 MathData md = cs.cell();
1313                 MathData::const_iterator it_end =
1314                         (( len == -1 || cs.pos() + len > int(md.size()))
1315                          ? md.end()
1316                          : md.begin() + cs.pos() + len );
1317                 for (MathData::const_iterator it = md.begin() + cs.pos();
1318                      it != it_end; ++it)
1319                         s = s + asString(*it);
1320                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1321                 return s;
1322         }
1323         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1324         return docstring();
1325 }
1326
1327
1328 /** Computes the LaTeX export of buf starting from cur and ending len positions
1329  * after cur, if len is positive, or at the paragraph or innermost inset end
1330  * if len is -1.
1331  */
1332 docstring latexifyFromCursor(DocIterator const & cur, int len)
1333 {
1334         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1335         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1336                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1337         Buffer const & buf = *cur.buffer();
1338
1339         odocstringstream ods;
1340         otexstream os(ods);
1341         OutputParams runparams(&buf.params().encoding());
1342         runparams.nice = false;
1343         runparams.flavor = OutputParams::LATEX;
1344         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1345         // No side effect of file copying and image conversion
1346         runparams.dryrun = true;
1347         runparams.for_search = true;
1348
1349         if (cur.inTexted()) {
1350                 // @TODO what about searching beyond/across paragraph breaks ?
1351                 pos_type endpos = cur.paragraph().size();
1352                 if (len != -1 && endpos > cur.pos() + len)
1353                         endpos = cur.pos() + len;
1354                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1355                           string(), cur.pos(), endpos);
1356                 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1357                 string s = correctlanguagesetting(lyx::to_utf8(ods.str()), false, false);
1358                 LYXERR(Debug::FIND, "Latexified text: '" << s << "'");
1359                 return(lyx::from_utf8(s));
1360         } else if (cur.inMathed()) {
1361                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1362                 for (int s = cur.depth() - 1; s >= 0; --s) {
1363                         CursorSlice const & cs = cur[s];
1364                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1365                                 WriteStream ws(os);
1366                                 cs.asInsetMath()->asHullInset()->header_write(ws);
1367                                 break;
1368                         }
1369                 }
1370
1371                 CursorSlice const & cs = cur.top();
1372                 MathData md = cs.cell();
1373                 MathData::const_iterator it_end =
1374                         ((len == -1 || cs.pos() + len > int(md.size()))
1375                          ? md.end()
1376                          : md.begin() + cs.pos() + len);
1377                 for (MathData::const_iterator it = md.begin() + cs.pos();
1378                      it != it_end; ++it)
1379                         ods << asString(*it);
1380
1381                 // Retrieve the math environment type, and add '$' or '$]'
1382                 // or others (\end{equation}) accordingly
1383                 for (int s = cur.depth() - 1; s >= 0; --s) {
1384                         CursorSlice const & cs2 = cur[s];
1385                         InsetMath * inset = cs2.asInsetMath();
1386                         if (inset && inset->asHullInset()) {
1387                                 WriteStream ws(os);
1388                                 inset->asHullInset()->footer_write(ws);
1389                                 break;
1390                         }
1391                 }
1392                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1393         } else {
1394                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1395         }
1396         return ods.str();
1397 }
1398
1399
1400 /** Finalize an advanced find operation, advancing the cursor to the innermost
1401  ** position that matches, plus computing the length of the matching text to
1402  ** be selected
1403  **/
1404 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1405 {
1406         // Search the foremost position that matches (avoids find of entire math
1407         // inset when match at start of it)
1408         size_t d;
1409         DocIterator old_cur(cur.buffer());
1410         do {
1411                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1412                 d = cur.depth();
1413                 old_cur = cur;
1414                 cur.forwardPos();
1415         } while (cur && cur.depth() > d && match(cur) > 0);
1416         cur = old_cur;
1417         LASSERT(match(cur) > 0, return 0);
1418         LYXERR(Debug::FIND, "Ok");
1419
1420         // Compute the match length
1421         int len = 1;
1422         if (cur.pos() + len > cur.lastpos())
1423                 return 0;
1424         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1425         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
1426                 ++len;
1427                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1428         }
1429         // Length of matched text (different from len param)
1430         int old_len = match(cur, len);
1431         if (old_len < 0) old_len = 0;
1432         int new_len;
1433         // Greedy behaviour while matching regexps
1434         while ((new_len = match(cur, len + 1)) > old_len) {
1435                 ++len;
1436                 old_len = new_len;
1437                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
1438         }
1439         return len;
1440 }
1441
1442
1443 /// Finds forward
1444 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1445 {
1446         if (!cur)
1447                 return 0;
1448         static int max_missed = 0;
1449         while (!theApp()->longOperationCancelled() && cur) {
1450                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1451                 int match_len = match(cur, -1, false);
1452                 LYXERR(Debug::FIND, "match_len: " << match_len);
1453                 if (match_len > 0) {
1454                         int count = 0;
1455                         int match_len_zero_count = 0;
1456                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1457                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1458                                 int match_len2 = match(cur);
1459                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
1460                                 if (match_len2 > 0) {
1461                                         // Sometimes in finalize we understand it wasn't a match
1462                                         // and we need to continue the outest loop
1463                                         int len = findAdvFinalize(cur, match);
1464                                         if (len > 0) {
1465                                                 return len;
1466                                         }
1467                                 }
1468                                 if (match_len2 >= 0) {
1469                                         count = 0;
1470                                         if (match_len2 == 0)
1471                                                 match_len_zero_count++;
1472                                         else
1473                                                 match_len_zero_count = 0;
1474                                 }
1475                                 else {
1476                                         count++;
1477                                         if (count > max_missed) max_missed = count;
1478                                         if (count > 5) {
1479                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
1480                                                 break;
1481                                         }
1482                                 }
1483                         }
1484                         if (!cur)
1485                                 return 0;
1486                 }
1487                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
1488                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1489                         cur.forwardPar();
1490                 } else {
1491                         // This should exit nested insets, if any, or otherwise undefine the currsor.
1492                         cur.pos() = cur.lastpos();
1493                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1494                         cur.forwardPos();
1495                 }
1496         }
1497         return 0;
1498 }
1499
1500
1501 /// Find the most backward consecutive match within same paragraph while searching backwards.
1502 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1503 {
1504         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1505         DocIterator tmp_cur = cur;
1506         int len = findAdvFinalize(tmp_cur, match);
1507         Inset & inset = cur.inset();
1508         for (; cur != cur_begin; cur.backwardPos()) {
1509                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1510                 DocIterator new_cur = cur;
1511                 new_cur.backwardPos();
1512                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1513                         break;
1514                 int new_len = findAdvFinalize(new_cur, match);
1515                 if (new_len == len)
1516                         break;
1517                 len = new_len;
1518         }
1519         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1520         return len;
1521 }
1522
1523
1524 /// Finds backwards
1525 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1526 {
1527         if (! cur)
1528                 return 0;
1529         // Backup of original position
1530         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1531         if (cur == cur_begin)
1532                 return 0;
1533         cur.backwardPos();
1534         DocIterator cur_orig(cur);
1535         bool pit_changed = false;
1536         do {
1537                 cur.pos() = 0;
1538                 bool found_match = match(cur, -1, false);
1539
1540                 if (found_match) {
1541                         if (pit_changed)
1542                                 cur.pos() = cur.lastpos();
1543                         else
1544                                 cur.pos() = cur_orig.pos();
1545                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1546                         DocIterator cur_prev_iter;
1547                         do {
1548                                 found_match = match(cur);
1549                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1550                                        << found_match << ", cur: " << cur);
1551                                 if (found_match)
1552                                         return findMostBackwards(cur, match);
1553
1554                                 // Stop if begin of document reached
1555                                 if (cur == cur_begin)
1556                                         break;
1557                                 cur_prev_iter = cur;
1558                                 cur.backwardPos();
1559                         } while (true);
1560                 }
1561                 if (cur == cur_begin)
1562                         break;
1563                 if (cur.pit() > 0)
1564                         --cur.pit();
1565                 else
1566                         cur.backwardPos();
1567                 pit_changed = true;
1568         } while (!theApp()->longOperationCancelled());
1569         return 0;
1570 }
1571
1572
1573 } // namespace
1574
1575
1576 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1577                                  DocIterator const & cur, int len)
1578 {
1579         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
1580                 return docstring();
1581         if (!opt.ignoreformat)
1582                 return latexifyFromCursor(cur, len);
1583         else
1584                 return stringifyFromCursor(cur, len);
1585 }
1586
1587
1588 FindAndReplaceOptions::FindAndReplaceOptions(
1589         docstring const & find_buf_name, bool casesensitive,
1590         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1591         docstring const & repl_buf_name, bool keep_case,
1592         SearchScope scope, SearchRestriction restr)
1593         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1594           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1595           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1596 {
1597 }
1598
1599
1600 namespace {
1601
1602
1603 /** Check if 'len' letters following cursor are all non-lowercase */
1604 static bool allNonLowercase(Cursor const & cur, int len)
1605 {
1606         pos_type beg_pos = cur.selectionBegin().pos();
1607         pos_type end_pos = cur.selectionBegin().pos() + len;
1608         if (len > cur.lastpos() + 1 - beg_pos) {
1609                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1610                 len = cur.lastpos() + 1 - beg_pos;
1611                 end_pos = beg_pos + len;
1612         }
1613         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1614                 if (isLowerCase(cur.paragraph().getChar(pos)))
1615                         return false;
1616         return true;
1617 }
1618
1619
1620 /** Check if first letter is upper case and second one is lower case */
1621 static bool firstUppercase(Cursor const & cur)
1622 {
1623         char_type ch1, ch2;
1624         pos_type pos = cur.selectionBegin().pos();
1625         if (pos >= cur.lastpos() - 1) {
1626                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1627                 return false;
1628         }
1629         ch1 = cur.paragraph().getChar(pos);
1630         ch2 = cur.paragraph().getChar(pos + 1);
1631         bool result = isUpperCase(ch1) && isLowerCase(ch2);
1632         LYXERR(Debug::FIND, "firstUppercase(): "
1633                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1634                << ch2 << "(" << char(ch2) << ")"
1635                << ", result=" << result << ", cur=" << cur);
1636         return result;
1637 }
1638
1639
1640 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1641  **
1642  ** \fixme What to do with possible further paragraphs in replace buffer ?
1643  **/
1644 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1645 {
1646         ParagraphList::iterator pit = buffer.paragraphs().begin();
1647         LASSERT(pit->size() >= 1, /**/);
1648         pos_type right = pos_type(1);
1649         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1650         right = pit->size();
1651         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1652 }
1653
1654 } // namespace
1655
1656 ///
1657 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1658 {
1659         Cursor & cur = bv->cursor();
1660         if (opt.repl_buf_name == docstring()
1661             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
1662             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1663                 return;
1664
1665         DocIterator sel_beg = cur.selectionBegin();
1666         DocIterator sel_end = cur.selectionEnd();
1667         if (&sel_beg.inset() != &sel_end.inset()
1668             || sel_beg.pit() != sel_end.pit()
1669             || sel_beg.idx() != sel_end.idx())
1670                 return;
1671         int sel_len = sel_end.pos() - sel_beg.pos();
1672         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1673                << ", sel_len: " << sel_len << endl);
1674         if (sel_len == 0)
1675                 return;
1676         LASSERT(sel_len > 0, return);
1677
1678         if (!matchAdv(sel_beg, sel_len))
1679                 return;
1680
1681         // Build a copy of the replace buffer, adapted to the KeepCase option
1682         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1683         ostringstream oss;
1684         repl_buffer_orig.write(oss);
1685         string lyx = oss.str();
1686         Buffer repl_buffer("", false);
1687         repl_buffer.setUnnamed(true);
1688         LASSERT(repl_buffer.readString(lyx), return);
1689         if (opt.keep_case && sel_len >= 2) {
1690                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1691                 if (cur.inTexted()) {
1692                         if (firstUppercase(cur))
1693                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1694                         else if (allNonLowercase(cur, sel_len))
1695                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1696                 }
1697         }
1698         cap::cutSelection(cur, false);
1699         if (cur.inTexted()) {
1700                 repl_buffer.changeLanguage(
1701                         repl_buffer.language(),
1702                         cur.getFont().language());
1703                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1704                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1705                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1706                                         repl_buffer.params().documentClassPtr(),
1707                                         bv->buffer().errorList("Paste"));
1708                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1709                 sel_len = repl_buffer.paragraphs().begin()->size();
1710         } else if (cur.inMathed()) {
1711                 odocstringstream ods;
1712                 otexstream os(ods);
1713                 OutputParams runparams(&repl_buffer.params().encoding());
1714                 runparams.nice = false;
1715                 runparams.flavor = OutputParams::LATEX;
1716                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1717                 runparams.dryrun = true;
1718                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1719                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1720                 docstring repl_latex = ods.str();
1721                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1722                 string s;
1723                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1724                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1725                 repl_latex = from_utf8(s);
1726                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1727                 MathData ar(cur.buffer());
1728                 asArray(repl_latex, ar, Parse::NORMAL);
1729                 cur.insert(ar);
1730                 sel_len = ar.size();
1731                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1732         }
1733         if (cur.pos() >= sel_len)
1734                 cur.pos() -= sel_len;
1735         else
1736                 cur.pos() = 0;
1737         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1738         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1739         bv->processUpdateFlags(Update::Force);
1740 }
1741
1742
1743 /// Perform a FindAdv operation.
1744 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1745 {
1746         DocIterator cur;
1747         int match_len = 0;
1748
1749         // e.g., when invoking word-findadv from mini-buffer wither with
1750         //       wrong options syntax or before ever opening advanced F&R pane
1751         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1752                 return false;
1753
1754         try {
1755                 MatchStringAdv matchAdv(bv->buffer(), opt);
1756                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1757                 if (length > 0)
1758                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1759                 findAdvReplace(bv, opt, matchAdv);
1760                 cur = bv->cursor();
1761                 if (opt.forward)
1762                         match_len = findForwardAdv(cur, matchAdv);
1763                 else
1764                         match_len = findBackwardsAdv(cur, matchAdv);
1765         } catch (...) {
1766                 // This may only be raised by lyx::regex()
1767                 bv->message(_("Invalid regular expression!"));
1768                 return false;
1769         }
1770
1771         if (match_len == 0) {
1772                 bv->message(_("Match not found!"));
1773                 return false;
1774         }
1775
1776         bv->message(_("Match found!"));
1777
1778         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1779         bv->putSelectionAt(cur, match_len, !opt.forward);
1780
1781         return true;
1782 }
1783
1784
1785 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1786 {
1787         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1788            << opt.casesensitive << ' '
1789            << opt.matchword << ' '
1790            << opt.forward << ' '
1791            << opt.expandmacros << ' '
1792            << opt.ignoreformat << ' '
1793            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1794            << opt.keep_case << ' '
1795            << int(opt.scope) << ' '
1796            << int(opt.restr);
1797
1798         LYXERR(Debug::FIND, "built: " << os.str());
1799
1800         return os;
1801 }
1802
1803
1804 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1805 {
1806         LYXERR(Debug::FIND, "parsing");
1807         string s;
1808         string line;
1809         getline(is, line);
1810         while (line != "EOSS") {
1811                 if (! s.empty())
1812                         s = s + "\n";
1813                 s = s + line;
1814                 if (is.eof())   // Tolerate malformed request
1815                         break;
1816                 getline(is, line);
1817         }
1818         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1819         opt.find_buf_name = from_utf8(s);
1820         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1821         is.get();       // Waste space before replace string
1822         s = "";
1823         getline(is, line);
1824         while (line != "EOSS") {
1825                 if (! s.empty())
1826                         s = s + "\n";
1827                 s = s + line;
1828                 if (is.eof())   // Tolerate malformed request
1829                         break;
1830                 getline(is, line);
1831         }
1832         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1833         opt.repl_buf_name = from_utf8(s);
1834         is >> opt.keep_case;
1835         int i;
1836         is >> i;
1837         opt.scope = FindAndReplaceOptions::SearchScope(i);
1838         is >> i;
1839         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1840
1841         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1842                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1843                << opt.scope << ' ' << opt.restr);
1844         return is;
1845 }
1846
1847 } // namespace lyx