3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
12 * Full author contact details are available in file CREDITS.
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
28 #include "output_latex.h"
29 #include "OutputParams.h"
30 #include "Paragraph.h"
34 #include "frontends/Application.h"
35 #include "frontends/alert.h"
37 #include "mathed/InsetMath.h"
38 #include "mathed/InsetMathHull.h"
39 #include "mathed/MathData.h"
40 #include "mathed/MathStream.h"
41 #include "mathed/MathSupport.h"
43 #include "support/debug.h"
44 #include "support/docstream.h"
45 #include "support/FileName.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49 #include "support/textutils.h"
55 using namespace lyx::support;
60 // Helper class for deciding what should be ignored
64 IgnoreFormats() = default;
66 bool getFamily() const { return ignoreFamily_; }
68 bool getSeries() const { return ignoreSeries_; }
70 bool getShape() const { return ignoreShape_; }
72 bool getUnderline() const { return ignoreUnderline_; }
74 bool getMarkUp() const { return ignoreMarkUp_; }
76 bool getStrikeOut() const { return ignoreStrikeOut_; }
78 bool getSectioning() const { return ignoreSectioning_; }
80 bool getFrontMatter() const { return ignoreFrontMatter_; }
82 bool getColor() const { return ignoreColor_; }
84 bool getLanguage() const { return ignoreLanguage_; }
86 void setIgnoreFormat(string const & type, bool value);
90 bool ignoreFamily_ = false;
92 bool ignoreSeries_ = false;
94 bool ignoreShape_ = false;
96 bool ignoreUnderline_ = false;
98 bool ignoreMarkUp_ = false;
100 bool ignoreStrikeOut_ = false;
102 bool ignoreSectioning_ = false;
104 bool ignoreFrontMatter_ = false;
106 bool ignoreColor_ = false;
108 bool ignoreLanguage_ = false;
112 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
114 if (type == "color") {
115 ignoreColor_ = value;
117 else if (type == "language") {
118 ignoreLanguage_ = value;
120 else if (type == "sectioning") {
121 ignoreSectioning_ = value;
122 ignoreFrontMatter_ = value;
124 else if (type == "font") {
125 ignoreSeries_ = value;
126 ignoreShape_ = value;
127 ignoreFamily_ = value;
129 else if (type == "series") {
130 ignoreSeries_ = value;
132 else if (type == "shape") {
133 ignoreShape_ = value;
135 else if (type == "family") {
136 ignoreFamily_ = value;
138 else if (type == "markup") {
139 ignoreMarkUp_ = value;
141 else if (type == "underline") {
142 ignoreUnderline_ = value;
144 else if (type == "strike") {
145 ignoreStrikeOut_ = value;
149 // The global variable that can be changed from outside
150 IgnoreFormats ignoreFormats;
153 void setIgnoreFormat(string const & type, bool value)
155 ignoreFormats.setIgnoreFormat(type, value);
161 bool parse_bool(docstring & howto)
166 howto = split(howto, var, ' ');
174 MatchString(docstring const & s, bool cs, bool mw)
175 : str(s), case_sens(cs), whole_words(mw)
178 // returns true if the specified string is at the specified position
179 // del specifies whether deleted strings in ct mode will be considered
180 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
182 return par.find(str, case_sens, whole_words, pos, del);
190 // match whole words only
195 int findForward(DocIterator & cur, MatchString const & match,
196 bool find_del = true)
198 for (; cur; cur.forwardChar())
199 if (cur.inTexted()) {
200 int len = match(cur.paragraph(), cur.pos(), find_del);
208 int findBackwards(DocIterator & cur, MatchString const & match,
209 bool find_del = true)
213 if (cur.inTexted()) {
214 int len = match(cur.paragraph(), cur.pos(), find_del);
223 bool searchAllowed(docstring const & str)
226 frontend::Alert::error(_("Search error"), _("Search string is empty"));
233 bool findOne(BufferView * bv, docstring const & searchstr,
234 bool case_sens, bool whole, bool forward,
235 bool find_del = true, bool check_wrap = false)
237 if (!searchAllowed(searchstr))
240 DocIterator cur = forward
241 ? bv->cursor().selectionEnd()
242 : bv->cursor().selectionBegin();
244 MatchString const match(searchstr, case_sens, whole);
246 int match_len = forward
247 ? findForward(cur, match, find_del)
248 : findBackwards(cur, match, find_del);
251 bv->putSelectionAt(cur, match_len, !forward);
252 else if (check_wrap) {
253 DocIterator cur_orig(bv->cursor());
256 q = _("End of file reached while searching forward.\n"
257 "Continue searching from the beginning?");
259 q = _("Beginning of file reached while searching backward.\n"
260 "Continue searching from the end?");
261 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
262 q, 0, 1, _("&Yes"), _("&No"));
263 if (wrap_answer == 0) {
265 bv->cursor().clear();
266 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
268 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
269 bv->cursor().backwardPos();
271 bv->clearSelection();
272 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
275 bv->cursor().setCursor(cur_orig);
279 return match_len > 0;
283 int replaceAll(BufferView * bv,
284 docstring const & searchstr, docstring const & replacestr,
285 bool case_sens, bool whole)
287 Buffer & buf = bv->buffer();
289 if (!searchAllowed(searchstr) || buf.isReadonly())
292 DocIterator cur_orig(bv->cursor());
294 MatchString const match(searchstr, case_sens, whole);
297 int const rsize = replacestr.size();
298 int const ssize = searchstr.size();
301 cur.setCursor(doc_iterator_begin(&buf));
302 int match_len = findForward(cur, match, false);
303 while (match_len > 0) {
304 // Backup current cursor position and font.
305 pos_type const pos = cur.pos();
306 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
308 int striked = ssize -
309 cur.paragraph().eraseChars(pos, pos + match_len,
310 buf.params().track_changes);
311 cur.paragraph().insert(pos, replacestr, font,
312 Change(buf.params().track_changes
314 : Change::UNCHANGED));
315 for (int i = 0; i < rsize + striked; ++i)
318 match_len = findForward(cur, match, false);
321 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
323 cur_orig.fixIfBroken();
324 bv->setCursor(cur_orig);
330 // the idea here is that we are going to replace the string that
331 // is selected IF it is the search string.
332 // if there is a selection, but it is not the search string, then
333 // we basically ignore it. (FIXME We ought to replace only within
335 // if there is no selection, then:
336 // (i) if some search string has been provided, then we find it.
337 // (think of how the dialog works when you hit "replace" the
339 // (ii) if no search string has been provided, then we treat the
340 // word the cursor is in as the search string. (why? i have no
341 // idea.) but this only works in text?
343 // returns the number of replacements made (one, if any) and
344 // whether anything at all was done.
345 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
346 docstring const & replacestr, bool case_sens,
347 bool whole, bool forward, bool findnext)
349 Cursor & cur = bv->cursor();
350 if (!cur.selection()) {
351 // no selection, non-empty search string: find it
352 if (!searchstr.empty()) {
353 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
354 return make_pair(found, 0);
356 // empty search string
359 return make_pair(false, 0);
360 // select current word and treat it as the search string.
361 // This causes a minor bug as undo will restore this selection,
362 // which the user did not create (#8986).
363 cur.innerText()->selectWord(cur, WHOLE_WORD);
364 searchstr = cur.selectionAsString(false);
367 // if we still don't have a search string, report the error
369 if (!searchAllowed(searchstr))
370 return make_pair(false, 0);
372 bool have_selection = cur.selection();
373 docstring const selected = cur.selectionAsString(false);
376 ? searchstr == selected
377 : compare_no_case(searchstr, selected) == 0;
379 // no selection or current selection is not search word:
380 // just find the search word
381 if (!have_selection || !match) {
382 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
383 return make_pair(found, 0);
386 // we're now actually ready to replace. if the buffer is
387 // read-only, we can't, though.
388 if (bv->buffer().isReadonly())
389 return make_pair(false, 0);
391 cap::replaceSelectionWithString(cur, replacestr);
393 cur.pos() += replacestr.length();
394 LASSERT(cur.pos() <= cur.lastpos(),
395 cur.pos() = cur.lastpos());
398 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
400 return make_pair(true, 1);
406 docstring const find2string(docstring const & search,
407 bool casesensitive, bool matchword, bool forward)
411 << int(casesensitive) << ' '
412 << int(matchword) << ' '
418 docstring const replace2string(docstring const & replace,
419 docstring const & search,
420 bool casesensitive, bool matchword,
421 bool all, bool forward, bool findnext)
424 ss << replace << '\n'
426 << int(casesensitive) << ' '
427 << int(matchword) << ' '
429 << int(forward) << ' '
435 bool lyxfind(BufferView * bv, FuncRequest const & ev)
437 if (!bv || ev.action() != LFUN_WORD_FIND)
440 //lyxerr << "find called, cmd: " << ev << endl;
442 // data is of the form
444 // <casesensitive> <matchword> <forward>"
446 docstring howto = split(ev.argument(), search, '\n');
448 bool casesensitive = parse_bool(howto);
449 bool matchword = parse_bool(howto);
450 bool forward = parse_bool(howto);
452 return findOne(bv, search, casesensitive, matchword, forward, true, true);
456 bool lyxreplace(BufferView * bv,
457 FuncRequest const & ev, bool has_deleted)
459 if (!bv || ev.action() != LFUN_WORD_REPLACE)
462 // data is of the form
465 // <casesensitive> <matchword> <all> <forward> <findnext>"
468 docstring howto = split(ev.argument(), rplc, '\n');
469 howto = split(howto, search, '\n');
471 bool casesensitive = parse_bool(howto);
472 bool matchword = parse_bool(howto);
473 bool all = parse_bool(howto);
474 bool forward = parse_bool(howto);
475 bool findnext = howto.empty() ? true : parse_bool(howto);
480 int replace_count = 0;
482 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
483 update = replace_count > 0;
486 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
488 replace_count = rv.second;
491 Buffer const & buf = bv->buffer();
493 // emit message signal.
494 buf.message(_("String not found."));
496 if (replace_count == 0) {
497 buf.message(_("String found."));
498 } else if (replace_count == 1) {
499 buf.message(_("String has been replaced."));
501 docstring const str =
502 bformat(_("%1$d strings have been replaced."), replace_count);
506 } else if (findnext) {
507 // if we have deleted characters, we do not replace at all, but
508 // rather search for the next occurence
509 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
512 bv->message(_("String not found."));
518 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
520 for (; cur; cur.forwardPos())
521 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
525 DocIterator cur_orig(bv->cursor());
526 docstring q = _("End of file reached while searching forward.\n"
527 "Continue searching from the beginning?");
528 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
529 q, 0, 1, _("&Yes"), _("&No"));
530 if (wrap_answer == 0) {
531 bv->cursor().clear();
532 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
533 bv->clearSelection();
534 cur.setCursor(bv->cursor().selectionBegin());
535 if (findNextChange(bv, cur, false))
538 bv->cursor().setCursor(cur_orig);
545 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
547 for (cur.backwardPos(); cur; cur.backwardPos()) {
548 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
553 DocIterator cur_orig(bv->cursor());
554 docstring q = _("Beginning of file reached while searching backward.\n"
555 "Continue searching from the end?");
556 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
557 q, 0, 1, _("&Yes"), _("&No"));
558 if (wrap_answer == 0) {
559 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
560 bv->cursor().backwardPos();
561 bv->clearSelection();
562 cur.setCursor(bv->cursor().selectionBegin());
563 if (findPreviousChange(bv, cur, false))
566 bv->cursor().setCursor(cur_orig);
573 bool selectChange(Cursor & cur, bool forward)
575 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
577 Change ch = cur.paragraph().lookupChange(cur.pos());
579 CursorSlice tip1 = cur.top();
580 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
581 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
582 if (!ch2.isSimilarTo(ch))
585 CursorSlice tip2 = cur.top();
586 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
588 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
589 if (!ch2.isSimilarTo(ch)) {
590 // take a step forward to correctly set the selection
598 cur.bv().mouseSetCursor(cur, false);
600 cur.bv().mouseSetCursor(cur, true);
608 bool findChange(BufferView * bv, bool forward)
611 cur.setCursor(forward ? bv->cursor().selectionEnd()
612 : bv->cursor().selectionBegin());
613 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
614 return selectChange(cur, forward);
619 bool findNextChange(BufferView * bv)
621 return findChange(bv, true);
625 bool findPreviousChange(BufferView * bv)
627 return findChange(bv, false);
634 typedef vector<pair<string, string> > Escapes;
636 /// A map of symbols and their escaped equivalent needed within a regex.
637 /// @note Beware of order
638 Escapes const & get_regexp_escapes()
640 typedef std::pair<std::string, std::string> P;
642 static Escapes escape_map;
643 if (escape_map.empty()) {
644 escape_map.push_back(P("$", "_x_$"));
645 escape_map.push_back(P("{", "_x_{"));
646 escape_map.push_back(P("}", "_x_}"));
647 escape_map.push_back(P("[", "_x_["));
648 escape_map.push_back(P("]", "_x_]"));
649 escape_map.push_back(P("(", "_x_("));
650 escape_map.push_back(P(")", "_x_)"));
651 escape_map.push_back(P("+", "_x_+"));
652 escape_map.push_back(P("*", "_x_*"));
653 escape_map.push_back(P(".", "_x_."));
654 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
655 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
656 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
657 escape_map.push_back(P("_x_", "\\"));
662 /// A map of lyx escaped strings and their unescaped equivalent.
663 Escapes const & get_lyx_unescapes()
665 typedef std::pair<std::string, std::string> P;
667 static Escapes escape_map;
668 if (escape_map.empty()) {
669 escape_map.push_back(P("\\%", "%"));
670 escape_map.push_back(P("\\mathcircumflex ", "^"));
671 escape_map.push_back(P("\\mathcircumflex", "^"));
672 escape_map.push_back(P("\\backslash ", "\\"));
673 escape_map.push_back(P("\\backslash", "\\"));
674 escape_map.push_back(P("\\\\{", "_x_<"));
675 escape_map.push_back(P("\\\\}", "_x_>"));
676 escape_map.push_back(P("\\sim ", "~"));
677 escape_map.push_back(P("\\sim", "~"));
682 /// A map of escapes turning a regexp matching text to one matching latex.
683 Escapes const & get_regexp_latex_escapes()
685 typedef std::pair<std::string, std::string> P;
687 static Escapes escape_map;
688 if (escape_map.empty()) {
689 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
690 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
691 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
692 escape_map.push_back(P("\\[", "\\{\\[\\}"));
693 escape_map.push_back(P("\\]", "\\{\\]\\}"));
694 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
695 escape_map.push_back(P("%", "\\\\\\%"));
696 escape_map.push_back(P("#", "\\\\#"));
701 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
702 ** the found occurrence were escaped.
704 string apply_escapes(string s, Escapes const & escape_map)
706 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
707 Escapes::const_iterator it;
708 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
709 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
710 unsigned int pos = 0;
711 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
712 s.replace(pos, it->first.length(), it->second);
713 LYXERR(Debug::FIND, "After escape: " << s);
714 pos += it->second.length();
715 // LYXERR(Debug::FIND, "pos: " << pos);
718 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
723 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
724 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
725 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
726 string escape_for_regex(string s, bool match_latex)
729 while (pos < s.size()) {
730 size_t new_pos = s.find("\\regexp{", pos);
731 if (new_pos == string::npos)
735 LYXERR(Debug::FIND, "new_pos: " << new_pos);
736 t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
737 LYXERR(Debug::FIND, "t [lyx]: " << t);
738 t = apply_escapes(t, get_regexp_escapes());
739 LYXERR(Debug::FIND, "t [rxp]: " << t);
740 s.replace(pos, new_pos - pos, t);
741 new_pos = pos + t.size();
742 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
743 LYXERR(Debug::FIND, "new_pos: " << new_pos);
744 if (new_pos == s.size())
747 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
748 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
749 LYXERR(Debug::FIND, "end_pos: " << end_pos);
750 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
751 LYXERR(Debug::FIND, "t in regexp : " << t);
752 t = apply_escapes(t, get_lyx_unescapes());
753 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
755 t = apply_escapes(t, get_regexp_latex_escapes());
756 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
758 if (end_pos == s.size()) {
759 s.replace(new_pos, end_pos - new_pos, t);
760 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
763 s.replace(new_pos, end_pos + 13 - new_pos, t);
764 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
765 pos = new_pos + t.size();
766 LYXERR(Debug::FIND, "pos: " << pos);
772 /// Wrapper for lyx::regex_replace with simpler interface
773 bool regex_replace(string const & s, string & t, string const & searchstr,
774 string const & replacestr)
776 regex e(searchstr, regex_constants::ECMAScript);
778 ostream_iterator<char, char> it(oss);
779 regex_replace(it, s.begin(), s.end(), e, replacestr);
780 // tolerate t and s be references to the same variable
781 bool rv = (s != oss.str());
787 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
789 ** Verify that closed braces exactly match open braces. This avoids that, for example,
790 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
793 ** Number of open braces that must remain open at the end for the verification to succeed.
795 bool braces_match(string::const_iterator const & beg,
796 string::const_iterator const & end,
800 string::const_iterator it = beg;
801 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
802 for (; it != end; ++it) {
803 // Skip escaped braces in the count
808 } else if (*it == '{') {
810 } else if (*it == '}') {
811 if (open_pars == 0) {
812 LYXERR(Debug::FIND, "Found unmatched closed brace");
818 if (open_pars != unmatched) {
819 LYXERR(Debug::FIND, "Found " << open_pars
820 << " instead of " << unmatched
821 << " unmatched open braces at the end of count");
824 LYXERR(Debug::FIND, "Braces match as expected");
834 MatchResult(): match_len(0),match2end(0), pos(0) {};
837 /** The class performing a match between a position in the document and the FindAdvOptions.
839 class MatchStringAdv {
841 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
843 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
844 ** constructor as opt.search, under the opt.* options settings.
847 ** If set, then match is searched only against beginning of text starting at cur.
848 ** If unset, then match is searched anywhere in text starting at cur.
851 ** The length of the matching text, or zero if no match was found.
853 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
858 /// first buffer on which search was started
859 lyx::Buffer * const p_first_buf;
861 FindAndReplaceOptions const & opt;
864 /// Auxiliary find method (does not account for opt.matchword)
865 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
867 /** Normalize a stringified or latexified LyX paragraph.
871 ** <li>if search is not casesensitive, then lowercase the string;
872 ** <li>remove any newline at begin or end of the string;
873 ** <li>replace any newline in the middle of the string with a simple space;
874 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
877 ** @todo Normalization should also expand macros, if the corresponding
878 ** search option was checked.
880 string normalize(docstring const & s, bool hack_braces) const;
881 // normalized string to search
882 string par_as_string;
883 // regular expression to use for searching
885 // same as regexp, but prefixed with a ".*?"
887 // leading format material as string
888 string lead_as_string;
889 // par_as_string after removal of lead_as_string
890 string par_as_string_nolead;
891 // unmatched open braces in the search string/regexp
893 // number of (.*?) subexpressions added at end of search regexp for closing
894 // environments, math mode, styles, etc...
896 // Are we searching with regular expressions ?
901 static docstring buffer_to_latex(Buffer & buffer)
903 //OutputParams runparams(&buffer.params().encoding());
904 OutputParams runparams(encodings.fromLyXName("utf8"));
905 odocstringstream ods;
907 runparams.nice = true;
908 runparams.flavor = Flavor::XeTeX;
909 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
910 // No side effect of file copying and image conversion
911 runparams.dryrun = true;
912 runparams.for_search = true;
913 pit_type const endpit = buffer.paragraphs().size();
914 for (pit_type pit = 0; pit != endpit; ++pit) {
915 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
916 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
922 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
925 if (!opt.ignoreformat) {
926 str = buffer_to_latex(buffer);
928 // OutputParams runparams(&buffer.params().encoding());
929 OutputParams runparams(encodings.fromLyXName("utf8"));
930 runparams.nice = true;
931 runparams.flavor = Flavor::XeTeX;
932 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
933 runparams.dryrun = true;
934 runparams.for_search = true;
935 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
936 Paragraph const & par = buffer.paragraphs().at(pit);
937 LYXERR(Debug::FIND, "Adding to search string: '"
938 << par.asString(pos_type(0), par.size(),
939 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
942 str += par.asString(pos_type(0), par.size(),
943 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
951 /// Return separation pos between the leading material and the rest
952 static size_t identifyLeading(string const & s)
955 // @TODO Support \item[text]
956 // Kornel: Added textsl, textsf, textit, texttt and noun
957 // + allow to search for colored text too
958 while (regex_replace(t, t, "^\\\\(((footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|emph|noun|minisec|text(bf|md|sl|sf|it|tt))|((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
959 || regex_replace(t, t, "^\\$", "")
960 || regex_replace(t, t, "^\\\\\\[", "")
961 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
962 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
964 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
969 * Given a latexified string, retrieve some handled features
970 * The features of the regex will later be compared with the features
971 * of the searched text. If the regex features are not a
972 * subset of the analized, then, in not format ignoring search
973 * we can early stop the search in the relevant inset.
975 typedef map<string, bool> Features;
977 static Features identifyFeatures(string const & s)
979 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
980 static regex const valid("^("
982 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
983 "emph|noun|text(bf|md|sl|sf|it|tt)|"
984 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
985 "(u|uu)line|(s|x)out|uwave|"
986 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
987 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
992 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
995 if (sub.str(1).compare("regexp") == 0) {
999 string token = sub.str(1);
1001 if (regex_match(token, sub2, valid)) {
1009 if (sub.str(1).compare("endregexp") == 0) {
1019 * defines values features of a key "\\[a-z]+{"
1024 /* Char type with content discarded
1025 * like \hspace{1cm} */
1027 /* Char, like \backslash */
1029 /* \part, \section*, ... */
1031 /* title, author etc */
1033 /* \foreignlanguage{ngerman}, ... */
1036 * to discard language in content */
1039 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1041 /* fonts, colors, markups, ... */
1043 /* footnotesize, ... large, ...
1044 * Ignore all of them */
1047 /* inputencoding, ...
1048 * Discard also content, because they do not help in search */
1051 * like remove, but also all arguments */
1053 /* item, listitem */
1055 /* tex, latex, ... like isChar */
1057 /* like \lettrine[lines=5]{}{} */
1059 /* End of arguments marker for lettrine,
1060 * so that they can be ignored */
1063 KeyInfo() = default;
1064 KeyInfo(KeyType type, int parcount, bool disable)
1066 parenthesiscount(parcount),
1067 disabled(disable) {}
1068 KeyType keytype = invalid;
1070 int _tokensize = -1;
1071 int _tokenstart = -1;
1072 int _dataStart = -1;
1074 int parenthesiscount = 1;
1075 bool disabled = false;
1076 bool used = false; /* by pattern */
1081 Border(int l=0, int u=0) : low(l), upper(u) {};
1086 #define MAXOPENED 30
1088 bool isPatternString_;
1090 explicit Intervall(bool isPattern, string const & p) :
1091 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1092 hasTitle(false), langcount(0)
1100 static vector<Border> borders;
1101 int depts[MAXOPENED];
1102 int closes[MAXOPENED];
1103 int actualdeptindex;
1104 int previousNotIgnored(int) const;
1105 int nextNotIgnored(int) const;
1106 void handleOpenP(int i);
1107 void handleCloseP(int i, bool closingAllowed);
1108 void resetOpenedP(int openPos);
1109 void addIntervall(int upper);
1110 void addIntervall(int low, int upper); /* if explicit */
1111 void removeAccents();
1112 void setForDefaultLang(KeyInfo const & defLang) const;
1113 int findclosing(int start, int end, char up, char down, int repeat);
1114 void handleParentheses(int lastpos, bool closingAllowed);
1116 int langcount; // Number of disabled language specs up to current position in actual interval
1117 int isOpeningPar(int pos) const;
1119 void output(ostringstream &os, int lastpos);
1120 // string show(int lastpos);
1123 vector<Border> Intervall::borders = vector<Border>(30);
1125 int Intervall::isOpeningPar(int pos) const
1127 if ((pos < 0) || (size_t(pos) >= par.size()))
1129 if (par[pos] != '{')
1131 if (size_t(pos) + 2 >= par.size())
1133 if (par[pos+2] != '}')
1135 if (par[pos+1] == '[' || par[pos+1] == ']')
1140 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1142 // Enable the use of first token again
1143 if (ignoreidx >= 0) {
1144 int value = defLang._tokenstart + defLang._tokensize;
1146 if (borders[0].low < value)
1147 borders[0].low = value;
1148 if (borders[0].upper < value)
1149 borders[0].upper = value;
1154 static void checkDepthIndex(int val)
1156 static int maxdepthidx = MAXOPENED-2;
1157 static int lastmaxdepth = 0;
1158 if (val > lastmaxdepth) {
1159 LYXERR(Debug::INFO, "Depth reached " << val);
1162 if (val > maxdepthidx) {
1164 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1169 // Not needed, because borders are now dynamically expanded
1170 static void checkIgnoreIdx(int val)
1172 static int lastmaxignore = -1;
1173 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1174 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1175 lastmaxignore = val;
1181 * Expand the region of ignored parts of the input latex string
1182 * The region is only relevant in output()
1184 void Intervall::addIntervall(int low, int upper)
1187 if (low == upper) return;
1188 for (idx = ignoreidx+1; idx > 0; --idx) {
1189 if (low > borders[idx-1].upper) {
1193 Border br(low, upper);
1194 if (idx > ignoreidx) {
1195 if (borders.size() <= size_t(idx)) {
1196 borders.push_back(br);
1202 // checkIgnoreIdx(ignoreidx);
1206 // Expand only if one of the new bound is inside the interwall
1207 // We know here that br.low > borders[idx-1].upper
1208 if (br.upper < borders[idx].low) {
1209 // We have to insert at this pos
1210 if (size_t(ignoreidx+1) >= borders.size()) {
1211 borders.push_back(borders[ignoreidx]);
1214 borders[ignoreidx+1] = borders[ignoreidx];
1216 for (int i = ignoreidx; i > idx; --i) {
1217 borders[i] = borders[i-1];
1221 // checkIgnoreIdx(ignoreidx);
1224 // Here we know, that we are overlapping
1225 if (br.low > borders[idx].low)
1226 br.low = borders[idx].low;
1227 // check what has to be concatenated
1229 for (int i = idx; i <= ignoreidx; i++) {
1230 if (br.upper >= borders[i].low) {
1232 if (br.upper < borders[i].upper)
1233 br.upper = borders[i].upper;
1239 // count should be >= 1 here
1242 for (int i = idx + count; i <= ignoreidx; i++) {
1243 borders[i-count+1] = borders[i];
1245 ignoreidx -= count - 1;
1251 typedef map<string, string> AccentsMap;
1252 static AccentsMap accents = map<string, string>();
1254 static void buildaccent(string n, string param, string values)
1258 const char delim = '|';
1259 while (getline(s, name, delim)) {
1261 for (char c : param) {
1262 string key = name + "{" + c + "}";
1263 // get the corresponding utf8-value
1264 if ((values[start] & 0xc0) != 0xc0) {
1265 // should not happen, utf8 encoding starts at least with 11xxxxxx
1266 // but value for '\dot{i}' is 'i', which is ascii
1267 if ((values[start] & 0x80) == 0) {
1269 accents[key] = values.substr(start, 1);
1270 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1275 for (int j = 1; ;j++) {
1276 if (start + j >= values.size()) {
1277 accents[key] = values.substr(start, j);
1278 start = values.size() - 1;
1281 else if ((values[start+j] & 0xc0) != 0x80) {
1282 // This is the first byte of following utf8 char
1283 accents[key] = values.substr(start, j);
1285 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1293 static void buildAccentsMap()
1295 accents["imath"] = "ı";
1297 accents["jmath"] = "ȷ";
1298 accents["cdot"] = "·";
1299 accents["hairspace"] = u8"\uf0000"; // select from free unicode plane 15
1300 accents["thinspace"] = u8"\uf0002"; // and used _only_ by findadv
1301 accents["negthinspace"] = u8"\uf0003"; // to omit backslashed latex macros
1302 accents["medspace"] = u8"\uf0004"; // See https://en.wikipedia.org/wiki/Private_Use_Areas
1303 accents["negmedspace"] = u8"\uf0005";
1304 accents["thickspace"] = u8"\uf0006";
1305 accents["negthickspace"] = u8"\uf0007";
1306 accents["lyxmathsym{ß}"] = "ß";
1307 accents["text{ß}"] = "ß";
1308 accents["ddot{\\imath}"] = "ï";
1309 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1310 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1311 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1312 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1313 accents["acute{\\imath}"] = "í";
1314 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1315 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1316 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1317 buildaccent("mathring|r", "aAuUwy",
1319 accents["check{\\imath}"] = "ǐ";
1320 accents["check{\\jmath}"] = "ǰ";
1321 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1322 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1323 accents["hat{\\imath}"] = "î";
1324 accents["hat{\\jmath}"] = "ĵ";
1325 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1326 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1327 accents["bar{\\imath}"] = "ī";
1328 buildaccent("bar|=", "aAeEiIoOuUyY",
1329 "āĀēĒīĪōŌūŪȳȲ"); // macron
1330 accents["tilde{\\imath}"] = "ĩ";
1331 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1332 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1333 accents["breve{\\imath}"] = "ĭ";
1334 buildaccent("breve|u", "aAeEgGiIoOuU",
1335 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1336 accents["grave{\\imath}"] = "ì";
1337 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1338 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1339 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1340 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1341 buildaccent("ogonek|k", "AaEeIiUuOo",
1342 "ĄąĘęĮįŲųǪǫ"); // ogonek
1343 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1344 "ÇçĢĢĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1345 buildaccent("subring|textsubring", "Aa",
1347 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1348 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1349 buildaccent("subtilde|textsubtilde", "EeIiUu",
1350 "ḚḛḬḭṴṵ"); // subtilde
1351 accents["dgrave{\\imath}"] = "ȉ";
1352 accents["textdoublegrave{\\i}"] = "ȉ";
1353 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1354 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1355 accents["rcap{\\imath}"] = "ȉ";
1356 accents["textroundcap{\\i}"] = "ȉ";
1357 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1358 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1359 buildaccent("slashed", "oO",
1364 * Created accents in math or regexp environment
1365 * are macros, but we need the utf8 equivalent
1367 void Intervall::removeAccents()
1369 if (accents.empty())
1371 static regex const accre("\\\\(([\\S]|grave|breve|lyxmathsym|text|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}|(i|imath|jmath|cdot|[a-z]+space)(?![a-zA-Z]))");
1373 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1375 string key = sub.str(1);
1376 if (accents.find(key) != accents.end()) {
1377 string val = accents[key];
1378 size_t pos = sub.position(size_t(0));
1379 for (size_t i = 0; i < val.size(); i++) {
1380 par[pos+i] = val[i];
1382 // Remove possibly following space too
1383 if (par[pos+sub.str(0).size()] == ' ')
1384 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1386 addIntervall(pos+val.size(), pos + sub.str(0).size());
1387 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1388 // remove traces of any remaining chars
1393 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1398 void Intervall::handleOpenP(int i)
1401 depts[actualdeptindex] = i+1;
1402 closes[actualdeptindex] = -1;
1403 checkDepthIndex(actualdeptindex);
1406 void Intervall::handleCloseP(int i, bool closingAllowed)
1408 if (actualdeptindex <= 0) {
1409 if (! closingAllowed)
1410 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1411 // if we are at the very end
1412 addIntervall(i, i+1);
1415 closes[actualdeptindex] = i+1;
1420 void Intervall::resetOpenedP(int openPos)
1422 // Used as initializer for foreignlanguage entry
1423 actualdeptindex = 1;
1424 depts[1] = openPos+1;
1428 int Intervall::previousNotIgnored(int start) const
1430 int idx = 0; /* int intervalls */
1431 for (idx = ignoreidx; idx >= 0; --idx) {
1432 if (start > borders[idx].upper)
1434 if (start >= borders[idx].low)
1435 start = borders[idx].low-1;
1440 int Intervall::nextNotIgnored(int start) const
1442 int idx = 0; /* int intervalls */
1443 for (idx = 0; idx <= ignoreidx; idx++) {
1444 if (start < borders[idx].low)
1446 if (start < borders[idx].upper)
1447 start = borders[idx].upper;
1452 typedef map<string, KeyInfo> KeysMap;
1453 typedef vector< KeyInfo> Entries;
1454 static KeysMap keys = map<string, KeyInfo>();
1460 Intervall interval_;
1461 void buildKeys(bool);
1462 void buildEntries(bool);
1463 void makeKey(const string &, KeyInfo, bool isPatternString);
1464 void processRegion(int start, int region_end); /* remove {} parts */
1465 void removeHead(KeyInfo const &, int count=0);
1468 LatexInfo(string const & par, bool isPatternString)
1469 : entidx_(-1), interval_(isPatternString, par)
1471 buildKeys(isPatternString);
1472 entries_ = vector<KeyInfo>();
1473 buildEntries(isPatternString);
1477 if (entries_.empty()) {
1480 if (entries_[0].keytype == KeyInfo::isTitle) {
1481 if (! entries_[0].disabled) {
1482 interval_.hasTitle = true;
1483 interval_.titleValue = entries_[0].head;
1486 interval_.hasTitle = false;
1487 interval_.titleValue = "";
1489 removeHead(entries_[0]);
1490 if (entries_.size() > 1)
1499 if (int(entries_.size()) > entidx_) {
1506 bool setNextKey(int idx) {
1507 if ((idx == entidx_) && (entidx_ >= 0)) {
1514 int find(int start, KeyInfo::KeyType keytype) const {
1518 while (tmpIdx < int(entries_.size())) {
1519 if (entries_[tmpIdx].keytype == keytype)
1525 int process(ostringstream & os, KeyInfo const & actual);
1526 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1527 // string show(int lastpos) { return interval.show(lastpos);};
1528 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1529 KeyInfo &getKeyInfo(int keyinfo) {
1530 static KeyInfo invalidInfo = KeyInfo();
1531 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1534 return entries_[keyinfo];
1536 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1537 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1541 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1545 for (int i = start; i < end; i += 1 + skip) {
1549 if (c == '\\') skip = 1;
1553 else if (c == down) {
1556 if ((repeat <= 0) || (par[i+1] != up))
1574 vector<MathEntry> entries_;
1579 void insert(string const & wait, size_t start, size_t end) {
1580 MathEntry m = MathEntry();
1582 m.mathStart = start;
1584 m.mathSize = end - start;
1585 entries_.push_back(m);
1587 bool empty() const { return entries_.empty(); };
1588 size_t getEndPos() const {
1589 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1592 return entries_[actualIdx_].mathEnd;
1594 size_t getStartPos() const {
1595 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1596 return 100000; /* definitely enough? */
1598 return entries_[actualIdx_].mathStart;
1600 size_t getFirstPos() {
1602 return getStartPos();
1604 size_t getSize() const {
1605 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1608 return entries_[actualIdx_].mathSize;
1610 void incrEntry() { actualIdx_++; };
1613 void LatexInfo::buildEntries(bool isPatternString)
1615 static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\}");
1616 static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1617 static bool disableLanguageOverride = false;
1618 smatch sub, submath;
1619 bool evaluatingRegexp = false;
1621 bool evaluatingMath = false;
1622 bool evaluatingCode = false;
1624 bool evaluatingOptional = false;
1625 size_t optionalEnd = 0;
1628 bool math_end_waiting = false;
1629 size_t math_pos = 10000;
1632 interval_.removeAccents();
1634 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1636 if (math_end_waiting) {
1637 size_t pos = submath.position(size_t(0));
1638 if ((math_end == "$") &&
1639 (submath.str(0) == "$") &&
1640 (interval_.par[pos-1] != '\\')) {
1641 mi.insert("$", math_pos, pos + 1);
1642 math_end_waiting = false;
1644 else if ((math_end == "\\]") &&
1645 (submath.str(0) == "\\]")) {
1646 mi.insert("\\]", math_pos, pos + 2);
1647 math_end_waiting = false;
1649 else if ((submath.str(1).compare("end") == 0) &&
1650 (submath.str(2).compare(math_end) == 0)) {
1651 mi.insert(math_end, math_pos, pos + submath.str(0).length());
1652 math_end_waiting = false;
1658 if (submath.str(1).compare("begin") == 0) {
1659 math_end_waiting = true;
1660 math_end = submath.str(2);
1661 math_pos = submath.position(size_t(0));
1663 else if (submath.str(0).compare("\\[") == 0) {
1664 math_end_waiting = true;
1666 math_pos = submath.position(size_t(0));
1668 else if (submath.str(0) == "$") {
1669 size_t pos = submath.position(size_t(0));
1670 if ((pos == 0) || (interval_.par[pos-1] != '\\')) {
1671 math_end_waiting = true;
1678 // Ignore language if there is math somewhere in pattern-string
1679 if (isPatternString) {
1682 keys["foreignlanguage"].disabled = true;
1683 disableLanguageOverride = true;
1686 disableLanguageOverride = false;
1689 if (disableLanguageOverride) {
1690 keys["foreignlanguage"].disabled = true;
1693 math_pos = mi.getFirstPos();
1694 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1696 string key = sub.str(3);
1698 if (sub.str(0)[0] == '\\')
1699 key = sub.str(0)[1];
1703 size_t k_pos = sub.position(size_t(0));
1704 if ((k_pos > 0) && (interval_.par[k_pos - 1] == '\\')) {
1705 // Escaped '$', ignoring
1711 if (evaluatingRegexp) {
1712 if (sub.str(1).compare("endregexp") == 0) {
1713 evaluatingRegexp = false;
1714 // found._tokenstart already set
1715 found._dataEnd = sub.position(size_t(0)) + 13;
1716 found._dataStart = found._dataEnd;
1717 found._tokensize = found._dataEnd - found._tokenstart;
1718 found.parenthesiscount = 0;
1719 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1726 if (evaluatingMath) {
1727 if (size_t(sub.position(size_t(0))) < mi.getEndPos())
1729 evaluatingMath = false;
1731 math_pos = mi.getStartPos();
1733 if (keys.find(key) == keys.end()) {
1734 found = KeyInfo(KeyInfo::isStandard, 0, true);
1735 if (isPatternString) {
1736 found.keytype = KeyInfo::isChar;
1737 found.disabled = false;
1744 if (key.compare("regexp") == 0) {
1745 evaluatingRegexp = true;
1746 found._tokenstart = sub.position(size_t(0));
1747 found._tokensize = 0;
1751 // Handle the other params of key
1752 if (found.keytype == KeyInfo::isIgnored)
1754 else if (found.keytype == KeyInfo::isMath) {
1755 if (size_t(sub.position(size_t(0))) == math_pos) {
1757 found._tokenstart = sub.position(size_t(0));
1758 found._tokensize = mi.getSize();
1759 found._dataEnd = found._tokenstart + found._tokensize;
1760 found._dataStart = found._dataEnd;
1761 found.parenthesiscount = 0;
1762 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1763 evaluatingMath = true;
1766 // begin|end of unknown env, discard
1767 // First handle tables
1768 // longtable|tabular
1769 bool discardComment;
1771 found.keytype = KeyInfo::doRemove;
1772 if ((sub.str(5).compare("longtable") == 0) ||
1773 (sub.str(5).compare("tabular") == 0)) {
1774 discardComment = true; /* '%' */
1777 discardComment = false;
1778 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1780 string token = sub.str(5);
1781 if (regex_match(token, sub2, removeArgs)) {
1782 found.keytype = KeyInfo::removeWithArg;
1785 // discard spaces before pos(0)
1786 int pos = sub.position(size_t(0));
1788 for (count = 0; pos - count > 0; count++) {
1789 char c = interval_.par[pos-count-1];
1790 if (discardComment) {
1791 if ((c != ' ') && (c != '%'))
1797 found._tokenstart = pos - count;
1798 if (sub.str(1).compare(0, 5, "begin") == 0) {
1799 size_t pos1 = pos + sub.str(0).length();
1800 if (sub.str(5).compare("cjk") == 0) {
1801 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1802 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1804 found.keytype = KeyInfo::isMain;
1805 found._dataStart = pos1;
1806 found._dataEnd = interval_.par.length();
1807 found.disabled = keys["foreignlanguage"].disabled;
1808 found.used = keys["foreignlanguage"].used;
1809 found._tokensize = pos1 - found._tokenstart;
1810 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1813 // Swallow possible optional params
1814 while (interval_.par[pos1] == '[') {
1815 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1817 // Swallow also the eventual parameter
1818 if (interval_.par[pos1] == '{') {
1819 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1822 found._dataEnd = pos1;
1824 found._dataStart = found._dataEnd;
1825 found._tokensize = count + found._dataEnd - pos;
1826 found.parenthesiscount = 0;
1827 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1828 found.disabled = true;
1832 // Handle "\end{...}"
1833 found._dataStart = pos + sub.str(0).length();
1834 found._dataEnd = found._dataStart;
1835 found._tokensize = count + found._dataEnd - pos;
1836 found.parenthesiscount = 0;
1837 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1838 found.disabled = true;
1842 else if (found.keytype != KeyInfo::isRegex) {
1843 found._tokenstart = sub.position(size_t(0));
1844 if (found.parenthesiscount == 0) {
1845 // Probably to be discarded
1846 size_t following_pos = sub.position(size_t(0)) + sub.str(3).length() + 1;
1847 char following = interval_.par[following_pos];
1848 if (following == ' ')
1849 found.head = "\\" + sub.str(3) + " ";
1850 else if (following == '=') {
1851 // like \uldepth=1000pt
1852 found.head = sub.str(0);
1855 found.head = "\\" + key;
1856 found._tokensize = found.head.length();
1857 found._dataEnd = found._tokenstart + found._tokensize;
1858 found._dataStart = found._dataEnd;
1861 int params = found._tokenstart + key.length() + 1;
1862 if (evaluatingOptional) {
1863 if (size_t(found._tokenstart) > optionalEnd) {
1864 evaluatingOptional = false;
1867 found.disabled = true;
1870 int optend = params;
1871 while (interval_.par[optend] == '[') {
1872 // discard optional parameters
1873 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
1875 if (optend > params) {
1876 key += interval_.par.substr(params, optend-params);
1877 evaluatingOptional = true;
1878 optionalEnd = optend;
1880 string token = sub.str(5);
1881 int closings = found.parenthesiscount;
1882 if (found.parenthesiscount == 1) {
1883 found.head = "\\" + key + "{";
1885 else if (found.parenthesiscount > 1) {
1887 found.head = sub.str(0) + "{";
1888 closings = found.parenthesiscount - 1;
1891 found.head = "\\" + key + "{";
1894 found._tokensize = found.head.length();
1895 found._dataStart = found._tokenstart + found.head.length();
1896 if (found.keytype == KeyInfo::doRemove) {
1897 int endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1898 found._dataStart = endpar;
1899 found._tokensize = found._dataStart - found._tokenstart;
1902 if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
1903 found._dataStart += 15;
1907 endpos = found._dataStart - 1;
1909 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1910 if (found.keytype == KeyInfo::isList) {
1911 // Check if it really is list env
1912 static regex const listre("^([a-z]+)$");
1914 if (!regex_match(token, sub2, listre)) {
1915 // Change the key of this entry. It is not in a list/item environment
1916 found.keytype = KeyInfo::endArguments;
1919 if (found.keytype == KeyInfo::noMain) {
1920 evaluatingCode = true;
1922 codeStart = found._dataStart;
1924 else if (evaluatingCode) {
1925 if (size_t(found._dataStart) > codeEnd)
1926 evaluatingCode = false;
1927 else if (found.keytype == KeyInfo::isMain) {
1928 // Disable this key, treate it as standard
1929 found.keytype = KeyInfo::isStandard;
1930 found.disabled = true;
1931 if ((codeEnd == interval_.par.length()) &&
1932 (found._tokenstart == codeStart)) {
1933 // trickery, because the code inset starts
1934 // with \selectlanguage ...
1936 if (entries_.size() > 1) {
1937 entries_[entries_.size()-1]._dataEnd = codeEnd;
1942 if ((endpos == interval_.par.length()) &&
1943 (found.keytype == KeyInfo::doRemove)) {
1944 // Missing closing => error in latex-input?
1945 // therefore do not delete remaining data
1946 found._dataStart -= 1;
1947 found._dataEnd = found._dataStart;
1950 found._dataEnd = endpos;
1952 if (isPatternString) {
1953 keys[key].used = true;
1956 entries_.push_back(found);
1960 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
1962 stringstream s(keysstring);
1964 const char delim = '|';
1965 while (getline(s, key, delim)) {
1966 KeyInfo keyII(keyI);
1967 if (isPatternString) {
1970 else if ( !keys[key].used)
1971 keyII.disabled = true;
1976 void LatexInfo::buildKeys(bool isPatternString)
1979 static bool keysBuilt = false;
1980 if (keysBuilt && !isPatternString) return;
1982 // Known standard keys with 1 parameter.
1983 // Split is done, if not at start of region
1984 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
1985 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
1986 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
1987 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
1988 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
1989 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
1991 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
1992 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
1993 makeKey("section*|subsection*|subsubsection*|paragraph*",
1994 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
1995 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
1996 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
1998 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2000 // Split is done, if not at start of region
2001 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2002 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2004 // Split is done always.
2005 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2009 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2010 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2011 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2012 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2014 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2015 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2016 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2017 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2019 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2020 // Custom space/skip, remove the content (== length value)
2021 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2022 // Found in fr/UserGuide.lyx
2023 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2025 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2026 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2027 // Known macros to remove (including their parameter)
2029 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2030 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2031 // handle like standard keys with 1 parameter.
2032 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2034 // Ignore deleted text
2035 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2036 // but preserve added text
2037 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2039 // Macros to remove, but let the parameter survive
2041 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2043 // Remove language spec from content of these insets
2044 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2046 // Same effect as previous, parameter will survive (because there is no one anyway)
2048 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2049 // Remove table decorations
2050 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2051 // Discard shape-header.
2052 // For footnote or shortcut too, because of lang settings
2053 // and wrong handling if used 'KeyInfo::noMain'
2054 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2055 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2056 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2057 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2058 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2059 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2060 // like ('tiny{}' or '\tiny ' ... )
2061 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2063 // Survives, like known character
2064 makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2065 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2067 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2068 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2069 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2071 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2072 // Remove RTL/LTR marker
2073 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2074 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2075 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2076 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2077 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2078 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2079 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2080 if (isPatternString) {
2081 // Allow the first searched string to rebuild the keys too
2085 // no need to rebuild again
2091 * Keep the list of actual opened parentheses actual
2092 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2094 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2097 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2101 if (c == '\\') skip = 1;
2102 else if (c == '{') {
2105 else if (c == '}') {
2106 handleCloseP(i, closingAllowed);
2112 string Intervall::show(int lastpos)
2114 int idx = 0; /* int intervalls */
2117 for (idx = 0; idx <= ignoreidx; idx++) {
2118 while (i < lastpos) {
2120 if (i <= borders[idx].low) {
2121 if (borders[idx].low > lastpos)
2122 printsize = lastpos - i;
2124 printsize = borders[idx].low - i;
2125 s += par.substr(i, printsize);
2127 if (i >= borders[idx].low)
2128 i = borders[idx].upper;
2131 i = borders[idx].upper;
2137 s += par.substr(i, lastpos-i);
2143 void Intervall::output(ostringstream &os, int lastpos)
2145 // get number of chars to output
2146 int idx = 0; /* int intervalls */
2149 string startTitle = titleValue;
2150 for (idx = 0; idx <= ignoreidx; idx++) {
2152 if (i <= borders[idx].low) {
2154 if (borders[idx].low > lastpos)
2155 printsize = lastpos - i;
2157 printsize = borders[idx].low - i;
2158 if (printsize > 0) {
2159 os << startTitle << par.substr(i, printsize);
2161 printed += printsize;
2164 handleParentheses(i, false);
2165 if (i >= borders[idx].low)
2166 i = borders[idx].upper;
2169 i = borders[idx].upper;
2176 os << startTitle << par.substr(i, lastpos-i);
2177 printed += lastpos-i;
2179 handleParentheses(lastpos, false);
2181 if (keys["foreignlanguage"].disabled)
2182 startindex = actualdeptindex-langcount;
2184 startindex = actualdeptindex;
2185 for (int i = startindex; i > 0; --i) {
2188 if (hasTitle && (printed > 0))
2190 if (! isPatternString_)
2192 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2195 void LatexInfo::processRegion(int start, int region_end)
2197 while (start < region_end) { /* Let {[} and {]} survive */
2198 int cnt = interval_.isOpeningPar(start);
2200 // Closing is allowed past the region
2201 int closing = interval_.findclosing(start+1, interval_.par.length());
2202 interval_.addIntervall(start, start+1);
2203 interval_.addIntervall(closing, closing+1);
2207 start = interval_.nextNotIgnored(start+1);
2211 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2213 if (actual.parenthesiscount == 0) {
2214 // "{\tiny{} ...}" ==> "{{} ...}"
2215 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2218 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2219 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2220 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2224 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2227 switch (actual.keytype)
2229 case KeyInfo::isTitle: {
2231 nextKeyIdx = getNextKey();
2234 case KeyInfo::cleanToStart: {
2235 actual._dataEnd = actual._dataStart;
2236 nextKeyIdx = getNextKey();
2237 // Search for end of arguments
2238 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2240 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2241 entries_[i].disabled = true;
2243 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2245 while (interval_.par[actual._dataEnd] == ' ')
2247 interval_.addIntervall(0, actual._dataEnd+1);
2248 interval_.actualdeptindex = 0;
2249 interval_.depts[0] = actual._dataEnd+1;
2250 interval_.closes[0] = -1;
2253 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2254 if (actual.disabled)
2255 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2257 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2260 case KeyInfo::isChar: {
2261 nextKeyIdx = getNextKey();
2264 case KeyInfo::isSize: {
2265 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2266 processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
2267 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2268 nextKeyIdx = getNextKey();
2270 // Here _dataStart points to '{', so correct it
2271 actual._dataStart += 1;
2272 actual._tokensize += 1;
2273 actual.parenthesiscount = 1;
2274 if (interval_.par[actual._dataStart] == '}') {
2275 // Determine the end if used like '{\tiny{}...}'
2276 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2277 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2280 // Determine the end if used like '\tiny{...}'
2281 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2283 // Split on this key if not at start
2284 int start = interval_.nextNotIgnored(previousStart);
2285 if (start < actual._tokenstart) {
2286 interval_.output(os, actual._tokenstart);
2287 interval_.addIntervall(start, actual._tokenstart);
2289 // discard entry if at end of actual
2290 nextKeyIdx = process(os, actual);
2294 case KeyInfo::endArguments:
2295 // Remove trailing '{}' too
2296 actual._dataStart += 1;
2297 actual._dataEnd += 1;
2298 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2299 nextKeyIdx = getNextKey();
2301 case KeyInfo::noMain:
2303 case KeyInfo::isStandard: {
2304 if (actual.disabled) {
2306 processRegion(actual._dataStart, actual._dataStart+1);
2307 nextKeyIdx = getNextKey();
2309 // Split on this key if not at datastart of calling entry
2310 int start = interval_.nextNotIgnored(previousStart);
2311 if (start < actual._tokenstart) {
2312 interval_.output(os, actual._tokenstart);
2313 interval_.addIntervall(start, actual._tokenstart);
2315 // discard entry if at end of actual
2316 nextKeyIdx = process(os, actual);
2320 case KeyInfo::removeWithArg: {
2321 nextKeyIdx = getNextKey();
2322 // Search for end of arguments
2323 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2325 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2326 entries_[i].disabled = true;
2328 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2330 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2333 case KeyInfo::doRemove: {
2334 // Remove the key with all parameters and following spaces
2336 for (pos = actual._dataEnd+1; pos < interval_.par.length(); pos++) {
2337 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2340 // Remove also enclosing parentheses [] and {}
2343 while (actual._tokenstart > numpars) {
2344 if (pos+numpars >= interval_.par.size())
2346 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2348 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2354 if (interval_.par[pos+numpars] == ' ')
2358 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2359 nextKeyIdx = getNextKey();
2362 case KeyInfo::isList: {
2363 // Discard space before _tokenstart
2365 for (count = 0; count < actual._tokenstart; count++) {
2366 if (interval_.par[actual._tokenstart-count-1] != ' ')
2369 nextKeyIdx = getNextKey();
2370 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2372 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2374 // How else can we catch this one?
2375 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2376 entries_[i].disabled = true;
2378 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2380 else if (nextKeyIdx > 0) {
2381 // Ignore any lang entries inside data region
2382 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2383 if (entries_[i].keytype == KeyInfo::isMain)
2384 entries_[i].disabled = true;
2387 if (actual.disabled) {
2388 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2391 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2393 if (interval_.par[actual._dataEnd+1] == '[') {
2394 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2395 if ((interval_.par[actual._dataEnd+2] == '{') &&
2396 (interval_.par[posdown-1] == '}')) {
2397 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2398 interval_.addIntervall(posdown-1, posdown+1);
2401 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2402 interval_.addIntervall(posdown, posdown+1);
2404 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2405 if (blk > posdown) {
2406 // Discard at most 1 space after empty item
2408 for (count = 0; count < 1; count++) {
2409 if (interval_.par[blk+count] != ' ')
2413 interval_.addIntervall(blk, blk+count);
2418 case KeyInfo::isSectioning: {
2419 // Discard spaces before _tokenstart
2421 int val = actual._tokenstart;
2422 for (count = 0; count < actual._tokenstart;) {
2423 val = interval_.previousNotIgnored(val-1);
2424 if (val < 0 || interval_.par[val] != ' ')
2427 count = actual._tokenstart - val;
2430 if (actual.disabled) {
2431 removeHead(actual, count);
2432 nextKeyIdx = getNextKey();
2434 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2435 nextKeyIdx = process(os, actual);
2439 case KeyInfo::isMath: {
2440 // Same as regex, use the content unchanged
2441 nextKeyIdx = getNextKey();
2444 case KeyInfo::isRegex: {
2445 // DO NOT SPLIT ON REGEX
2447 nextKeyIdx = getNextKey();
2450 case KeyInfo::isIgnored: {
2451 // Treat like a character for now
2452 nextKeyIdx = getNextKey();
2455 case KeyInfo::isMain: {
2456 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2457 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2458 if (actual._tokenstart > 0) {
2459 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2460 if ((prev >= 0) && interval_.par[prev] == '%')
2461 interval_.addIntervall(prev, prev+1);
2463 if (actual.disabled) {
2465 interval_.langcount++;
2466 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2467 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2468 // Discard also the space before math-equation
2469 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2471 nextKeyIdx = getNextKey();
2472 // interval.resetOpenedP(actual._dataStart-1);
2475 if (actual._tokenstart < 26) {
2476 // for the first (and maybe dummy) language
2477 interval_.setForDefaultLang(actual);
2479 interval_.resetOpenedP(actual._dataStart-1);
2483 case KeyInfo::invalid:
2484 // This cannot happen, already handled
2487 // LYXERR(Debug::INFO, "Unhandled keytype");
2488 nextKeyIdx = getNextKey();
2495 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2497 int end = interval_.nextNotIgnored(actual._dataEnd);
2498 int oldStart = actual._dataStart;
2499 int nextKeyIdx = getNextKey();
2501 if ((nextKeyIdx < 0) ||
2502 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2503 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2504 if (oldStart <= end) {
2505 processRegion(oldStart, end);
2510 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2512 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2513 (void) dispatch(os, actual._dataStart, nextKey);
2514 end = nextKey._tokenstart;
2517 processRegion(oldStart, nextKey._tokenstart);
2518 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2520 oldStart = nextKey._dataEnd+1;
2522 // now nextKey is either invalid or is outside of actual._dataEnd
2523 // output the remaining and discard myself
2524 if (oldStart <= end) {
2525 processRegion(oldStart, end);
2527 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2529 // This is the normal case.
2530 // But if using the firstlanguage, the closing may be missing
2532 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2534 if (actual._dataEnd < end)
2535 output_end = interval_.nextNotIgnored(actual._dataEnd);
2537 output_end = interval_.nextNotIgnored(end);
2538 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2539 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2541 // Remove possible empty data
2542 int dstart = interval_.nextNotIgnored(actual._dataStart);
2543 while (interval_.isOpeningPar(dstart) == 1) {
2544 interval_.addIntervall(dstart, dstart+1);
2545 int dend = interval_.findclosing(dstart+1, output_end);
2546 interval_.addIntervall(dend, dend+1);
2547 dstart = interval_.nextNotIgnored(dstart+1);
2549 if (dstart < output_end)
2550 interval_.output(os, output_end);
2551 interval_.addIntervall(actual._tokenstart, end);
2555 string splitOnKnownMacros(string par, bool isPatternString)
2558 LatexInfo li(par, isPatternString);
2559 // LYXERR(Debug::INFO, "Berfore split: " << par);
2560 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2562 DummyKey._tokensize = 0;
2563 DummyKey._dataStart = 0;
2564 DummyKey._dataEnd = par.length();
2565 DummyKey.disabled = true;
2566 int firstkeyIdx = li.getFirstKey();
2568 if (firstkeyIdx >= 0) {
2569 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2570 DummyKey._tokenstart = firstKey._tokenstart;
2572 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2573 // Use dummy firstKey
2574 firstKey = DummyKey;
2575 (void) li.setNextKey(firstkeyIdx);
2578 if (par.substr(firstKey._dataStart, 2) == "% ")
2579 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2581 nextkeyIdx = li.process(os, firstKey);
2582 while (nextkeyIdx >= 0) {
2583 // Check for a possible gap between the last
2584 // entry and this one
2585 int datastart = li.nextNotIgnored(firstKey._dataStart);
2586 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2587 if ((nextKey._tokenstart > datastart)) {
2589 firstKey._dataStart = datastart;
2590 firstKey._dataEnd = par.length();
2591 (void) li.setNextKey(nextkeyIdx);
2592 // Fake the last opened parenthesis
2593 li.setForDefaultLang(firstKey);
2594 nextkeyIdx = li.process(os, firstKey);
2597 if (nextKey.keytype != KeyInfo::isMain) {
2598 firstKey._dataStart = datastart;
2599 firstKey._dataEnd = nextKey._dataEnd+1;
2600 (void) li.setNextKey(nextkeyIdx);
2601 li.setForDefaultLang(firstKey);
2602 nextkeyIdx = li.process(os, firstKey);
2605 nextkeyIdx = li.process(os, nextKey);
2609 // Handle the remaining
2610 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2611 firstKey._dataEnd = par.length();
2613 if ((firstKey._dataStart < firstKey._dataEnd) &&
2614 (par[firstKey._dataStart] != '}')) {
2615 li.setForDefaultLang(firstKey);
2616 (void) li.process(os, firstKey);
2620 // return string definitelly impossible to match
2621 s = "\\foreignlanguage{ignore}{ }";
2625 s = par; /* no known macros found */
2626 // LYXERR(Debug::INFO, "After split: " << s);
2631 * Try to unify the language specs in the latexified text.
2632 * Resulting modified string is set to "", if
2633 * the searched tex does not contain all the features in the search pattern
2635 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2637 static Features regex_f;
2638 static int missed = 0;
2639 static bool regex_with_format = false;
2641 int parlen = par.length();
2643 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2646 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2647 // Happens to be there in case of description or labeling environment
2652 // Split the latex input into pieces which
2653 // can be digested by our search engine
2654 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2655 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2656 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2659 result = par.substr(0, parlen);
2660 if (isPatternString) {
2663 regex_f = identifyFeatures(result);
2664 string features = "";
2665 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2666 string a = it->first;
2667 regex_with_format = true;
2668 features += " " + a;
2669 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2671 LYXERR(Debug::FIND, "Identified Features" << features);
2674 } else if (regex_with_format) {
2675 Features info = identifyFeatures(result);
2676 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2677 string a = it->first;
2678 bool b = it->second;
2679 if (b && ! info[a]) {
2681 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2687 // LYXERR(Debug::INFO, "No regex formats");
2693 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2694 static int identifyClosing(string & t)
2696 int open_braces = 0;
2698 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2699 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2701 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2703 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2705 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2714 static int num_replaced = 0;
2715 static bool previous_single_replace = true;
2717 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2718 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2720 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2721 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2722 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2723 if (opt.replace_all && previous_single_replace) {
2724 previous_single_replace = false;
2727 else if (!opt.replace_all) {
2728 num_replaced = 0; // count number of replaced strings
2729 previous_single_replace = true;
2731 // When using regexp, braces are hacked already by escape_for_regex()
2732 par_as_string = normalize(ds, !use_regexp);
2734 close_wildcards = 0;
2736 size_t lead_size = 0;
2737 // correct the language settings
2738 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2739 if (opt.ignoreformat) {
2741 // if par_as_string_nolead were emty,
2742 // the following call to findAux will always *find* the string
2743 // in the checked data, and thus always using the slow
2744 // examining of the current text part.
2745 par_as_string_nolead = par_as_string;
2748 lead_size = identifyLeading(par_as_string);
2749 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2750 lead_as_string = par_as_string.substr(0, lead_size);
2751 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2755 open_braces = identifyClosing(par_as_string);
2756 identifyClosing(par_as_string_nolead);
2757 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2758 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2760 string lead_as_regexp;
2761 if (lead_size > 0) {
2762 // @todo No need to search for \regexp{} insets in leading material
2763 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2764 par_as_string = par_as_string_nolead;
2765 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2766 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2768 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2769 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2770 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2772 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2773 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2774 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2775 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2776 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2777 || regex_replace(par_as_string, par_as_string,
2778 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2779 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2780 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2784 if (!opt.ignoreformat) {
2785 // Remove extra '\}' at end if not part of \{\.\}
2786 size_t lng = par_as_string.size();
2788 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
2790 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
2799 if (lng < par_as_string.size())
2800 par_as_string = par_as_string.substr(0,lng);
2803 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2804 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2805 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2806 // replace '[^...]' with '[^...\}\{\\]'
2807 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2808 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2809 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2811 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2814 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2815 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2816 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
2817 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2819 // If entered regexp must match at begin of searched string buffer
2820 // Kornel: Added parentheses to use $1 for size of the leading string
2824 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2825 // Unfortunately is '\1', '\2', etc not working for strings with extra format
2826 // so the convert has no effect in that case
2827 for (int i = 8; i > 0; --i) {
2828 string orig = "\\\\" + std::to_string(i);
2829 string dest = "\\" + std::to_string(i+1);
2830 while (regex_replace(par_as_string, par_as_string, orig, dest));
2832 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2833 regexp2_str = "(" + lead_as_regexp + ").*?" + par_as_string;
2835 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2836 regexp = regex(regexp_str);
2838 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2839 regexp2 = regex(regexp2_str);
2844 // Count number of characters in string
2848 // \\[a-zA-Z]+ ==> 1
2849 static int computeSize(string s, int len)
2855 for (int i = 0; i < len; i += skip, count++) {
2858 if (isalpha(s[i+1])) {
2859 for (int j = 2; i+j < len; j++) {
2860 if (! isalpha(s[i+j])) {
2863 else if ((s[i+j] == '{') && s[i+j+1] == '}')
2865 else if ((s[i+j] == '{') && (i + j + 1 >= len))
2873 else if (s[i] == '{') {
2879 else if (s[i] == '-') {
2880 if (s[i+1] == '-') {
2896 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2901 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2904 docstring docstr = stringifyFromForSearch(opt, cur, len);
2905 string str = normalize(docstr, true);
2906 if (!opt.ignoreformat) {
2907 str = correctlanguagesetting(str, false, !opt.ignoreformat);
2910 mres.match_len = -1;
2913 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
2914 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
2917 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
2918 regex const *p_regexp;
2919 regex_constants::match_flag_type flags;
2921 flags = regex_constants::match_continuous;
2924 flags = regex_constants::match_default;
2925 p_regexp = ®exp2;
2927 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
2928 if (re_it == sregex_iterator())
2930 match_results<string::const_iterator> const & m = *re_it;
2932 if (0) { // Kornel Benko: DO NOT CHECKK
2933 // Check braces on the segment that matched the entire regexp expression,
2934 // plus the last subexpression, if a (.*?) was inserted in the constructor.
2935 if (!braces_match(m[0].first, m[0].second, open_braces))
2939 // Check braces on segments that matched all (.*?) subexpressions,
2940 // except the last "padding" one inserted by lyx.
2941 for (size_t i = 1; i < m.size() - 1; ++i)
2942 if (!braces_match(m[i].first, m[i].second, open_braces))
2945 // Exclude from the returned match length any length
2946 // due to close wildcards added at end of regexp
2947 // and also the length of the leading (e.g. '\emph{}')
2949 // Whole found string, including the leading: m[0].second - m[0].first
2950 // Size of the leading string: m[1].second - m[1].first
2951 int leadingsize = 0;
2953 leadingsize = m[1].second - m[1].first;
2955 for (size_t i = 0; i < m.size(); i++) {
2956 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2958 if (close_wildcards == 0)
2959 result = m[0].second - m[0].first;
2962 result = m[m.size() - close_wildcards].first - m[0].first;
2964 size_t pos = m.position(size_t(0));
2965 // Ignore last closing characters
2966 while (result > 0) {
2967 if (str[pos+result-1] == '}')
2972 if (result > leadingsize)
2973 result -= leadingsize;
2976 mres.match_len = computeSize(str.substr(pos+leadingsize,result), result);
2977 mres.match2end = str.size() - pos - leadingsize;
2978 mres.pos = pos+leadingsize;
2982 // else !use_regexp: but all code paths above return
2983 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2984 << par_as_string << "', str='" << str << "'");
2985 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2986 << lead_as_string << "', par_as_string_nolead='"
2987 << par_as_string_nolead << "'");
2990 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2991 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2992 if (str.substr(0, par_as_string.size()) == par_as_string) {
2993 mres.match_len = par_as_string.size();
2994 mres.match2end = str.size();
2999 // Start the search _after_ the leading part
3000 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3001 if (pos != string::npos) {
3002 mres.match_len = par_as_string.size();
3003 mres.match2end = str.size() - pos;
3012 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3014 MatchResult mres = findAux(cur, len, at_begin);
3015 int res = mres.match_len;
3017 "res=" << res << ", at_begin=" << at_begin
3018 << ", matchword=" << opt.matchword
3019 << ", inTexted=" << cur.inTexted());
3020 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
3022 if ((len > 0) && (res < len)) {
3026 Paragraph const & par = cur.paragraph();
3027 bool ws_left = (cur.pos() > 0)
3028 ? par.isWordSeparator(cur.pos() - 1)
3034 ws_right = (cur.pos() + len < par.size())
3035 ? par.isWordSeparator(cur.pos() + len)
3039 "cur.pos()=" << cur.pos() << ", res=" << res
3040 << ", separ: " << ws_left << ", " << ws_right
3043 if (ws_left && ws_right) {
3044 // Check for word separators inside the found 'word'
3045 for (int i = 0; i < len; i++) {
3046 if (par.isWordSeparator(cur.pos() + i)) {
3058 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
3061 if (! opt.casesensitive)
3062 t = lyx::to_utf8(lowercase(s));
3064 t = lyx::to_utf8(s);
3065 // Remove \n at begin
3066 while (!t.empty() && t[0] == '\n')
3069 while (!t.empty() && t[t.size() - 1] == '\n')
3070 t = t.substr(0, t.size() - 1);
3072 // Handle all other '\n'
3073 while ((pos = t.find("\n")) != string::npos) {
3074 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3076 if (isAlnumASCII(t[pos+1])) {
3077 t.replace(pos-2, 3, " ");
3080 t.replace(pos-2, 3, "");
3083 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3084 // '\n' adjacent to non-alpha-numerics, discard
3085 t.replace(pos, 1, "");
3088 // Replace all other \n with spaces
3089 t.replace(pos, 1, " ");
3092 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3093 // Kornel: Added textsl, textsf, textit, texttt and noun
3094 // + allow to seach for colored text too
3095 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3096 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3097 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3098 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3099 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3101 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3102 // FIXME - check what preceeds the brace
3104 if (opt.ignoreformat)
3105 while (regex_replace(t, t, "\\{", "_x_<")
3106 || regex_replace(t, t, "\\}", "_x_>"))
3107 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3109 while (regex_replace(t, t, "\\\\\\{", "_x_<")
3110 || regex_replace(t, t, "\\\\\\}", "_x_>"))
3111 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3118 docstring stringifyFromCursor(DocIterator const & cur, int len)
3120 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3121 if (cur.inTexted()) {
3122 Paragraph const & par = cur.paragraph();
3123 // TODO what about searching beyond/across paragraph breaks ?
3124 // TODO Try adding a AS_STR_INSERTS as last arg
3125 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3126 int(par.size()) : cur.pos() + len;
3127 // OutputParams runparams(&cur.buffer()->params().encoding());
3128 OutputParams runparams(encodings.fromLyXName("utf8"));
3129 runparams.nice = true;
3130 runparams.flavor = Flavor::XeTeX;
3131 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3132 // No side effect of file copying and image conversion
3133 runparams.dryrun = true;
3134 runparams.for_search = true;
3135 LYXERR(Debug::FIND, "Stringifying with cur: "
3136 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3137 return par.asString(cur.pos(), end,
3138 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3140 } else if (cur.inMathed()) {
3141 CursorSlice cs = cur.top();
3142 MathData md = cs.cell();
3143 MathData::const_iterator it_end =
3144 (( len == -1 || cs.pos() + len > int(md.size()))
3146 : md.begin() + cs.pos() + len );
3148 for (MathData::const_iterator it = md.begin() + cs.pos();
3151 docstring s = asString(md2);
3152 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3155 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3160 /** Computes the LaTeX export of buf starting from cur and ending len positions
3161 * after cur, if len is positive, or at the paragraph or innermost inset end
3164 docstring latexifyFromCursor(DocIterator const & cur, int len)
3166 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3167 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3168 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3169 Buffer const & buf = *cur.buffer();
3171 odocstringstream ods;
3173 //OutputParams runparams(&buf.params().encoding());
3174 OutputParams runparams(encodings.fromLyXName("utf8"));
3175 runparams.nice = false;
3176 runparams.flavor = Flavor::XeTeX;
3177 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3178 // No side effect of file copying and image conversion
3179 runparams.dryrun = true;
3180 runparams.for_search = true;
3182 if (cur.inTexted()) {
3183 // @TODO what about searching beyond/across paragraph breaks ?
3184 pos_type endpos = cur.paragraph().size();
3185 if (len != -1 && endpos > cur.pos() + len)
3186 endpos = cur.pos() + len;
3187 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3188 string(), cur.pos(), endpos);
3189 string s = lyx::to_utf8(ods.str());
3190 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3191 return(lyx::from_utf8(s));
3192 } else if (cur.inMathed()) {
3193 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3194 for (int s = cur.depth() - 1; s >= 0; --s) {
3195 CursorSlice const & cs = cur[s];
3196 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3198 cs.asInsetMath()->asHullInset()->header_write(ws);
3203 CursorSlice const & cs = cur.top();
3204 MathData md = cs.cell();
3205 MathData::const_iterator it_end =
3206 ((len == -1 || cs.pos() + len > int(md.size()))
3208 : md.begin() + cs.pos() + len);
3210 for (MathData::const_iterator it = md.begin() + cs.pos();
3214 ods << asString(md2);
3215 // Retrieve the math environment type, and add '$' or '$]'
3216 // or others (\end{equation}) accordingly
3217 for (int s = cur.depth() - 1; s >= 0; --s) {
3218 CursorSlice const & cs2 = cur[s];
3219 InsetMath * inset = cs2.asInsetMath();
3220 if (inset && inset->asHullInset()) {
3222 inset->asHullInset()->footer_write(ws);
3226 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3228 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3234 /** Finalize an advanced find operation, advancing the cursor to the innermost
3235 ** position that matches, plus computing the length of the matching text to
3238 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
3240 // Search the foremost position that matches (avoids find of entire math
3241 // inset when match at start of it)
3243 DocIterator old_cur(cur.buffer());
3245 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
3249 } while (cur && cur.depth() > d && match(cur).match_len > 0);
3251 int max_match = match(cur).match_len; /* match valid only if not searching whole words */
3252 if (max_match <= 0) return 0;
3253 LYXERR(Debug::FIND, "Ok");
3255 // Compute the match length
3257 if (cur.pos() + len > cur.lastpos())
3259 if (match.opt.matchword) {
3260 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3261 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3263 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3265 // Length of matched text (different from len param)
3266 int old_match = match(cur, len).match_len;
3270 // Greedy behaviour while matching regexps
3271 while ((new_match = match(cur, len + 1).match_len) > old_match) {
3273 old_match = new_match;
3274 LYXERR(Debug::FIND, "verifying match with len = " << len);
3281 int maxl = cur.lastpos() - cur.pos();
3282 // Greedy behaviour while matching regexps
3283 while (maxl > minl) {
3284 int actual_match = match(cur, len).match_len;
3285 if (actual_match >= max_match) {
3286 // actual_match > max_match _can_ happen,
3287 // if the search area splits
3288 // some following word so that the regex
3289 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3291 // This means, the len value is too big
3293 len = (int)((maxl + minl)/2);
3296 // (actual_match < max_match)
3298 len = (int)((maxl + minl)/2);
3302 // Search for real start of matched characters
3307 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3308 if (cur.depth() < old_cur.depth()) {
3310 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3313 if (cur.pos() != old_cur.pos()) {
3314 // OK, forwarded 1 pos in actual inset
3315 actual_match = match(cur, len-1).match_len;
3316 if (actual_match == max_match) {
3317 // Ha, got it! The shorter selection has the same match length
3322 // OK, the shorter selection matches less chars, revert to previous value
3328 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3329 actual_match = match(cur, len).match_len;
3330 if (actual_match == max_match)
3340 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
3344 while (!theApp()->longOperationCancelled() && cur) {
3345 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3346 MatchResult mres = match(cur, -1, false);
3347 int match_len = mres.match_len;
3348 LYXERR(Debug::FIND, "match_len: " << match_len);
3349 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3350 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3353 if (match_len > 0) {
3354 // Try to find the begin of searched string
3355 int increment = mres.pos/2;
3356 while (mres.pos > 5 && (increment > 5)) {
3357 DocIterator old_cur = cur;
3358 for (int i = 0; i < increment && cur; cur.forwardPos(), i++) {
3360 if (! cur || (cur.pit() > old_cur.pit())) {
3361 // Are we outside of the paragraph?
3362 // This can happen if moving past some UTF8-encoded chars
3367 MatchResult mres2 = match(cur, -1, false);
3368 if ((mres2.match2end < mres.match2end) ||
3369 (mres2.match_len < mres.match_len)) {
3376 if (increment > mres.pos/2)
3377 increment = mres.pos/2;
3381 int match_len_zero_count = 0;
3382 for (int i = 0; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
3384 int remaining_len = match(cur, -1, false).match_len;
3385 if (remaining_len <= 0) {
3386 // Apparently the searched string is not in the remaining part
3393 LYXERR(Debug::FIND, "Advancing cur: " << cur);
3394 int match_len3 = match(cur, 1).match_len;
3397 int match_len2 = match(cur).match_len;
3398 LYXERR(Debug::FIND, "match_len2: " << match_len2);
3399 if (match_len2 > 0) {
3400 // Sometimes in finalize we understand it wasn't a match
3401 // and we need to continue the outest loop
3402 int len = findAdvFinalize(cur, match);
3407 if (match_len2 >= 0) {
3408 if (match_len2 == 0)
3409 match_len_zero_count++;
3411 match_len_zero_count = 0;
3414 if (++match_len_zero_count > 3) {
3415 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
3423 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
3424 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
3427 // This should exit nested insets, if any, or otherwise undefine the currsor.
3428 cur.pos() = cur.lastpos();
3429 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3437 /// Find the most backward consecutive match within same paragraph while searching backwards.
3438 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3440 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3441 DocIterator tmp_cur = cur;
3442 int len = findAdvFinalize(tmp_cur, match);
3443 Inset & inset = cur.inset();
3444 for (; cur != cur_begin; cur.backwardPos()) {
3445 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3446 DocIterator new_cur = cur;
3447 new_cur.backwardPos();
3448 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3450 int new_len = findAdvFinalize(new_cur, match);
3455 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3461 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3465 // Backup of original position
3466 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3467 if (cur == cur_begin)
3470 DocIterator cur_orig(cur);
3471 bool pit_changed = false;
3474 bool found_match = (match(cur, -1, false).match_len > 0);
3478 cur.pos() = cur.lastpos();
3480 cur.pos() = cur_orig.pos();
3481 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3482 DocIterator cur_prev_iter;
3484 found_match = (match(cur).match_len > 0);
3485 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3486 << found_match << ", cur: " << cur);
3488 return findMostBackwards(cur, match);
3490 // Stop if begin of document reached
3491 if (cur == cur_begin)
3493 cur_prev_iter = cur;
3497 if (cur == cur_begin)
3504 } while (!theApp()->longOperationCancelled());
3512 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3513 DocIterator const & cur, int len)
3515 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3517 if (!opt.ignoreformat)
3518 return latexifyFromCursor(cur, len);
3520 return stringifyFromCursor(cur, len);
3524 FindAndReplaceOptions::FindAndReplaceOptions(
3525 docstring const & _find_buf_name, bool _casesensitive,
3526 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3527 docstring const & _repl_buf_name, bool _keep_case,
3528 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3529 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3530 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3531 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3539 /** Check if 'len' letters following cursor are all non-lowercase */
3540 static bool allNonLowercase(Cursor const & cur, int len)
3542 pos_type beg_pos = cur.selectionBegin().pos();
3543 pos_type end_pos = cur.selectionBegin().pos() + len;
3544 if (len > cur.lastpos() + 1 - beg_pos) {
3545 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3546 len = cur.lastpos() + 1 - beg_pos;
3547 end_pos = beg_pos + len;
3549 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3550 if (isLowerCase(cur.paragraph().getChar(pos)))
3556 /** Check if first letter is upper case and second one is lower case */
3557 static bool firstUppercase(Cursor const & cur)
3560 pos_type pos = cur.selectionBegin().pos();
3561 if (pos >= cur.lastpos() - 1) {
3562 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3565 ch1 = cur.paragraph().getChar(pos);
3566 ch2 = cur.paragraph().getChar(pos + 1);
3567 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3568 LYXERR(Debug::FIND, "firstUppercase(): "
3569 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3570 << ch2 << "(" << char(ch2) << ")"
3571 << ", result=" << result << ", cur=" << cur);
3576 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3578 ** \fixme What to do with possible further paragraphs in replace buffer ?
3580 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3582 ParagraphList::iterator pit = buffer.paragraphs().begin();
3583 LASSERT(!pit->empty(), /**/);
3584 pos_type right = pos_type(1);
3585 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3586 right = pit->size();
3587 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3593 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3595 Cursor & cur = bv->cursor();
3596 if (opt.repl_buf_name.empty()
3597 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3598 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3601 DocIterator sel_beg = cur.selectionBegin();
3602 DocIterator sel_end = cur.selectionEnd();
3603 if (&sel_beg.inset() != &sel_end.inset()
3604 || sel_beg.pit() != sel_end.pit()
3605 || sel_beg.idx() != sel_end.idx())
3607 int sel_len = sel_end.pos() - sel_beg.pos();
3608 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3609 << ", sel_len: " << sel_len << endl);
3612 LASSERT(sel_len > 0, return 0);
3614 if (!matchAdv(sel_beg, sel_len).match_len)
3617 // Build a copy of the replace buffer, adapted to the KeepCase option
3618 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
3620 repl_buffer_orig.write(oss);
3621 string lyx = oss.str();
3622 Buffer repl_buffer("", false);
3623 repl_buffer.setUnnamed(true);
3624 LASSERT(repl_buffer.readString(lyx), return 0);
3625 if (opt.keep_case && sel_len >= 2) {
3626 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
3627 if (cur.inTexted()) {
3628 if (firstUppercase(cur))
3629 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
3630 else if (allNonLowercase(cur, sel_len))
3631 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
3634 cap::cutSelection(cur, false);
3635 if (cur.inTexted()) {
3636 repl_buffer.changeLanguage(
3637 repl_buffer.language(),
3638 cur.getFont().language());
3639 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
3640 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
3641 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
3642 repl_buffer.params().documentClassPtr(),
3643 bv->buffer().errorList("Paste"));
3644 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
3645 sel_len = repl_buffer.paragraphs().begin()->size();
3646 } else if (cur.inMathed()) {
3647 odocstringstream ods;
3649 // OutputParams runparams(&repl_buffer.params().encoding());
3650 OutputParams runparams(encodings.fromLyXName("utf8"));
3651 runparams.nice = false;
3652 runparams.flavor = Flavor::XeTeX;
3653 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3654 runparams.dryrun = true;
3655 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
3656 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
3657 docstring repl_latex = ods.str();
3658 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
3660 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
3661 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
3662 repl_latex = from_utf8(s);
3663 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
3664 MathData ar(cur.buffer());
3665 asArray(repl_latex, ar, Parse::NORMAL);
3667 sel_len = ar.size();
3668 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3670 if (cur.pos() >= sel_len)
3671 cur.pos() -= sel_len;
3674 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3675 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
3676 bv->processUpdateFlags(Update::Force);
3681 /// Perform a FindAdv operation.
3682 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
3687 // e.g., when invoking word-findadv from mini-buffer wither with
3688 // wrong options syntax or before ever opening advanced F&R pane
3689 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3693 MatchStringAdv matchAdv(bv->buffer(), opt);
3694 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
3696 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
3697 num_replaced += findAdvReplace(bv, opt, matchAdv);
3700 match_len = findForwardAdv(cur, matchAdv);
3702 match_len = findBackwardsAdv(cur, matchAdv);
3704 // This may only be raised by lyx::regex()
3705 bv->message(_("Invalid regular expression!"));
3709 if (match_len == 0) {
3710 if (num_replaced > 0) {
3711 switch (num_replaced)
3714 bv->message(_("One match has been replaced."));
3717 bv->message(_("Two matches have been replaced."));
3720 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
3726 bv->message(_("Match not found."));
3731 if (num_replaced > 0)
3732 bv->message(_("Match has been replaced."));
3734 bv->message(_("Match found."));
3736 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
3737 bv->putSelectionAt(cur, match_len, !opt.forward);
3743 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
3745 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
3746 << opt.casesensitive << ' '
3747 << opt.matchword << ' '
3748 << opt.forward << ' '
3749 << opt.expandmacros << ' '
3750 << opt.ignoreformat << ' '
3751 << opt.replace_all << ' '
3752 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
3753 << opt.keep_case << ' '
3754 << int(opt.scope) << ' '
3757 LYXERR(Debug::FIND, "built: " << os.str());
3763 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
3765 LYXERR(Debug::FIND, "parsing");
3769 while (line != "EOSS") {
3773 if (is.eof()) // Tolerate malformed request
3777 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
3778 opt.find_buf_name = from_utf8(s);
3779 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
3780 is.get(); // Waste space before replace string
3783 while (line != "EOSS") {
3787 if (is.eof()) // Tolerate malformed request
3791 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
3792 opt.repl_buf_name = from_utf8(s);
3793 is >> opt.keep_case;
3796 opt.scope = FindAndReplaceOptions::SearchScope(i);
3798 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
3800 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
3801 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
3802 << opt.scope << ' ' << opt.restr);