]> git.lyx.org Git - lyx.git/blob - src/lyxfind.cpp
5ffbad455474525f3613beb561449e235215f935
[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/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 /*
859  * Given a latexified string, retrieve some handled features
860  * The features of the regex will later be compared with the features
861  * of the searched text. If the regex features are not a
862  * subset of the analized, then, in not format ignoring search
863  * we can early stop the search in the relevant inset.
864  */
865 typedef map<string, bool> Features;
866
867 static Features identifyFeatures(string const & s)
868 {
869         static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
870         static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage)\\{[a-z]+\\})|item |(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)$");
871         smatch sub;
872         bool displ = true;
873         Features info;
874
875         for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
876                 sub = *it;
877                 if (displ) {
878                         if (sub.str(1).compare("regexp") == 0) {
879                                 displ = false;
880                                 continue;
881                         }
882                         string token = sub.str(1);
883                         smatch sub2;
884                         if (regex_match(token, sub2, valid)) {
885                                 info[token] = true;
886                         }
887                         else {
888                                 // ignore
889                         }
890                 }
891                 else {
892                         if (sub.str(1).compare("endregexp") == 0) {
893                                 displ = true;
894                                 continue;
895                         }
896                 }
897         }
898         return(info);
899 }
900
901 /*
902  * Faster search for the related closing parenthesis
903  */
904  static int findclosing(string p, int start, int end)
905 {
906         int skip = 0;
907         int depth = 0;
908         int lastunclosed = start-1;
909         for (int i = start; i < end; i += 1 + skip) {
910                 char c;
911                 c = p[i];
912                 skip = 0;
913                 if (c == '\\') skip = 1;
914                 else if (c == '{') {
915                   depth++;
916                   lastunclosed = i;
917                 }
918                 else if (c == '}') {
919                         if (depth == 0) return(i);
920                         --depth;
921                 }
922         }
923         return(0 - lastunclosed);
924 }
925
926 /*
927  * defines values features of a key "\\[a-z]+{"
928  */
929 class KeyInfo {
930  public:
931   enum KeyType {
932     isChar,
933     isMain,                             /* for \\foreignlanguage */
934     isRegex,
935     isStandard,
936     invalid,
937     doRemove,
938     leadRemove,
939     isIgnored                           /* to be ignored by creating infos */
940   };
941  KeyInfo(string key) : head(key) {};
942  KeyInfo()
943    : keytype(invalid),
944     head(""),
945     parenthesiscount(1)
946   {};
947  KeyInfo(KeyType type, int parcount)
948    : keytype(type),
949     parenthesiscount(parcount) {};
950   KeyType keytype;
951   string head;
952   int _tokensize;
953   int _tokenstart;
954   int _dataStart;
955   int _dataEnd;
956   int parenthesiscount;
957 };
958
959 class Border {
960  public:
961  Border(int l=0, int u=0) : low(l), upper(u) {};
962   int low;
963   int upper;
964 };
965
966 #define MAXOPENED 30
967 class Intervall {
968  public:
969  Intervall() : ignoreidx(-1), actualdeptindex(0) {};
970   string par;
971   int ignoreidx;
972   int depts[MAXOPENED];
973   int closes[MAXOPENED];
974   int actualdeptindex;
975   Border borders[2*MAXOPENED];
976   // int previousNotIgnored(int);
977   int nextNotIgnored(int);
978   void handleOpenP(int i);
979   void handleCloseP(int i, bool closingAllowed);
980   void resetOpenedP(int openPos);
981   void addIntervall(int upper);
982   void addIntervall(int low, int upper); /* if explicit */
983   void setForDefaultLang(int upTo);
984   int findclosing(int start, int end);
985   void handleParentheses(int lastpos, bool closingAllowed);
986   void output(ostringstream &os, int lastpos);
987   // string show(int lastpos);
988 };
989
990 void Intervall::setForDefaultLang(int upTo)
991 {
992   // Enable the use of first token again
993   if (ignoreidx >= 0) {
994     if (borders[0].low < upTo)
995       borders[0].low = upTo;
996     if (borders[0].upper < upTo)
997       borders[0].upper = upTo;
998   }
999 }
1000
1001 static void checkDepthIndex(int val)
1002 {
1003   static int maxdepthidx = MAXOPENED-2;
1004   if (val > maxdepthidx) {
1005     maxdepthidx = val;
1006     LYXERR0("maxdepthidx now " << val);
1007   }
1008 }
1009
1010 static void checkIgnoreIdx(int val)
1011 {
1012   static int maxignoreidx = 2*MAXOPENED - 4;
1013   if (val > maxignoreidx) {
1014     maxignoreidx = val;
1015     LYXERR0("maxignoreidx now " << val);
1016   }
1017 }
1018
1019 /*
1020  * Expand the region of ignored parts of the input latex string
1021  * The region is only relevant in output()
1022  */
1023 void Intervall::addIntervall(int low, int upper)
1024 {
1025   int idx;
1026   if (low == upper) return;
1027   for (idx = ignoreidx+1; idx > 0; --idx) {
1028     if (low > borders[idx-1].upper) {
1029       break;
1030     }
1031   }
1032   Border br(low, upper);
1033   if (idx > ignoreidx) {
1034     borders[idx] = br;
1035     ignoreidx = idx;
1036     checkIgnoreIdx(ignoreidx);
1037     return;
1038   }
1039   else {
1040     // Expand only if one of the new bound is inside the interwall
1041     // We know here that br.low > borders[idx-1].upper
1042     if (br.upper < borders[idx].low) {
1043       // We have to insert at this pos
1044       for (int i = ignoreidx+1; i > idx; --i) {
1045         borders[i] = borders[i-1];
1046       }
1047       borders[idx] = br;
1048       ignoreidx += 1;
1049       checkIgnoreIdx(ignoreidx);
1050       return;
1051     }
1052     // Here we know, that we are overlapping
1053     if (br.low > borders[idx].low)
1054       br.low = borders[idx].low;
1055     // check what has to be concatenated
1056     int count = 0;
1057     for (int i = idx; i <= ignoreidx; i++) {
1058       if (br.upper >= borders[i].low) {
1059         count++;
1060         if (br.upper < borders[i].upper)
1061           br.upper = borders[i].upper;
1062       }
1063       else {
1064         break;
1065       }
1066     }
1067     // count should be >= 1 here
1068     borders[idx] = br;
1069     if (count > 1) {
1070       for (int i = idx + count; i <= ignoreidx; i++) {
1071         borders[i-count+1] = borders[i];
1072       }
1073       ignoreidx -= count - 1;
1074       return;
1075     }
1076   }
1077 }
1078
1079 void Intervall::handleOpenP(int i)
1080 {
1081   actualdeptindex++;
1082   depts[actualdeptindex] = i+1;
1083   closes[actualdeptindex] = -1;
1084   checkDepthIndex(actualdeptindex);
1085 }
1086
1087 void Intervall::handleCloseP(int i, bool closingAllowed)
1088 {
1089   if (actualdeptindex <= 0) {
1090     if (closingAllowed) {
1091       // if we are at the very end
1092       addIntervall(i, i+1);
1093     }
1094     else {
1095       LYXERR(Debug::FIND, "Bad closing parenthesis in latex");  /* should never happen! */
1096     }
1097   }
1098   else {
1099     closes[actualdeptindex] = i+1;
1100     actualdeptindex--;
1101   }
1102 }
1103
1104 void Intervall::resetOpenedP(int openPos)
1105 {
1106   actualdeptindex = 1;
1107   depts[1] = openPos+1;
1108   closes[1] = -1;
1109 }
1110
1111 #if 0
1112 int Intervall::previousNotIgnored(int start)
1113 {
1114     int idx = 0;                          /* int intervalls */
1115     for (idx = ignoreidx; idx >= 0; --idx) {
1116       if (start > borders[idx].upper)
1117         return(start);
1118       if (start >= borders[idx].low)
1119         start = borders[idx].low-1;
1120     }
1121     return start;
1122 }
1123 #endif
1124
1125 int Intervall::nextNotIgnored(int start)
1126 {
1127     int idx = 0;                          /* int intervalls */
1128     for (idx = 0; idx <= ignoreidx; idx++) {
1129       if (start < borders[idx].low)
1130         return(start);
1131       if (start < borders[idx].upper)
1132         start = borders[idx].upper;
1133     }
1134     return start;
1135 }
1136
1137 typedef map<string, KeyInfo> KeysMap;
1138 typedef vector< KeyInfo> Entries;
1139 static KeysMap keys = map<string, KeyInfo>();
1140
1141 class LatexInfo {
1142  private:
1143   int entidx;
1144   Entries entries;
1145   KeyInfo analyze(string key);
1146   Intervall interval;
1147   void buildKeys();
1148   void buildEntries();
1149   void makeKey(const string &, KeyInfo);
1150   void processRegion(ostringstream &os, int start, int region_end);
1151  public:
1152  LatexInfo(string par) {
1153     interval.par = par;
1154     buildKeys();
1155     entries = vector<KeyInfo>();
1156     buildEntries();
1157   };
1158   int getFirstKey() {
1159     entidx = 0;
1160     if (entries.empty()) {
1161       return (-1);
1162     }
1163     return 0;
1164   };
1165   int getNextKey() {
1166     entidx++;
1167     if (int(entries.size()) > entidx) {
1168       return entidx;
1169     }
1170     else {
1171       return (-1);
1172     }
1173   };
1174   bool setNextKey(int idx) {
1175     if ((idx == entidx) && (entidx > 0)) {
1176       entidx--;
1177       return true;
1178     }
1179     else
1180       return(false);
1181   };
1182   int process(ostringstream &os, int actual, bool faking);
1183   // string show(int lastpos) { return interval.show(lastpos);};
1184   int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1185   KeyInfo &getKeyInfo(int keyinfo) {
1186     static KeyInfo invalidInfo = KeyInfo();
1187     if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1188       return invalidInfo;
1189     else
1190       return entries[keyinfo];
1191   };
1192 };
1193
1194
1195 int Intervall::findclosing(int start, int end)
1196 {
1197   int skip = 0;
1198   int depth = 0;
1199   for (int i = start; i < end; i += 1 + skip) {
1200     char c;
1201     c = par[i];
1202     skip = 0;
1203     if (c == '\\') skip = 1;
1204     else if (c == '{') {
1205       depth++;
1206     }
1207     else if (c == '}') {
1208       if (depth == 0) return(i);
1209       --depth;
1210     }
1211   }
1212   return(end);
1213 }
1214
1215 void LatexInfo::buildEntries()
1216 {
1217   static regex const rkeys("\\\\((([a-z]+)(\\{([a-z]+)\\}|\\*)?))([\\{ ])");
1218   smatch sub;
1219   bool evaluatingRegexp = false;
1220   KeyInfo found;
1221   for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1222     sub = *it;
1223     if (evaluatingRegexp) {
1224       if (sub.str(1).compare("endregexp") == 0) {
1225         evaluatingRegexp = false;
1226         // found._tokenstart already set
1227         found._dataEnd = sub.position(0) + 12;
1228         found._dataStart = found._tokenstart;
1229       }
1230     }
1231     else {
1232       if (keys.find(sub.str(3)) == keys.end()) {
1233         LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1234         continue;
1235       }
1236       found = keys[sub.str(3)];
1237       if (sub.str(3).compare("regexp") == 0) {
1238         evaluatingRegexp = true;
1239         found._tokenstart = sub.position(0);
1240         found._tokensize = 0;
1241         continue;
1242       }
1243     }
1244     // Handle the other params of key
1245     if (found.keytype == KeyInfo::isIgnored)
1246       continue;
1247     else if (found.keytype == KeyInfo::isRegex) {
1248     }
1249     else {
1250       found._tokenstart = sub.position(0);
1251       if (found.parenthesiscount == 0) {
1252         // Probably to be discarded
1253         if (interval.par[sub.position(0) + sub.str(3).length()] == ' ')
1254           found.head = "\\" + sub.str(3) + " ";
1255         else
1256           found.head = "\\" + sub.str(3);
1257         found._tokensize = found.head.length();
1258         found._dataStart = found._dataEnd;
1259       }
1260       else {
1261         if (found.parenthesiscount == 1)
1262           found.head = "\\" + sub.str(3) + "{";
1263         else if (found.parenthesiscount == 2) {
1264           found.head = sub.str(0);
1265           found._tokensize = found.head.length();
1266         }
1267         found._dataStart = found._tokenstart + found.head.length();
1268         found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1269       }
1270     }
1271     entries.push_back(found);
1272   }
1273 }
1274
1275 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI)
1276 {
1277   stringstream s(keysstring);
1278   string key;
1279   KeyInfo keyII(keyI);
1280   const char delim = '|';
1281   while (getline(s, key, delim)) {
1282     keys[key] = keyII;
1283   }
1284 }
1285
1286 void LatexInfo::buildKeys()
1287 {
1288   static bool keysBuilt = false;
1289
1290   if (keysBuilt) return;
1291   KeyInfo foreign = KeyInfo(KeyInfo::isMain,     2);
1292   KeyInfo standard = KeyInfo(KeyInfo::isStandard,1);
1293   KeyInfo regex = KeyInfo(KeyInfo::isRegex,      1);
1294   KeyInfo color = KeyInfo(KeyInfo::isStandard,   2);
1295   KeyInfo character = KeyInfo(KeyInfo::isChar,   1);
1296   KeyInfo toremove = KeyInfo(KeyInfo::doRemove,  1);
1297   KeyInfo leadremove = KeyInfo(KeyInfo::leadRemove,1);
1298   KeyInfo ignoreMe = KeyInfo(KeyInfo::isIgnored, 0);
1299
1300   // Know statdard keys with 1 parameter.
1301   // Split is done, if not at start of region
1302   makeKey("textsf|texttt|textbf|textit|emph|noun|uuline|uline|sout|xout|uwave",standard);
1303
1304   // Regex, split is always done
1305   makeKey("regexp",regex);
1306
1307   // Split is done, if not at start of region
1308   makeKey("textcolor",color);
1309
1310   // Split is done always.
1311   makeKey("foreignlanguage",foreign);
1312
1313   // Know charaters
1314   // No split
1315   makeKey("backslash|textbackslash",character);
1316
1317   // Known macros to remove (including their parameter)
1318   // No split
1319   makeKey("inputencoding|shortcut", toremove);
1320
1321   // Macros to remove, but let the parameter survive
1322   // No split
1323   toremove.parenthesiscount = 0;
1324   makeKey("url|href|menuitem|footnote|code", leadremove);
1325
1326   // Same effect as previous, parameter will survive (because there is no one anyway)
1327   // No split
1328   leadremove.parenthesiscount = 0;
1329   makeKey("noindent|footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", leadremove);
1330
1331   // Survives, like known character
1332   makeKey("lyx", ignoreMe);
1333   keysBuilt = true;
1334 }
1335
1336 /*
1337  * Keep the list of actual opened parentheses actual
1338  * (e.g. depth == 4 means there are 4 '{' not processed yet)
1339  */
1340 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1341 {
1342   int skip = 0;
1343   for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1344     char c;
1345     c = par[i];
1346     skip = 0;
1347     if (c == '\\') skip = 1;
1348     else if (c == '{') {
1349       handleOpenP(i);
1350     }
1351     else if (c == '}') {
1352       handleCloseP(i, closingAllowed);
1353     }
1354   }
1355 }
1356
1357 #if (0)
1358 string Intervall::show(int lastpos)
1359 {
1360   int idx = 0;                          /* int intervalls */
1361   int count = 0;
1362   string s;
1363   int i = 0;
1364   for (idx = 0; idx <= ignoreidx; idx++) {
1365     while (i < lastpos) {
1366       int printsize;
1367       if (i <= borders[idx].low) {
1368         if (borders[idx].low > lastpos)
1369           printsize = lastpos - i;
1370         else
1371           printsize = borders[idx].low - i;
1372         s += par.substr(i, printsize);
1373         i += printsize;
1374         if (i >= borders[idx].low)
1375           i = borders[idx].upper;
1376       }
1377       else {
1378         i = borders[idx].upper;
1379         break;
1380       }
1381     }
1382   }
1383   if (lastpos > i) {
1384     s += par.substr(i, lastpos-i);
1385   }
1386   return (s);
1387 }
1388 #endif
1389
1390 void Intervall::output(ostringstream &os, int lastpos)
1391 {
1392   // get number of chars to output
1393   int idx = 0;                          /* int intervalls */
1394   int i = 0;
1395   for (idx = 0; idx <= ignoreidx; idx++) {
1396     if (i < lastpos) {
1397       int printsize;
1398       if (i <= borders[idx].low) {
1399         if (borders[idx].low > lastpos)
1400           printsize = lastpos - i;
1401         else
1402           printsize = borders[idx].low - i;
1403         os << par.substr(i, printsize);
1404         i += printsize;
1405         handleParentheses(i, false);
1406         if (i >= borders[idx].low)
1407           i = borders[idx].upper;
1408       }
1409       else {
1410         i = borders[idx].upper;
1411       }
1412     }
1413     else
1414       break;
1415   }
1416   if (lastpos > i) {
1417     os << par.substr(i, lastpos-i);
1418   }
1419   handleParentheses(lastpos, false);
1420   for (int i = actualdeptindex; i > 0; --i) {
1421     os << "}";
1422   }
1423   handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1424 }
1425
1426 void LatexInfo::processRegion(ostringstream &os, int start, int region_end)
1427 {
1428   int old_start = start;
1429   while (start < region_end) {
1430     if (interval.par[start] == '{') {
1431       int closing = interval.findclosing(start+1, region_end);
1432       interval.addIntervall(start, start+1);
1433       interval.addIntervall(closing, closing+1);
1434     }
1435     start = interval.nextNotIgnored(start+1);
1436   }
1437   start = interval.nextNotIgnored(old_start);
1438   if (start < region_end) {
1439     interval.output(os, region_end);
1440     interval.addIntervall(start, region_end);
1441   }
1442 }
1443
1444 int LatexInfo::process(ostringstream &os, int actualidx, bool faking)
1445 {
1446   KeyInfo &actual = getKeyInfo(actualidx);
1447   int nextKeyIdx = getNextKey();
1448   int start, old_start;
1449   int end = interval.nextNotIgnored(actual._dataEnd);
1450   old_start = interval.nextNotIgnored(actual._dataStart);
1451   if (faking) {
1452     // Adapt for start of first open parenthesis
1453     interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1454   }
1455   if (actual.keytype == KeyInfo::isMain) {
1456     // Fake for opened braces
1457     interval.resetOpenedP(actual._dataStart-1);
1458   }
1459   while (true) {
1460     if ((nextKeyIdx < 0) ||
1461         (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1462         (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1463       processRegion(os, old_start, end);
1464       old_start = end+1;
1465       break;
1466     }
1467     KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1468     if (nextKey.keytype == KeyInfo::isMain) {
1469       end = nextKey._tokenstart;
1470       break;
1471     }
1472     switch (nextKey.keytype)
1473       {
1474       case KeyInfo::isChar: {
1475         old_start = nextKey._dataEnd+1;
1476         nextKeyIdx = getNextKey();
1477         break;
1478       }
1479       case KeyInfo::isStandard: {
1480         // Split on this key
1481         processRegion(os, old_start, nextKey._tokenstart);
1482         old_start = nextKey._dataEnd+1;
1483         nextKeyIdx = process(os, nextKeyIdx, false);
1484         break;
1485       }
1486       case KeyInfo::doRemove: {
1487         // Remove the key with all parameters
1488         interval.addIntervall(nextKey._tokenstart, nextKey._dataEnd+1);
1489         nextKeyIdx = getNextKey();
1490         break;
1491       }
1492       case KeyInfo::leadRemove: {
1493         // Disable output of header of this key
1494         // ( == remove header)
1495         if (nextKey.parenthesiscount == 0) {
1496           // "{\tiny{} ...}" ==> "{{} ...}"
1497           interval.addIntervall(nextKey._tokenstart, nextKey._tokenstart + nextKey._tokensize);
1498         }
1499         else {
1500           // Remove header hull, that is "\url{abcd}" ==> "abcd"
1501           interval.addIntervall(nextKey._tokenstart, nextKey._dataStart);
1502           interval.addIntervall(nextKey._dataEnd, nextKey._dataEnd+1);
1503         }
1504         nextKeyIdx = getNextKey();
1505         break;
1506       }
1507       case KeyInfo::isRegex: {
1508         // Copy regexp part as is
1509         // Split in any case
1510         processRegion(os, old_start, nextKey._tokenstart);
1511         // Now split on end of regexp{ ...} too
1512         interval.output(os, nextKey._dataEnd+1);
1513         old_start = nextKey._dataEnd+1;
1514         interval.addIntervall(nextKey._tokenstart, nextKey._dataEnd+1);
1515         nextKeyIdx = getNextKey();
1516         break;
1517       }
1518       default: {
1519         // LYXERR0("Unhandled keytype");
1520         nextKeyIdx = getNextKey();
1521         break;
1522       }
1523     }
1524   }
1525   // now nextKey is either invalid or is outside of actual._dataEnd
1526   // output the remaing and discard myself
1527   start = interval.nextNotIgnored(actual._dataStart);
1528   processRegion(os, start, end);
1529   if (interval.par[end] == '}') {
1530     end += 1;
1531     // This is the normal case.
1532     // But if using the firstlanguage, the closing may be missing
1533   }
1534   interval.addIntervall(actual._tokenstart, end);
1535   if (faking) {
1536     // Adapt for start of first open parenthesis
1537   }
1538   return nextKeyIdx;
1539 }
1540
1541 string splitOnKnownMacros(string par) {
1542   ostringstream os;
1543   LatexInfo li(par);
1544   int firstkeyIdx = li.getFirstKey();
1545   string s;
1546   if (firstkeyIdx >= 0) {
1547     int nextkeyIdx = li.process(os, firstkeyIdx, true);
1548     KeyInfo &firstKey = li.getKeyInfo(firstkeyIdx);
1549     while (nextkeyIdx >= 0) {
1550       // Check for a possible gap between the last
1551       // entry and this one
1552       int datastart = li.nextNotIgnored(firstKey._dataStart);
1553       KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1554       if (nextKey._tokenstart > datastart) {
1555         // Handle the gap
1556         firstKey._dataStart = datastart;
1557         firstKey._dataEnd = nextKey._tokenstart;
1558         (void) li.setNextKey(nextkeyIdx);
1559         // Fake the last opened parenthesis
1560         int testkey = li.process(os, firstkeyIdx, true); /* The returned key should be the same */
1561         if (testkey != nextkeyIdx) {
1562           LYXERR(Debug::FIND,"Something's wrong");
1563         }
1564       }
1565       else {
1566         if (nextKey.keytype != KeyInfo::isMain) {
1567           firstKey._dataStart = datastart;
1568           firstKey._dataEnd = nextKey._dataEnd+1;
1569           (void) li.setNextKey(nextkeyIdx);
1570           nextkeyIdx = li.process(os, firstkeyIdx, true);
1571         }
1572         else {
1573           nextkeyIdx = li.process(os, nextkeyIdx, false);
1574         }
1575       }
1576     }
1577     // Handle the remaining
1578     firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1579     firstKey._dataEnd = par.length();
1580     if (firstKey._dataStart +1 < firstKey._dataEnd)
1581       (void) li.process(os, firstkeyIdx, true);
1582     s = os.str();
1583   }
1584   else
1585     s = "";                        /* found end */
1586   return s;
1587 }
1588
1589 /*
1590  * Try to unify the language specs in the latexified text.
1591  * Resulting modified string is set to "", if
1592  * the searched tex does not contain all the features in the search pattern
1593  */
1594 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1595 {
1596         static Features regex_f;
1597         static int missed = 0;
1598         static bool regex_with_format = false;
1599
1600         int parlen = par.length();
1601
1602         while ((parlen > 0) && (par[parlen-1] == '\n')) {
1603                 parlen--;
1604         }
1605         string result;
1606         if (withformat) {
1607                 // Split the latex input into pieces which
1608                 // can be digested by our search engine
1609                 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1610                 result = splitOnKnownMacros(par);
1611                 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1612         }
1613         else
1614                 result = par.substr(0, parlen);
1615         bool handle_colors = false;
1616         if (from_regex) {
1617                 missed = 0;
1618                 if (withformat) {
1619                         regex_f = identifyFeatures(result);
1620                         string features = "";
1621                         for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1622                                 string a = it->first;
1623                                 regex_with_format = true;
1624                                 if (a.compare(0,10,"textcolor{") == 0)
1625                                   handle_colors = true;
1626                                 features += " " + a;
1627                                 // LYXERR0("Identified regex format:" << a);
1628                         }
1629                         LYXERR(Debug::FIND, "Identified Features" << features);
1630
1631                 }
1632         } else if (regex_with_format) {
1633                 Features info = identifyFeatures(result);
1634                 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1635                         string a = it->first;
1636                         bool b = it->second;
1637                         if (b && ! info[a]) {
1638                                 missed++;
1639                                 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1640                                 return("");
1641                         }
1642                         else if (a.compare(0,10,"textcolor{") == 0)
1643                                 handle_colors = true;
1644                 }
1645         }
1646         else {
1647                 // LYXERR0("No regex formats");
1648         }
1649         // remove possible disturbing macros
1650         while (regex_replace(result, result, "\\\\(noindent )", ""))
1651                 ;
1652         // Either not found language spec,or is single and closed spec or empty
1653         // to be removed
1654         // [a-z+]par
1655         static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1656
1657         list <string> pars;
1658         smatch sub;
1659         for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1660                 sub = *it;
1661                 string token = sub.str(1);
1662                 pars.push_back(token);
1663         }
1664         for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1665                 string token = *li;
1666                 int ti = result.find(token);
1667                 int tokensize = token.size() + 1;
1668                 if (ti >= 0) {
1669                         int tc = findclosing(result, ti + tokensize, result.size());
1670                         if (tc > 0)
1671                                 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1672
1673                 }
1674         }
1675         if (handle_colors) {
1676           while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1677           while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1678         }
1679         return(result);
1680 }
1681
1682
1683 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1684 static int identifyClosing(string & t)
1685 {
1686         int open_braces = 0;
1687         do {
1688                 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1689                 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1690                         continue;
1691                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1692                         continue;
1693                 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1694                         continue;
1695                 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1696                         ++open_braces;
1697                         continue;
1698                 }
1699                 break;
1700         } while (true);
1701         return open_braces;
1702 }
1703
1704
1705 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1706         : p_buf(&buf), p_first_buf(&buf), opt(opt)
1707 {
1708         Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1709         docstring const & ds = stringifySearchBuffer(find_buf, opt);
1710         use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1711         // When using regexp, braces are hacked already by escape_for_regex()
1712         par_as_string = normalize(ds, !use_regexp);
1713         open_braces = 0;
1714         close_wildcards = 0;
1715
1716         size_t lead_size = 0;
1717         // correct the language settings
1718         par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1719         if (opt.ignoreformat) {
1720                 if (!use_regexp) {
1721                         // if par_as_string_nolead were emty,
1722                         // the following call to findAux will always *find* the string
1723                         // in the checked data, and thus always using the slow
1724                         // examining of the current text part.
1725                         par_as_string_nolead = par_as_string;
1726                 }
1727         } else {
1728                 lead_size = identifyLeading(par_as_string);
1729                 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1730                 lead_as_string = par_as_string.substr(0, lead_size);
1731                 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1732         }
1733
1734         if (!use_regexp) {
1735                 open_braces = identifyClosing(par_as_string);
1736                 identifyClosing(par_as_string_nolead);
1737                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1738                 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1739         } else {
1740                 string lead_as_regexp;
1741                 if (lead_size > 0) {
1742                         // @todo No need to search for \regexp{} insets in leading material
1743                         lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1744                         par_as_string = par_as_string_nolead;
1745                         LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1746                         LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1747                 }
1748                 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1749                 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1750                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1751                 if (
1752                         // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1753                         regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1754                         // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1755                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1756                         // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1757                         || regex_replace(par_as_string, par_as_string,
1758                                          "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1759                         // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1760                         || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1761                         ) {
1762                         ++close_wildcards;
1763                 }
1764                 if (!opt.ignoreformat) {
1765                         // Remove extra '\}' at end
1766                         while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1767                                 open_braces++;
1768                         }
1769                         // save '\.'
1770                         regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1771                         // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1772                         regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1773                         // replace '[^...]' with '[^...\}\{\\]'
1774                         regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1775                         regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1776                         regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1777                         // restore '\.'
1778                         regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1779                 }
1780                 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1781                 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1782                 LYXERR(Debug::FIND, "Close .*?  : " << close_wildcards);
1783                 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1784
1785                 // If entered regexp must match at begin of searched string buffer
1786                 // Kornel: Added parentheses to use $1 for size of the leading string
1787                 string regexp_str;
1788                 string regexp2_str;
1789                 {
1790                         // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1791                         // Unfortunately is '\1', '\2', etc not working for strings with extra format
1792                         // so the convert has no effect in that case
1793                         for (int i = 8; i > 0; --i) {
1794                                 string orig = "\\\\" + std::to_string(i);
1795                                 string dest = "\\" + std::to_string(i+1);
1796                                 while (regex_replace(par_as_string, par_as_string, orig, dest));
1797                         }
1798                         regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1799                         regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1800                 }
1801                 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1802                 regexp = lyx::regex(regexp_str);
1803
1804                 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1805                 regexp2 = lyx::regex(regexp2_str);
1806         }
1807 }
1808
1809
1810 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1811 {
1812         if (at_begin &&
1813                 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1814                 return 0;
1815
1816         docstring docstr = stringifyFromForSearch(opt, cur, len);
1817         string str = normalize(docstr, true);
1818         if (!opt.ignoreformat) {
1819                 str = correctlanguagesetting(str, false, !opt.ignoreformat);
1820         }
1821         if (str.empty()) return(-1);
1822         LYXERR(Debug::FIND, "Matching against     '" << lyx::to_utf8(docstr) << "'");
1823         LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1824
1825         if (use_regexp) {
1826                 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1827                 regex const *p_regexp;
1828                 regex_constants::match_flag_type flags;
1829                 if (at_begin) {
1830                         flags = regex_constants::match_continuous;
1831                         p_regexp = &regexp;
1832                 } else {
1833                         flags = regex_constants::match_default;
1834                         p_regexp = &regexp2;
1835                 }
1836                 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1837                 if (re_it == sregex_iterator())
1838                         return 0;
1839                 match_results<string::const_iterator> const & m = *re_it;
1840
1841                 if (0) { // Kornel Benko: DO NOT CHECKK
1842                         // Check braces on the segment that matched the entire regexp expression,
1843                         // plus the last subexpression, if a (.*?) was inserted in the constructor.
1844                         if (!braces_match(m[0].first, m[0].second, open_braces))
1845                                 return 0;
1846                 }
1847
1848                 // Check braces on segments that matched all (.*?) subexpressions,
1849                 // except the last "padding" one inserted by lyx.
1850                 for (size_t i = 1; i < m.size() - 1; ++i)
1851                         if (!braces_match(m[i].first, m[i].second, open_braces))
1852                                 return 0;
1853
1854                 // Exclude from the returned match length any length
1855                 // due to close wildcards added at end of regexp
1856                 // and also the length of the leading (e.g. '\emph{')
1857                 //
1858                 // Whole found string, including the leading: m[0].second - m[0].first
1859                 // Size of the leading string: m[1].second - m[1].first
1860                 int leadingsize = 0;
1861                 if (m.size() > 1)
1862                         leadingsize = m[1].second - m[1].first;
1863                 int result;
1864                 for (size_t i = 0; i < m.size(); i++) {
1865                   LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
1866                 }
1867                 if (close_wildcards == 0)
1868                         result = m[0].second - m[0].first;
1869
1870                 else
1871                         result =  m[m.size() - close_wildcards].first - m[0].first;
1872
1873                 if (result > leadingsize)
1874                         result -= leadingsize;
1875                 else
1876                         result = 0;
1877                 return(result);
1878         }
1879
1880         // else !use_regexp: but all code paths above return
1881         LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1882                                  << par_as_string << "', str='" << str << "'");
1883         LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1884                                  << lead_as_string << "', par_as_string_nolead='"
1885                                  << par_as_string_nolead << "'");
1886
1887         if (at_begin) {
1888                 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1889                                          << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1890                 if (str.substr(0, par_as_string.size()) == par_as_string)
1891                         return par_as_string.size();
1892         } else {
1893                 size_t pos = str.find(par_as_string_nolead);
1894                 if (pos != string::npos)
1895                         return par_as_string.size();
1896         }
1897         return 0;
1898 }
1899
1900
1901 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1902 {
1903         int res = findAux(cur, len, at_begin);
1904         LYXERR(Debug::FIND,
1905                "res=" << res << ", at_begin=" << at_begin
1906                << ", matchword=" << opt.matchword
1907                << ", inTexted=" << cur.inTexted());
1908         if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1909                 return res;
1910         Paragraph const & par = cur.paragraph();
1911         bool ws_left = (cur.pos() > 0)
1912                 ? par.isWordSeparator(cur.pos() - 1)
1913                 : true;
1914         bool ws_right = (cur.pos() + res < par.size())
1915                 ? par.isWordSeparator(cur.pos() + res)
1916                 : true;
1917         LYXERR(Debug::FIND,
1918                "cur.pos()=" << cur.pos() << ", res=" << res
1919                << ", separ: " << ws_left << ", " << ws_right
1920                << endl);
1921         if (ws_left && ws_right)
1922                 return res;
1923         return 0;
1924 }
1925
1926
1927 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1928 {
1929         string t;
1930         if (! opt.casesensitive)
1931                 t = lyx::to_utf8(lowercase(s));
1932         else
1933                 t = lyx::to_utf8(s);
1934         // Remove \n at begin
1935         while (!t.empty() && t[0] == '\n')
1936                 t = t.substr(1);
1937         // Remove \n at end
1938         while (!t.empty() && t[t.size() - 1] == '\n')
1939                 t = t.substr(0, t.size() - 1);
1940         size_t pos;
1941         // Replace all other \n with spaces
1942         while ((pos = t.find("\n")) != string::npos)
1943                 t.replace(pos, 1, " ");
1944         // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1945         // Kornel: Added textsl, textsf, textit, texttt and noun
1946         // + allow to seach for colored text too
1947         LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1948         while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
1949                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1950         while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
1951                 LYXERR(Debug::FIND, "  further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1952
1953         while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
1954         // FIXME - check what preceeds the brace
1955         if (hack_braces) {
1956                 if (opt.ignoreformat)
1957                         while (regex_replace(t, t, "\\{", "_x_<")
1958                                || regex_replace(t, t, "\\}", "_x_>"))
1959                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1960                 else
1961                         while (regex_replace(t, t, "\\\\\\{", "_x_<")
1962                                || regex_replace(t, t, "\\\\\\}", "_x_>"))
1963                                 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1964         }
1965
1966         return t;
1967 }
1968
1969
1970 docstring stringifyFromCursor(DocIterator const & cur, int len)
1971 {
1972         LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1973         if (cur.inTexted()) {
1974                 Paragraph const & par = cur.paragraph();
1975                 // TODO what about searching beyond/across paragraph breaks ?
1976                 // TODO Try adding a AS_STR_INSERTS as last arg
1977                 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1978                         int(par.size()) : cur.pos() + len;
1979                 OutputParams runparams(&cur.buffer()->params().encoding());
1980                 runparams.nice = true;
1981                 runparams.flavor = OutputParams::LATEX;
1982                 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1983                 // No side effect of file copying and image conversion
1984                 runparams.dryrun = true;
1985                 LYXERR(Debug::FIND, "Stringifying with cur: "
1986                        << cur << ", from pos: " << cur.pos() << ", end: " << end);
1987                 return par.asString(cur.pos(), end,
1988                         AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1989                         &runparams);
1990         } else if (cur.inMathed()) {
1991                 docstring s;
1992                 CursorSlice cs = cur.top();
1993                 MathData md = cs.cell();
1994                 MathData::const_iterator it_end =
1995                         (( len == -1 || cs.pos() + len > int(md.size()))
1996                          ? md.end()
1997                          : md.begin() + cs.pos() + len );
1998                 for (MathData::const_iterator it = md.begin() + cs.pos();
1999                      it != it_end; ++it)
2000                         s = s + asString(*it);
2001                 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2002                 return s;
2003         }
2004         LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2005         return docstring();
2006 }
2007
2008
2009 /** Computes the LaTeX export of buf starting from cur and ending len positions
2010  * after cur, if len is positive, or at the paragraph or innermost inset end
2011  * if len is -1.
2012  */
2013 docstring latexifyFromCursor(DocIterator const & cur, int len)
2014 {
2015         LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2016         LYXERR(Debug::FIND, "  with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2017                << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2018         Buffer const & buf = *cur.buffer();
2019
2020         odocstringstream ods;
2021         otexstream os(ods);
2022         OutputParams runparams(&buf.params().encoding());
2023         runparams.nice = false;
2024         runparams.flavor = OutputParams::LATEX;
2025         runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2026         // No side effect of file copying and image conversion
2027         runparams.dryrun = true;
2028         runparams.for_search = true;
2029
2030         if (cur.inTexted()) {
2031                 // @TODO what about searching beyond/across paragraph breaks ?
2032                 pos_type endpos = cur.paragraph().size();
2033                 if (len != -1 && endpos > cur.pos() + len)
2034                         endpos = cur.pos() + len;
2035                 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2036                           string(), cur.pos(), endpos);
2037                 string s = lyx::to_utf8(ods.str());
2038                 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2039                 return(lyx::from_utf8(s));
2040         } else if (cur.inMathed()) {
2041                 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2042                 for (int s = cur.depth() - 1; s >= 0; --s) {
2043                         CursorSlice const & cs = cur[s];
2044                         if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2045                                 WriteStream ws(os);
2046                                 cs.asInsetMath()->asHullInset()->header_write(ws);
2047                                 break;
2048                         }
2049                 }
2050
2051                 CursorSlice const & cs = cur.top();
2052                 MathData md = cs.cell();
2053                 MathData::const_iterator it_end =
2054                         ((len == -1 || cs.pos() + len > int(md.size()))
2055                          ? md.end()
2056                          : md.begin() + cs.pos() + len);
2057                 for (MathData::const_iterator it = md.begin() + cs.pos();
2058                      it != it_end; ++it)
2059                         ods << asString(*it);
2060
2061                 // Retrieve the math environment type, and add '$' or '$]'
2062                 // or others (\end{equation}) accordingly
2063                 for (int s = cur.depth() - 1; s >= 0; --s) {
2064                         CursorSlice const & cs2 = cur[s];
2065                         InsetMath * inset = cs2.asInsetMath();
2066                         if (inset && inset->asHullInset()) {
2067                                 WriteStream ws(os);
2068                                 inset->asHullInset()->footer_write(ws);
2069                                 break;
2070                         }
2071                 }
2072                 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2073         } else {
2074                 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2075         }
2076         return ods.str();
2077 }
2078
2079
2080 /** Finalize an advanced find operation, advancing the cursor to the innermost
2081  ** position that matches, plus computing the length of the matching text to
2082  ** be selected
2083  **/
2084 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2085 {
2086         // Search the foremost position that matches (avoids find of entire math
2087         // inset when match at start of it)
2088         size_t d;
2089         DocIterator old_cur(cur.buffer());
2090         do {
2091                 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2092                 d = cur.depth();
2093                 old_cur = cur;
2094                 cur.forwardPos();
2095         } while (cur && cur.depth() > d && match(cur) > 0);
2096         cur = old_cur;
2097         if (match(cur) <= 0) return 0;
2098         LYXERR(Debug::FIND, "Ok");
2099
2100         // Compute the match length
2101         int len = 1;
2102         if (cur.pos() + len > cur.lastpos())
2103                 return 0;
2104         LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2105         while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2106                 ++len;
2107                 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2108         }
2109         // Length of matched text (different from len param)
2110         int old_len = match(cur, len);
2111         if (old_len < 0) old_len = 0;
2112         int new_len;
2113         // Greedy behaviour while matching regexps
2114         while ((new_len = match(cur, len + 1)) > old_len) {
2115                 ++len;
2116                 old_len = new_len;
2117                 LYXERR(Debug::FIND, "verifying   match with len = " << len);
2118         }
2119         return len;
2120 }
2121
2122
2123 /// Finds forward
2124 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2125 {
2126         if (!cur)
2127                 return 0;
2128         while (!theApp()->longOperationCancelled() && cur) {
2129                 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2130                 int match_len = match(cur, -1, false);
2131                 LYXERR(Debug::FIND, "match_len: " << match_len);
2132                 if (match_len > 0) {
2133                         int match_len_zero_count = 0;
2134                         for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2135                                 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2136                                 int match_len2 = match(cur);
2137                                 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2138                                 if (match_len2 > 0) {
2139                                         // Sometimes in finalize we understand it wasn't a match
2140                                         // and we need to continue the outest loop
2141                                         int len = findAdvFinalize(cur, match);
2142                                         if (len > 0) {
2143                                                 return len;
2144                                         }
2145                                 }
2146                                 if (match_len2 >= 0) {
2147                                         if (match_len2 == 0)
2148                                                 match_len_zero_count++;
2149                                         else
2150                                                 match_len_zero_count = 0;
2151                                 }
2152                                 else {
2153                                         if (++match_len_zero_count > 3) {
2154                                                 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2155                                                 match_len_zero_count = 0;
2156                                         }
2157                                         break;
2158                                 }
2159                         }
2160                         if (!cur)
2161                                 return 0;
2162                 }
2163                 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2164                         LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2165                         cur.forwardPar();
2166                 } else {
2167                         // This should exit nested insets, if any, or otherwise undefine the currsor.
2168                         cur.pos() = cur.lastpos();
2169                         LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2170                         cur.forwardPos();
2171                 }
2172         }
2173         return 0;
2174 }
2175
2176
2177 /// Find the most backward consecutive match within same paragraph while searching backwards.
2178 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2179 {
2180         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2181         DocIterator tmp_cur = cur;
2182         int len = findAdvFinalize(tmp_cur, match);
2183         Inset & inset = cur.inset();
2184         for (; cur != cur_begin; cur.backwardPos()) {
2185                 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2186                 DocIterator new_cur = cur;
2187                 new_cur.backwardPos();
2188                 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2189                         break;
2190                 int new_len = findAdvFinalize(new_cur, match);
2191                 if (new_len == len)
2192                         break;
2193                 len = new_len;
2194         }
2195         LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2196         return len;
2197 }
2198
2199
2200 /// Finds backwards
2201 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2202 {
2203         if (! cur)
2204                 return 0;
2205         // Backup of original position
2206         DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2207         if (cur == cur_begin)
2208                 return 0;
2209         cur.backwardPos();
2210         DocIterator cur_orig(cur);
2211         bool pit_changed = false;
2212         do {
2213                 cur.pos() = 0;
2214                 bool found_match = match(cur, -1, false);
2215
2216                 if (found_match) {
2217                         if (pit_changed)
2218                                 cur.pos() = cur.lastpos();
2219                         else
2220                                 cur.pos() = cur_orig.pos();
2221                         LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2222                         DocIterator cur_prev_iter;
2223                         do {
2224                                 found_match = match(cur);
2225                                 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2226                                        << found_match << ", cur: " << cur);
2227                                 if (found_match)
2228                                         return findMostBackwards(cur, match);
2229
2230                                 // Stop if begin of document reached
2231                                 if (cur == cur_begin)
2232                                         break;
2233                                 cur_prev_iter = cur;
2234                                 cur.backwardPos();
2235                         } while (true);
2236                 }
2237                 if (cur == cur_begin)
2238                         break;
2239                 if (cur.pit() > 0)
2240                         --cur.pit();
2241                 else
2242                         cur.backwardPos();
2243                 pit_changed = true;
2244         } while (!theApp()->longOperationCancelled());
2245         return 0;
2246 }
2247
2248
2249 } // namespace
2250
2251
2252 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2253                                  DocIterator const & cur, int len)
2254 {
2255         if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2256                 return docstring();
2257         if (!opt.ignoreformat)
2258                 return latexifyFromCursor(cur, len);
2259         else
2260                 return stringifyFromCursor(cur, len);
2261 }
2262
2263
2264 FindAndReplaceOptions::FindAndReplaceOptions(
2265         docstring const & find_buf_name, bool casesensitive,
2266         bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2267         docstring const & repl_buf_name, bool keep_case,
2268         SearchScope scope, SearchRestriction restr)
2269         : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2270           forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2271           repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2272 {
2273 }
2274
2275
2276 namespace {
2277
2278
2279 /** Check if 'len' letters following cursor are all non-lowercase */
2280 static bool allNonLowercase(Cursor const & cur, int len)
2281 {
2282         pos_type beg_pos = cur.selectionBegin().pos();
2283         pos_type end_pos = cur.selectionBegin().pos() + len;
2284         if (len > cur.lastpos() + 1 - beg_pos) {
2285                 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2286                 len = cur.lastpos() + 1 - beg_pos;
2287                 end_pos = beg_pos + len;
2288         }
2289         for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2290                 if (isLowerCase(cur.paragraph().getChar(pos)))
2291                         return false;
2292         return true;
2293 }
2294
2295
2296 /** Check if first letter is upper case and second one is lower case */
2297 static bool firstUppercase(Cursor const & cur)
2298 {
2299         char_type ch1, ch2;
2300         pos_type pos = cur.selectionBegin().pos();
2301         if (pos >= cur.lastpos() - 1) {
2302                 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2303                 return false;
2304         }
2305         ch1 = cur.paragraph().getChar(pos);
2306         ch2 = cur.paragraph().getChar(pos + 1);
2307         bool result = isUpperCase(ch1) && isLowerCase(ch2);
2308         LYXERR(Debug::FIND, "firstUppercase(): "
2309                << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2310                << ch2 << "(" << char(ch2) << ")"
2311                << ", result=" << result << ", cur=" << cur);
2312         return result;
2313 }
2314
2315
2316 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2317  **
2318  ** \fixme What to do with possible further paragraphs in replace buffer ?
2319  **/
2320 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2321 {
2322         ParagraphList::iterator pit = buffer.paragraphs().begin();
2323         LASSERT(pit->size() >= 1, /**/);
2324         pos_type right = pos_type(1);
2325         pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2326         right = pit->size();
2327         pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2328 }
2329
2330 } // namespace
2331
2332 ///
2333 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2334 {
2335         Cursor & cur = bv->cursor();
2336         if (opt.repl_buf_name == docstring()
2337             || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2338             || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2339                 return;
2340
2341         DocIterator sel_beg = cur.selectionBegin();
2342         DocIterator sel_end = cur.selectionEnd();
2343         if (&sel_beg.inset() != &sel_end.inset()
2344             || sel_beg.pit() != sel_end.pit()
2345             || sel_beg.idx() != sel_end.idx())
2346                 return;
2347         int sel_len = sel_end.pos() - sel_beg.pos();
2348         LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2349                << ", sel_len: " << sel_len << endl);
2350         if (sel_len == 0)
2351                 return;
2352         LASSERT(sel_len > 0, return);
2353
2354         if (!matchAdv(sel_beg, sel_len))
2355                 return;
2356
2357         // Build a copy of the replace buffer, adapted to the KeepCase option
2358         Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2359         ostringstream oss;
2360         repl_buffer_orig.write(oss);
2361         string lyx = oss.str();
2362         Buffer repl_buffer("", false);
2363         repl_buffer.setUnnamed(true);
2364         LASSERT(repl_buffer.readString(lyx), return);
2365         if (opt.keep_case && sel_len >= 2) {
2366                 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2367                 if (cur.inTexted()) {
2368                         if (firstUppercase(cur))
2369                                 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2370                         else if (allNonLowercase(cur, sel_len))
2371                                 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2372                 }
2373         }
2374         cap::cutSelection(cur, false);
2375         if (cur.inTexted()) {
2376                 repl_buffer.changeLanguage(
2377                         repl_buffer.language(),
2378                         cur.getFont().language());
2379                 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2380                 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2381                 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2382                                         repl_buffer.params().documentClassPtr(),
2383                                         bv->buffer().errorList("Paste"));
2384                 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2385                 sel_len = repl_buffer.paragraphs().begin()->size();
2386         } else if (cur.inMathed()) {
2387                 odocstringstream ods;
2388                 otexstream os(ods);
2389                 OutputParams runparams(&repl_buffer.params().encoding());
2390                 runparams.nice = false;
2391                 runparams.flavor = OutputParams::LATEX;
2392                 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2393                 runparams.dryrun = true;
2394                 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2395                 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2396                 docstring repl_latex = ods.str();
2397                 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2398                 string s;
2399                 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2400                 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2401                 repl_latex = from_utf8(s);
2402                 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2403                 MathData ar(cur.buffer());
2404                 asArray(repl_latex, ar, Parse::NORMAL);
2405                 cur.insert(ar);
2406                 sel_len = ar.size();
2407                 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2408         }
2409         if (cur.pos() >= sel_len)
2410                 cur.pos() -= sel_len;
2411         else
2412                 cur.pos() = 0;
2413         LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2414         bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2415         bv->processUpdateFlags(Update::Force);
2416 }
2417
2418
2419 /// Perform a FindAdv operation.
2420 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2421 {
2422         DocIterator cur;
2423         int match_len = 0;
2424
2425         // e.g., when invoking word-findadv from mini-buffer wither with
2426         //       wrong options syntax or before ever opening advanced F&R pane
2427         if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2428                 return false;
2429
2430         try {
2431                 MatchStringAdv matchAdv(bv->buffer(), opt);
2432                 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2433                 if (length > 0)
2434                         bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2435                 findAdvReplace(bv, opt, matchAdv);
2436                 cur = bv->cursor();
2437                 if (opt.forward)
2438                         match_len = findForwardAdv(cur, matchAdv);
2439                 else
2440                         match_len = findBackwardsAdv(cur, matchAdv);
2441         } catch (...) {
2442                 // This may only be raised by lyx::regex()
2443                 bv->message(_("Invalid regular expression!"));
2444                 return false;
2445         }
2446
2447         if (match_len == 0) {
2448                 bv->message(_("Match not found!"));
2449                 return false;
2450         }
2451
2452         bv->message(_("Match found!"));
2453
2454         LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2455         bv->putSelectionAt(cur, match_len, !opt.forward);
2456
2457         return true;
2458 }
2459
2460
2461 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2462 {
2463         os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2464            << opt.casesensitive << ' '
2465            << opt.matchword << ' '
2466            << opt.forward << ' '
2467            << opt.expandmacros << ' '
2468            << opt.ignoreformat << ' '
2469            << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2470            << opt.keep_case << ' '
2471            << int(opt.scope) << ' '
2472            << int(opt.restr);
2473
2474         LYXERR(Debug::FIND, "built: " << os.str());
2475
2476         return os;
2477 }
2478
2479
2480 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2481 {
2482         LYXERR(Debug::FIND, "parsing");
2483         string s;
2484         string line;
2485         getline(is, line);
2486         while (line != "EOSS") {
2487                 if (! s.empty())
2488                         s = s + "\n";
2489                 s = s + line;
2490                 if (is.eof())   // Tolerate malformed request
2491                         break;
2492                 getline(is, line);
2493         }
2494         LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2495         opt.find_buf_name = from_utf8(s);
2496         is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2497         is.get();       // Waste space before replace string
2498         s = "";
2499         getline(is, line);
2500         while (line != "EOSS") {
2501                 if (! s.empty())
2502                         s = s + "\n";
2503                 s = s + line;
2504                 if (is.eof())   // Tolerate malformed request
2505                         break;
2506                 getline(is, line);
2507         }
2508         LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2509         opt.repl_buf_name = from_utf8(s);
2510         is >> opt.keep_case;
2511         int i;
2512         is >> i;
2513         opt.scope = FindAndReplaceOptions::SearchScope(i);
2514         is >> i;
2515         opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2516
2517         LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2518                << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2519                << opt.scope << ' ' << opt.restr);
2520         return is;
2521 }
2522
2523 } // namespace lyx