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
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
35 #include "frontends/Application.h"
36 #include "frontends/alert.h"
38 #include "mathed/InsetMath.h"
39 #include "mathed/InsetMathHull.h"
40 #include "mathed/MathData.h"
41 #include "mathed/MathStream.h"
42 #include "mathed/MathSupport.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/FileName.h"
47 #include "support/gettext.h"
48 #include "support/lassert.h"
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
56 using namespace lyx::support;
61 // Helper class for deciding what should be ignored
65 IgnoreFormats() = default;
67 bool getFamily() const { return ignoreFamily_; }
69 bool getSeries() const { return ignoreSeries_; }
71 bool getShape() const { return ignoreShape_; }
73 bool getUnderline() const { return ignoreUnderline_; }
75 bool getMarkUp() const { return ignoreMarkUp_; }
77 bool getStrikeOut() const { return ignoreStrikeOut_; }
79 bool getSectioning() const { return ignoreSectioning_; }
81 bool getFrontMatter() const { return ignoreFrontMatter_; }
83 bool getColor() const { return ignoreColor_; }
85 bool getLanguage() const { return ignoreLanguage_; }
87 void setIgnoreFormat(string const & type, bool value);
91 bool ignoreFamily_ = false;
93 bool ignoreSeries_ = false;
95 bool ignoreShape_ = false;
97 bool ignoreUnderline_ = false;
99 bool ignoreMarkUp_ = false;
101 bool ignoreStrikeOut_ = false;
103 bool ignoreSectioning_ = false;
105 bool ignoreFrontMatter_ = false;
107 bool ignoreColor_ = false;
109 bool ignoreLanguage_ = false;
113 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
115 if (type == "color") {
116 ignoreColor_ = value;
118 else if (type == "language") {
119 ignoreLanguage_ = value;
121 else if (type == "sectioning") {
122 ignoreSectioning_ = value;
123 ignoreFrontMatter_ = value;
125 else if (type == "font") {
126 ignoreSeries_ = value;
127 ignoreShape_ = value;
128 ignoreFamily_ = value;
130 else if (type == "series") {
131 ignoreSeries_ = value;
133 else if (type == "shape") {
134 ignoreShape_ = value;
136 else if (type == "family") {
137 ignoreFamily_ = value;
139 else if (type == "markup") {
140 ignoreMarkUp_ = value;
142 else if (type == "underline") {
143 ignoreUnderline_ = value;
145 else if (type == "strike") {
146 ignoreStrikeOut_ = value;
150 // The global variable that can be changed from outside
151 IgnoreFormats ignoreFormats;
154 void setIgnoreFormat(string const & type, bool value)
156 ignoreFormats.setIgnoreFormat(type, value);
162 bool parse_bool(docstring & howto)
167 howto = split(howto, var, ' ');
175 MatchString(docstring const & s, bool cs, bool mw)
176 : str(s), case_sens(cs), whole_words(mw)
179 // returns true if the specified string is at the specified position
180 // del specifies whether deleted strings in ct mode will be considered
181 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
183 return par.find(str, case_sens, whole_words, pos, del);
191 // match whole words only
196 int findForward(DocIterator & cur, MatchString const & match,
197 bool find_del = true)
199 for (; cur; cur.forwardChar())
200 if (cur.inTexted()) {
201 int len = match(cur.paragraph(), cur.pos(), find_del);
209 int findBackwards(DocIterator & cur, MatchString const & match,
210 bool find_del = true)
214 if (cur.inTexted()) {
215 int len = match(cur.paragraph(), cur.pos(), find_del);
224 bool searchAllowed(docstring const & str)
227 frontend::Alert::error(_("Search error"), _("Search string is empty"));
234 bool findOne(BufferView * bv, docstring const & searchstr,
235 bool case_sens, bool whole, bool forward,
236 bool find_del = true, bool check_wrap = false)
238 if (!searchAllowed(searchstr))
241 DocIterator cur = forward
242 ? bv->cursor().selectionEnd()
243 : bv->cursor().selectionBegin();
245 MatchString const match(searchstr, case_sens, whole);
247 int match_len = forward
248 ? findForward(cur, match, find_del)
249 : findBackwards(cur, match, find_del);
252 bv->putSelectionAt(cur, match_len, !forward);
253 else if (check_wrap) {
254 DocIterator cur_orig(bv->cursor());
257 q = _("End of file reached while searching forward.\n"
258 "Continue searching from the beginning?");
260 q = _("Beginning of file reached while searching backward.\n"
261 "Continue searching from the end?");
262 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
263 q, 0, 1, _("&Yes"), _("&No"));
264 if (wrap_answer == 0) {
266 bv->cursor().clear();
267 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
269 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
270 bv->cursor().backwardPos();
272 bv->clearSelection();
273 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
276 bv->cursor().setCursor(cur_orig);
280 return match_len > 0;
284 int replaceAll(BufferView * bv,
285 docstring const & searchstr, docstring const & replacestr,
286 bool case_sens, bool whole)
288 Buffer & buf = bv->buffer();
290 if (!searchAllowed(searchstr) || buf.isReadonly())
293 DocIterator cur_orig(bv->cursor());
295 MatchString const match(searchstr, case_sens, whole);
298 int const rsize = replacestr.size();
299 int const ssize = searchstr.size();
302 cur.setCursor(doc_iterator_begin(&buf));
303 int match_len = findForward(cur, match, false);
304 while (match_len > 0) {
305 // Backup current cursor position and font.
306 pos_type const pos = cur.pos();
307 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
309 int striked = ssize -
310 cur.paragraph().eraseChars(pos, pos + match_len,
311 buf.params().track_changes);
312 cur.paragraph().insert(pos, replacestr, font,
313 Change(buf.params().track_changes
315 : Change::UNCHANGED));
316 for (int i = 0; i < rsize + striked; ++i)
319 match_len = findForward(cur, match, false);
322 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
324 cur_orig.fixIfBroken();
325 bv->setCursor(cur_orig);
331 // the idea here is that we are going to replace the string that
332 // is selected IF it is the search string.
333 // if there is a selection, but it is not the search string, then
334 // we basically ignore it. (FIXME We ought to replace only within
336 // if there is no selection, then:
337 // (i) if some search string has been provided, then we find it.
338 // (think of how the dialog works when you hit "replace" the
340 // (ii) if no search string has been provided, then we treat the
341 // word the cursor is in as the search string. (why? i have no
342 // idea.) but this only works in text?
344 // returns the number of replacements made (one, if any) and
345 // whether anything at all was done.
346 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
347 docstring const & replacestr, bool case_sens,
348 bool whole, bool forward, bool findnext)
350 Cursor & cur = bv->cursor();
351 if (!cur.selection()) {
352 // no selection, non-empty search string: find it
353 if (!searchstr.empty()) {
354 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
355 return make_pair(found, 0);
357 // empty search string
360 return make_pair(false, 0);
361 // select current word and treat it as the search string.
362 // This causes a minor bug as undo will restore this selection,
363 // which the user did not create (#8986).
364 cur.innerText()->selectWord(cur, WHOLE_WORD);
365 searchstr = cur.selectionAsString(false);
368 // if we still don't have a search string, report the error
370 if (!searchAllowed(searchstr))
371 return make_pair(false, 0);
373 bool have_selection = cur.selection();
374 docstring const selected = cur.selectionAsString(false);
377 ? searchstr == selected
378 : compare_no_case(searchstr, selected) == 0;
380 // no selection or current selection is not search word:
381 // just find the search word
382 if (!have_selection || !match) {
383 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
384 return make_pair(found, 0);
387 // we're now actually ready to replace. if the buffer is
388 // read-only, we can't, though.
389 if (bv->buffer().isReadonly())
390 return make_pair(false, 0);
392 cap::replaceSelectionWithString(cur, replacestr);
394 cur.pos() += replacestr.length();
395 LASSERT(cur.pos() <= cur.lastpos(),
396 cur.pos() = cur.lastpos());
399 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
401 return make_pair(true, 1);
407 docstring const find2string(docstring const & search,
408 bool casesensitive, bool matchword, bool forward)
412 << int(casesensitive) << ' '
413 << int(matchword) << ' '
419 docstring const replace2string(docstring const & replace,
420 docstring const & search,
421 bool casesensitive, bool matchword,
422 bool all, bool forward, bool findnext)
425 ss << replace << '\n'
427 << int(casesensitive) << ' '
428 << int(matchword) << ' '
430 << int(forward) << ' '
436 bool lyxfind(BufferView * bv, FuncRequest const & ev)
438 if (!bv || ev.action() != LFUN_WORD_FIND)
441 //lyxerr << "find called, cmd: " << ev << endl;
443 // data is of the form
445 // <casesensitive> <matchword> <forward>"
447 docstring howto = split(ev.argument(), search, '\n');
449 bool casesensitive = parse_bool(howto);
450 bool matchword = parse_bool(howto);
451 bool forward = parse_bool(howto);
453 return findOne(bv, search, casesensitive, matchword, forward, true, true);
457 bool lyxreplace(BufferView * bv,
458 FuncRequest const & ev, bool has_deleted)
460 if (!bv || ev.action() != LFUN_WORD_REPLACE)
463 // data is of the form
466 // <casesensitive> <matchword> <all> <forward> <findnext>"
469 docstring howto = split(ev.argument(), rplc, '\n');
470 howto = split(howto, search, '\n');
472 bool casesensitive = parse_bool(howto);
473 bool matchword = parse_bool(howto);
474 bool all = parse_bool(howto);
475 bool forward = parse_bool(howto);
476 bool findnext = howto.empty() ? true : parse_bool(howto);
481 int replace_count = 0;
483 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
484 update = replace_count > 0;
487 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
489 replace_count = rv.second;
492 Buffer const & buf = bv->buffer();
494 // emit message signal.
495 buf.message(_("String not found."));
497 if (replace_count == 0) {
498 buf.message(_("String found."));
499 } else if (replace_count == 1) {
500 buf.message(_("String has been replaced."));
502 docstring const str =
503 bformat(_("%1$d strings have been replaced."), replace_count);
507 } else if (findnext) {
508 // if we have deleted characters, we do not replace at all, but
509 // rather search for the next occurence
510 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
513 bv->message(_("String not found."));
519 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
521 for (; cur; cur.forwardPos())
522 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
526 DocIterator cur_orig(bv->cursor());
527 docstring q = _("End of file reached while searching forward.\n"
528 "Continue searching from the beginning?");
529 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
530 q, 0, 1, _("&Yes"), _("&No"));
531 if (wrap_answer == 0) {
532 bv->cursor().clear();
533 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
534 bv->clearSelection();
535 cur.setCursor(bv->cursor().selectionBegin());
536 if (findNextChange(bv, cur, false))
539 bv->cursor().setCursor(cur_orig);
546 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
548 for (cur.backwardPos(); cur; cur.backwardPos()) {
549 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
554 DocIterator cur_orig(bv->cursor());
555 docstring q = _("Beginning of file reached while searching backward.\n"
556 "Continue searching from the end?");
557 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
558 q, 0, 1, _("&Yes"), _("&No"));
559 if (wrap_answer == 0) {
560 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
561 bv->cursor().backwardPos();
562 bv->clearSelection();
563 cur.setCursor(bv->cursor().selectionBegin());
564 if (findPreviousChange(bv, cur, false))
567 bv->cursor().setCursor(cur_orig);
574 bool selectChange(Cursor & cur, bool forward)
576 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
578 Change ch = cur.paragraph().lookupChange(cur.pos());
580 CursorSlice tip1 = cur.top();
581 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
582 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
583 if (!ch2.isSimilarTo(ch))
586 CursorSlice tip2 = cur.top();
587 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
589 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
590 if (!ch2.isSimilarTo(ch)) {
591 // take a step forward to correctly set the selection
599 cur.bv().mouseSetCursor(cur, false);
601 cur.bv().mouseSetCursor(cur, true);
609 bool findChange(BufferView * bv, bool forward)
612 cur.setCursor(forward ? bv->cursor().selectionEnd()
613 : bv->cursor().selectionBegin());
614 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
615 return selectChange(cur, forward);
620 bool findNextChange(BufferView * bv)
622 return findChange(bv, true);
626 bool findPreviousChange(BufferView * bv)
628 return findChange(bv, false);
635 typedef vector<pair<string, string> > Escapes;
637 /// A map of symbols and their escaped equivalent needed within a regex.
638 /// @note Beware of order
639 Escapes const & get_regexp_escapes()
641 typedef std::pair<std::string, std::string> P;
643 static Escapes escape_map;
644 if (escape_map.empty()) {
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(".", "_x_."));
655 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
656 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
657 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
658 escape_map.push_back(P("_x_", "\\"));
663 /// A map of lyx escaped strings and their unescaped equivalent.
664 Escapes const & get_lyx_unescapes()
666 typedef std::pair<std::string, std::string> P;
668 static Escapes escape_map;
669 if (escape_map.empty()) {
670 escape_map.push_back(P("\\%", "%"));
671 escape_map.push_back(P("\\{", "{"));
672 escape_map.push_back(P("\\}", "}"));
673 escape_map.push_back(P("\\mathcircumflex ", "^"));
674 escape_map.push_back(P("\\mathcircumflex", "^"));
675 escape_map.push_back(P("\\backslash ", "\\"));
676 escape_map.push_back(P("\\backslash", "\\"));
677 escape_map.push_back(P("\\sim ", "~"));
678 escape_map.push_back(P("\\sim", "~"));
683 /// A map of escapes turning a regexp matching text to one matching latex.
684 Escapes const & get_regexp_latex_escapes()
686 typedef std::pair<std::string, std::string> P;
688 static Escapes escape_map;
689 if (escape_map.empty()) {
690 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
691 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
692 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
693 escape_map.push_back(P("\\[", "\\{\\[\\}"));
694 escape_map.push_back(P("\\]", "\\{\\]\\}"));
695 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
696 escape_map.push_back(P("%", "\\\\\\%"));
697 escape_map.push_back(P("#", "\\\\#"));
702 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
703 ** the found occurrence were escaped.
705 string apply_escapes(string s, Escapes const & escape_map)
707 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
708 Escapes::const_iterator it;
709 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
710 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
711 unsigned int pos = 0;
712 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
713 s.replace(pos, it->first.length(), it->second);
714 LYXERR(Debug::FIND, "After escape: " << s);
715 pos += it->second.length();
716 // LYXERR(Debug::FIND, "pos: " << pos);
719 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
724 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
725 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
726 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
727 string escape_for_regex(string s, bool match_latex)
730 while (pos < s.size()) {
731 size_t new_pos = s.find("\\regexp{", pos);
732 if (new_pos == string::npos)
736 LYXERR(Debug::FIND, "new_pos: " << new_pos);
737 t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
738 LYXERR(Debug::FIND, "t [lyx]: " << t);
739 t = apply_escapes(t, get_regexp_escapes());
740 LYXERR(Debug::FIND, "t [rxp]: " << t);
741 s.replace(pos, new_pos - pos, t);
742 new_pos = pos + t.size();
743 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
744 LYXERR(Debug::FIND, "new_pos: " << new_pos);
745 if (new_pos == s.size())
748 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
749 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
750 LYXERR(Debug::FIND, "end_pos: " << end_pos);
751 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
752 LYXERR(Debug::FIND, "t in regexp : " << t);
753 t = apply_escapes(t, get_lyx_unescapes());
754 LYXERR(Debug::FIND, "t in regexp after unescapes [lyx]: " << t);
756 t = apply_escapes(t, get_regexp_latex_escapes());
757 LYXERR(Debug::FIND, "t in regexp after latex_escapes [ltx]: " << t);
759 if (end_pos == s.size()) {
760 s.replace(new_pos, end_pos - new_pos, t);
761 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
764 s.replace(new_pos, end_pos + 13 - new_pos, t);
765 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
766 pos = new_pos + t.size();
767 LYXERR(Debug::FIND, "pos: " << pos);
773 /// Wrapper for lyx::regex_replace with simpler interface
774 bool regex_replace(string const & s, string & t, string const & searchstr,
775 string const & replacestr)
777 regex e(searchstr, regex_constants::ECMAScript);
779 ostream_iterator<char, char> it(oss);
780 regex_replace(it, s.begin(), s.end(), e, replacestr);
781 // tolerate t and s be references to the same variable
782 bool rv = (s != oss.str());
788 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
790 ** Verify that closed braces exactly match open braces. This avoids that, for example,
791 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
794 ** Number of open braces that must remain open at the end for the verification to succeed.
796 bool braces_match(string::const_iterator const & beg,
797 string::const_iterator const & end,
801 string::const_iterator it = beg;
802 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
803 for (; it != end; ++it) {
804 // Skip escaped braces in the count
809 } else if (*it == '{') {
811 } else if (*it == '}') {
812 if (open_pars == 0) {
813 LYXERR(Debug::FIND, "Found unmatched closed brace");
819 if (open_pars != unmatched) {
820 LYXERR(Debug::FIND, "Found " << open_pars
821 << " instead of " << unmatched
822 << " unmatched open braces at the end of count");
825 LYXERR(Debug::FIND, "Braces match as expected");
835 MatchResult(): match_len(0),match2end(0), pos(0) {};
838 /** The class performing a match between a position in the document and the FindAdvOptions.
840 class MatchStringAdv {
842 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
844 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
845 ** constructor as opt.search, under the opt.* options settings.
848 ** If set, then match is searched only against beginning of text starting at cur.
849 ** If unset, then match is searched anywhere in text starting at cur.
852 ** The length of the matching text, or zero if no match was found.
854 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
859 /// first buffer on which search was started
860 lyx::Buffer * const p_first_buf;
862 FindAndReplaceOptions const & opt;
865 /// Auxiliary find method (does not account for opt.matchword)
866 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
868 /** Normalize a stringified or latexified LyX paragraph.
872 ** <li>if search is not casesensitive, then lowercase the string;
873 ** <li>remove any newline at begin or end of the string;
874 ** <li>replace any newline in the middle of the string with a simple space;
875 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
878 ** @todo Normalization should also expand macros, if the corresponding
879 ** search option was checked.
881 string normalize(docstring const & s, bool hack_braces) const;
882 // normalized string to search
883 string par_as_string;
884 // regular expression to use for searching
886 // same as regexp, but prefixed with a ".*?"
888 // leading format material as string
889 string lead_as_string;
890 // par_as_string after removal of lead_as_string
891 string par_as_string_nolead;
892 // unmatched open braces in the search string/regexp
894 // number of (.*?) subexpressions added at end of search regexp for closing
895 // environments, math mode, styles, etc...
897 // Are we searching with regular expressions ?
902 static docstring buffer_to_latex(Buffer & buffer)
904 //OutputParams runparams(&buffer.params().encoding());
905 OutputParams runparams(encodings.fromLyXName("utf8"));
906 odocstringstream ods;
908 runparams.nice = true;
909 runparams.flavor = Flavor::XeTeX;
910 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
911 // No side effect of file copying and image conversion
912 runparams.dryrun = true;
913 runparams.for_search = true;
914 pit_type const endpit = buffer.paragraphs().size();
915 for (pit_type pit = 0; pit != endpit; ++pit) {
916 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
917 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
923 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
926 if (!opt.ignoreformat) {
927 str = buffer_to_latex(buffer);
929 // OutputParams runparams(&buffer.params().encoding());
930 OutputParams runparams(encodings.fromLyXName("utf8"));
931 runparams.nice = true;
932 runparams.flavor = Flavor::XeTeX;
933 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
934 runparams.dryrun = true;
935 runparams.for_search = true;
936 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
937 Paragraph const & par = buffer.paragraphs().at(pit);
938 LYXERR(Debug::FIND, "Adding to search string: '"
939 << par.asString(pos_type(0), par.size(),
940 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
943 str += par.asString(pos_type(0), par.size(),
944 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
947 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
948 string t = to_utf8(str);
949 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
956 /// Return separation pos between the leading material and the rest
957 static size_t identifyLeading(string const & s)
960 // @TODO Support \item[text]
961 // Kornel: Added textsl, textsf, textit, texttt and noun
962 // + allow to search for colored text too
963 while (regex_replace(t, t, "^\\\\(("
964 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
965 "lyxaddress|lyxrightaddress|"
966 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
967 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
968 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
969 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
970 || regex_replace(t, t, "^\\$", "")
971 || regex_replace(t, t, "^\\\\\\[", "")
972 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
973 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
975 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
980 * Given a latexified string, retrieve some handled features
981 * The features of the regex will later be compared with the features
982 * of the searched text. If the regex features are not a
983 * subset of the analized, then, in not format ignoring search
984 * we can early stop the search in the relevant inset.
986 typedef map<string, bool> Features;
988 static Features identifyFeatures(string const & s)
990 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
991 static regex const valid("^("
993 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
994 "emph|noun|text(bf|md|sl|sf|it|tt)|"
995 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
996 "(u|uu)line|(s|x)out|uwave|"
997 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
998 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1003 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1006 if (sub.str(1).compare("regexp") == 0) {
1010 string token = sub.str(1);
1012 if (regex_match(token, sub2, valid)) {
1020 if (sub.str(1).compare("endregexp") == 0) {
1030 * defines values features of a key "\\[a-z]+{"
1035 /* Char type with content discarded
1036 * like \hspace{1cm} */
1038 /* Char, like \backslash */
1040 /* \part, \section*, ... */
1042 /* title, author etc */
1044 /* \foreignlanguage{ngerman}, ... */
1047 * to discard language in content */
1050 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1052 /* fonts, colors, markups, ... */
1054 /* footnotesize, ... large, ...
1055 * Ignore all of them */
1058 /* inputencoding, ...
1059 * Discard also content, because they do not help in search */
1062 * like remove, but also all arguments */
1064 /* item, listitem */
1066 /* tex, latex, ... like isChar */
1068 /* like \lettrine[lines=5]{}{} */
1070 // like isStandard, but always remove head
1072 /* End of arguments marker for lettrine,
1073 * so that they can be ignored */
1076 KeyInfo() = default;
1077 KeyInfo(KeyType type, int parcount, bool disable)
1079 parenthesiscount(parcount),
1080 disabled(disable) {}
1081 KeyType keytype = invalid;
1083 int _tokensize = -1;
1084 int _tokenstart = -1;
1085 int _dataStart = -1;
1087 int parenthesiscount = 1;
1088 bool disabled = false;
1089 bool used = false; /* by pattern */
1094 Border(int l=0, int u=0) : low(l), upper(u) {};
1099 #define MAXOPENED 30
1101 bool isPatternString_;
1103 explicit Intervall(bool isPattern, string const & p) :
1104 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1105 hasTitle(false), langcount(0)
1113 static vector<Border> borders;
1114 int depts[MAXOPENED];
1115 int closes[MAXOPENED];
1116 int actualdeptindex;
1117 int previousNotIgnored(int) const;
1118 int nextNotIgnored(int) const;
1119 void handleOpenP(int i);
1120 void handleCloseP(int i, bool closingAllowed);
1121 void resetOpenedP(int openPos);
1122 void addIntervall(int upper);
1123 void addIntervall(int low, int upper); /* if explicit */
1124 void removeAccents();
1125 void setForDefaultLang(KeyInfo const & defLang) const;
1126 int findclosing(int start, int end, char up, char down, int repeat);
1127 void handleParentheses(int lastpos, bool closingAllowed);
1129 int langcount; // Number of disabled language specs up to current position in actual interval
1130 int isOpeningPar(int pos) const;
1132 void output(ostringstream &os, int lastpos);
1133 // string show(int lastpos);
1136 vector<Border> Intervall::borders = vector<Border>(30);
1138 int Intervall::isOpeningPar(int pos) const
1140 if ((pos < 0) || (size_t(pos) >= par.size()))
1142 if (par[pos] != '{')
1144 if (size_t(pos) + 2 >= par.size())
1146 if (par[pos+2] != '}')
1148 if (par[pos+1] == '[' || par[pos+1] == ']')
1153 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1155 // Enable the use of first token again
1156 if (ignoreidx >= 0) {
1157 int value = defLang._tokenstart + defLang._tokensize;
1163 if (borders[borderidx].low < value)
1164 borders[borderidx].low = value;
1165 if (borders[borderidx].upper < value)
1166 borders[borderidx].upper = value;
1171 static void checkDepthIndex(int val)
1173 static int maxdepthidx = MAXOPENED-2;
1174 static int lastmaxdepth = 0;
1175 if (val > lastmaxdepth) {
1176 LYXERR(Debug::INFO, "Depth reached " << val);
1179 if (val > maxdepthidx) {
1181 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1186 // Not needed, because borders are now dynamically expanded
1187 static void checkIgnoreIdx(int val)
1189 static int lastmaxignore = -1;
1190 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1191 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1192 lastmaxignore = val;
1198 * Expand the region of ignored parts of the input latex string
1199 * The region is only relevant in output()
1201 void Intervall::addIntervall(int low, int upper)
1204 if (low == upper) return;
1205 for (idx = ignoreidx+1; idx > 0; --idx) {
1206 if (low > borders[idx-1].upper) {
1210 Border br(low, upper);
1211 if (idx > ignoreidx) {
1212 if (borders.size() <= size_t(idx)) {
1213 borders.push_back(br);
1219 // checkIgnoreIdx(ignoreidx);
1223 // Expand only if one of the new bound is inside the interwall
1224 // We know here that br.low > borders[idx-1].upper
1225 if (br.upper < borders[idx].low) {
1226 // We have to insert at this pos
1227 if (size_t(ignoreidx+1) >= borders.size()) {
1228 borders.push_back(borders[ignoreidx]);
1231 borders[ignoreidx+1] = borders[ignoreidx];
1233 for (int i = ignoreidx; i > idx; --i) {
1234 borders[i] = borders[i-1];
1238 // checkIgnoreIdx(ignoreidx);
1241 // Here we know, that we are overlapping
1242 if (br.low > borders[idx].low)
1243 br.low = borders[idx].low;
1244 // check what has to be concatenated
1246 for (int i = idx; i <= ignoreidx; i++) {
1247 if (br.upper >= borders[i].low) {
1249 if (br.upper < borders[i].upper)
1250 br.upper = borders[i].upper;
1256 // count should be >= 1 here
1259 for (int i = idx + count; i <= ignoreidx; i++) {
1260 borders[i-count+1] = borders[i];
1262 ignoreidx -= count - 1;
1268 typedef map<string, string> AccentsMap;
1269 static AccentsMap accents = map<string, string>();
1271 static void buildaccent(string n, string param, string values)
1275 const char delim = '|';
1276 while (getline(s, name, delim)) {
1278 for (char c : param) {
1279 string key = name + "{" + c + "}";
1280 // get the corresponding utf8-value
1281 if ((values[start] & 0xc0) != 0xc0) {
1282 // should not happen, utf8 encoding starts at least with 11xxxxxx
1283 // but value for '\dot{i}' is 'i', which is ascii
1284 if ((values[start] & 0x80) == 0) {
1286 accents[key] = values.substr(start, 1);
1287 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1292 for (int j = 1; ;j++) {
1293 if (start + j >= values.size()) {
1294 accents[key] = values.substr(start, j);
1295 start = values.size() - 1;
1298 else if ((values[start+j] & 0xc0) != 0x80) {
1299 // This is the first byte of following utf8 char
1300 accents[key] = values.substr(start, j);
1302 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1311 static string getutf8(unsigned uchar)
1314 string ret = string();
1316 if (uchar <= 0x7f) {
1317 c[maxc-1] = uchar & 0x7f;
1320 unsigned char rest = 0x40;
1321 unsigned char first = 0x80;
1323 for (int i = start; i >=0; --i) {
1325 c[i] = first + uchar;
1328 c[i] = 0x80 | (uchar & 0x3f);
1335 for (int i = 0; i < maxc; i++) {
1336 if (c[i] == 0) continue;
1342 static void buildAccentsMap()
1344 accents["imath"] = "ı";
1346 accents["jmath"] = "ȷ";
1347 accents["cdot"] = "·";
1348 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1349 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1350 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1351 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1352 accents["negmedspace"] = getutf8(0xf0005);
1353 accents["thickspace"] = getutf8(0xf0006);
1354 accents["negthickspace"] = getutf8(0xf0007);
1355 accents["lyx"] = getutf8(0xf0010); // Used logos
1356 accents["LyX"] = getutf8(0xf0010);
1357 accents["tex"] = getutf8(0xf0011);
1358 accents["TeX"] = getutf8(0xf0011);
1359 accents["latex"] = getutf8(0xf0012);
1360 accents["LaTeX"] = getutf8(0xf0012);
1361 accents["latexe"] = getutf8(0xf0013);
1362 accents["LaTeXe"] = getutf8(0xf0013);
1363 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1364 accents["backslash LyX"] = getutf8(0xf0010);
1365 accents["backslash tex"] = getutf8(0xf0011);
1366 accents["backslash TeX"] = getutf8(0xf0011);
1367 accents["backslash latex"] = getutf8(0xf0012);
1368 accents["backslash LaTeX"] = getutf8(0xf0012);
1369 accents["backslash latexe"] = getutf8(0xf0013);
1370 accents["backslash LaTeXe"] = getutf8(0xf0013);
1371 accents["ddot{\\imath}"] = "ï";
1372 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1373 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1374 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1375 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1376 accents["acute{\\imath}"] = "í";
1377 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1378 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1379 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1380 buildaccent("mathring|r", "aAuUwy",
1382 accents["check{\\imath}"] = "ǐ";
1383 accents["check{\\jmath}"] = "ǰ";
1384 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1385 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1386 accents["hat{\\imath}"] = "î";
1387 accents["hat{\\jmath}"] = "ĵ";
1388 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1389 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1390 accents["bar{\\imath}"] = "ī";
1391 buildaccent("bar|=", "aAeEiIoOuUyY",
1392 "āĀēĒīĪōŌūŪȳȲ"); // macron
1393 accents["tilde{\\imath}"] = "ĩ";
1394 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1395 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1396 accents["breve{\\imath}"] = "ĭ";
1397 buildaccent("breve|u", "aAeEgGiIoOuU",
1398 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1399 accents["grave{\\imath}"] = "ì";
1400 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1401 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1402 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1403 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1404 buildaccent("ogonek|k", "AaEeIiUuOo",
1405 "ĄąĘęĮįŲųǪǫ"); // ogonek
1406 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1407 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1408 buildaccent("subring|textsubring", "Aa",
1410 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1411 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1412 buildaccent("subtilde|textsubtilde", "EeIiUu",
1413 "ḚḛḬḭṴṵ"); // subtilde
1414 accents["dgrave{\\imath}"] = "ȉ";
1415 accents["textdoublegrave{\\i}"] = "ȉ";
1416 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1417 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1418 accents["rcap{\\imath}"] = "ȉ";
1419 accents["textroundcap{\\i}"] = "ȉ";
1420 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1421 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1422 buildaccent("slashed", "oO",
1427 * Created accents in math or regexp environment
1428 * are macros, but we need the utf8 equivalent
1430 void Intervall::removeAccents()
1432 if (accents.empty())
1434 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1435 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1436 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?)))(?![a-zA-Z]))");
1438 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1440 string key = sub.str(1);
1441 if (accents.find(key) != accents.end()) {
1442 string val = accents[key];
1443 size_t pos = sub.position(size_t(0));
1444 for (size_t i = 0; i < val.size(); i++) {
1445 par[pos+i] = val[i];
1447 // Remove possibly following space too
1448 if (par[pos+sub.str(0).size()] == ' ')
1449 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1451 addIntervall(pos+val.size(), pos + sub.str(0).size());
1452 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1453 // remove traces of any remaining chars
1458 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1463 void Intervall::handleOpenP(int i)
1466 depts[actualdeptindex] = i+1;
1467 closes[actualdeptindex] = -1;
1468 checkDepthIndex(actualdeptindex);
1471 void Intervall::handleCloseP(int i, bool closingAllowed)
1473 if (actualdeptindex <= 0) {
1474 if (! closingAllowed)
1475 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1476 // if we are at the very end
1477 addIntervall(i, i+1);
1480 closes[actualdeptindex] = i+1;
1485 void Intervall::resetOpenedP(int openPos)
1487 // Used as initializer for foreignlanguage entry
1488 actualdeptindex = 1;
1489 depts[1] = openPos+1;
1493 int Intervall::previousNotIgnored(int start) const
1495 int idx = 0; /* int intervalls */
1496 for (idx = ignoreidx; idx >= 0; --idx) {
1497 if (start > borders[idx].upper)
1499 if (start >= borders[idx].low)
1500 start = borders[idx].low-1;
1505 int Intervall::nextNotIgnored(int start) const
1507 int idx = 0; /* int intervalls */
1508 for (idx = 0; idx <= ignoreidx; idx++) {
1509 if (start < borders[idx].low)
1511 if (start < borders[idx].upper)
1512 start = borders[idx].upper;
1517 typedef map<string, KeyInfo> KeysMap;
1518 typedef vector< KeyInfo> Entries;
1519 static KeysMap keys = map<string, KeyInfo>();
1525 Intervall interval_;
1526 void buildKeys(bool);
1527 void buildEntries(bool);
1528 void makeKey(const string &, KeyInfo, bool isPatternString);
1529 void processRegion(int start, int region_end); /* remove {} parts */
1530 void removeHead(KeyInfo const &, int count=0);
1533 LatexInfo(string const & par, bool isPatternString)
1534 : entidx_(-1), interval_(isPatternString, par)
1536 buildKeys(isPatternString);
1537 entries_ = vector<KeyInfo>();
1538 buildEntries(isPatternString);
1542 if (entries_.empty()) {
1545 if (entries_[0].keytype == KeyInfo::isTitle) {
1546 interval_.hasTitle = true;
1547 if (! entries_[0].disabled) {
1548 interval_.titleValue = entries_[0].head;
1551 interval_.titleValue = "";
1553 removeHead(entries_[0]);
1554 if (entries_.size() > 1)
1563 if (int(entries_.size()) > entidx_) {
1570 bool setNextKey(int idx) {
1571 if ((idx == entidx_) && (entidx_ >= 0)) {
1578 int find(int start, KeyInfo::KeyType keytype) const {
1582 while (tmpIdx < int(entries_.size())) {
1583 if (entries_[tmpIdx].keytype == keytype)
1589 int process(ostringstream & os, KeyInfo const & actual);
1590 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1591 // string show(int lastpos) { return interval.show(lastpos);};
1592 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1593 KeyInfo &getKeyInfo(int keyinfo) {
1594 static KeyInfo invalidInfo = KeyInfo();
1595 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1598 return entries_[keyinfo];
1600 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1601 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1605 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1609 for (int i = start; i < end; i += 1 + skip) {
1613 if (c == '\\') skip = 1;
1617 else if (c == down) {
1620 if ((repeat <= 0) || (par[i+1] != up))
1638 vector<MathEntry> entries_;
1643 void insert(string const & wait, size_t start, size_t end) {
1644 MathEntry m = MathEntry();
1646 m.mathStart = start;
1648 m.mathSize = end - start;
1649 entries_.push_back(m);
1651 bool empty() const { return entries_.empty(); };
1652 size_t getEndPos() const {
1653 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1656 return entries_[actualIdx_].mathEnd;
1658 size_t getStartPos() const {
1659 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1660 return 100000; /* definitely enough? */
1662 return entries_[actualIdx_].mathStart;
1664 size_t getFirstPos() {
1666 return getStartPos();
1668 size_t getSize() const {
1669 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1672 return entries_[actualIdx_].mathSize;
1674 void incrEntry() { actualIdx_++; };
1677 void LatexInfo::buildEntries(bool isPatternString)
1679 static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\}");
1680 static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1681 static bool disableLanguageOverride = false;
1682 smatch sub, submath;
1683 bool evaluatingRegexp = false;
1685 bool evaluatingMath = false;
1686 bool evaluatingCode = false;
1688 bool evaluatingOptional = false;
1689 size_t optionalEnd = 0;
1692 bool math_end_waiting = false;
1693 size_t math_pos = 10000;
1696 interval_.removeAccents();
1698 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1700 if (math_end_waiting) {
1701 size_t pos = submath.position(size_t(0));
1702 if ((math_end == "$") &&
1703 (submath.str(0) == "$") &&
1704 (interval_.par[pos-1] != '\\')) {
1705 mi.insert("$", math_pos, pos + 1);
1706 math_end_waiting = false;
1708 else if ((math_end == "\\]") &&
1709 (submath.str(0) == "\\]")) {
1710 mi.insert("\\]", math_pos, pos + 2);
1711 math_end_waiting = false;
1713 else if ((submath.str(1).compare("end") == 0) &&
1714 (submath.str(2).compare(math_end) == 0)) {
1715 mi.insert(math_end, math_pos, pos + submath.str(0).length());
1716 math_end_waiting = false;
1722 if (submath.str(1).compare("begin") == 0) {
1723 math_end_waiting = true;
1724 math_end = submath.str(2);
1725 math_pos = submath.position(size_t(0));
1727 else if (submath.str(0).compare("\\[") == 0) {
1728 math_end_waiting = true;
1730 math_pos = submath.position(size_t(0));
1732 else if (submath.str(0) == "$") {
1733 size_t pos = submath.position(size_t(0));
1734 if ((pos == 0) || (interval_.par[pos-1] != '\\')) {
1735 math_end_waiting = true;
1742 // Ignore language if there is math somewhere in pattern-string
1743 if (isPatternString) {
1746 keys["foreignlanguage"].disabled = true;
1747 disableLanguageOverride = true;
1750 disableLanguageOverride = false;
1753 if (disableLanguageOverride) {
1754 keys["foreignlanguage"].disabled = true;
1757 math_pos = mi.getFirstPos();
1758 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1760 string key = sub.str(3);
1762 if (sub.str(0)[0] == '\\')
1763 key = sub.str(0)[1];
1767 size_t k_pos = sub.position(size_t(0));
1768 if ((k_pos > 0) && (interval_.par[k_pos - 1] == '\\')) {
1769 // Escaped '$', ignoring
1775 if (keys.find(key) != keys.end()) {
1776 if (keys[key].keytype == KeyInfo::headRemove) {
1777 KeyInfo found1 = keys[key];
1778 found1.disabled = true;
1779 found1.head = "\\" + key + "{";
1780 found1._tokenstart = sub.position(size_t(0));
1781 found1._tokensize = found1.head.length();
1782 found1._dataStart = found1._tokenstart + found1.head.length();
1783 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1784 found1._dataEnd = endpos;
1789 if (evaluatingRegexp) {
1790 if (sub.str(1).compare("endregexp") == 0) {
1791 evaluatingRegexp = false;
1792 // found._tokenstart already set
1793 found._dataEnd = sub.position(size_t(0)) + 13;
1794 found._dataStart = found._dataEnd;
1795 found._tokensize = found._dataEnd - found._tokenstart;
1796 found.parenthesiscount = 0;
1797 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1804 if (evaluatingMath) {
1805 if (size_t(sub.position(size_t(0))) < mi.getEndPos())
1807 evaluatingMath = false;
1809 math_pos = mi.getStartPos();
1811 if (keys.find(key) == keys.end()) {
1812 found = KeyInfo(KeyInfo::isStandard, 0, true);
1813 if (isPatternString) {
1814 found.keytype = KeyInfo::isChar;
1815 found.disabled = false;
1822 if (key.compare("regexp") == 0) {
1823 evaluatingRegexp = true;
1824 found._tokenstart = sub.position(size_t(0));
1825 found._tokensize = 0;
1829 // Handle the other params of key
1830 if (found.keytype == KeyInfo::isIgnored)
1832 else if (found.keytype == KeyInfo::isMath) {
1833 if (size_t(sub.position(size_t(0))) == math_pos) {
1835 found._tokenstart = sub.position(size_t(0));
1836 found._tokensize = mi.getSize();
1837 found._dataEnd = found._tokenstart + found._tokensize;
1838 found._dataStart = found._dataEnd;
1839 found.parenthesiscount = 0;
1840 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1841 evaluatingMath = true;
1844 // begin|end of unknown env, discard
1845 // First handle tables
1846 // longtable|tabular
1847 bool discardComment;
1849 found.keytype = KeyInfo::doRemove;
1850 if ((sub.str(5).compare("longtable") == 0) ||
1851 (sub.str(5).compare("tabular") == 0)) {
1852 discardComment = true; /* '%' */
1855 discardComment = false;
1856 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1858 string token = sub.str(5);
1859 if (regex_match(token, sub2, removeArgs)) {
1860 found.keytype = KeyInfo::removeWithArg;
1863 // discard spaces before pos(0)
1864 int pos = sub.position(size_t(0));
1866 for (count = 0; pos - count > 0; count++) {
1867 char c = interval_.par[pos-count-1];
1868 if (discardComment) {
1869 if ((c != ' ') && (c != '%'))
1875 found._tokenstart = pos - count;
1876 if (sub.str(1).compare(0, 5, "begin") == 0) {
1877 size_t pos1 = pos + sub.str(0).length();
1878 if (sub.str(5).compare("cjk") == 0) {
1879 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1880 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1882 found.keytype = KeyInfo::isMain;
1883 found._dataStart = pos1;
1884 found._dataEnd = interval_.par.length();
1885 found.disabled = keys["foreignlanguage"].disabled;
1886 found.used = keys["foreignlanguage"].used;
1887 found._tokensize = pos1 - found._tokenstart;
1888 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1891 // Swallow possible optional params
1892 while (interval_.par[pos1] == '[') {
1893 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1895 // Swallow also the eventual parameter
1896 if (interval_.par[pos1] == '{') {
1897 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1900 found._dataEnd = pos1;
1902 found._dataStart = found._dataEnd;
1903 found._tokensize = count + found._dataEnd - pos;
1904 found.parenthesiscount = 0;
1905 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1906 found.disabled = true;
1910 // Handle "\end{...}"
1911 found._dataStart = pos + sub.str(0).length();
1912 found._dataEnd = found._dataStart;
1913 found._tokensize = count + found._dataEnd - pos;
1914 found.parenthesiscount = 0;
1915 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1916 found.disabled = true;
1920 else if (found.keytype != KeyInfo::isRegex) {
1921 found._tokenstart = sub.position(size_t(0));
1922 if (found.parenthesiscount == 0) {
1923 // Probably to be discarded
1924 size_t following_pos = sub.position(size_t(0)) + sub.str(3).length() + 1;
1925 char following = interval_.par[following_pos];
1926 if (following == ' ')
1927 found.head = "\\" + sub.str(3) + " ";
1928 else if (following == '=') {
1929 // like \uldepth=1000pt
1930 found.head = sub.str(0);
1933 found.head = "\\" + key;
1934 found._tokensize = found.head.length();
1935 found._dataEnd = found._tokenstart + found._tokensize;
1936 found._dataStart = found._dataEnd;
1939 int params = found._tokenstart + key.length() + 1;
1940 if (evaluatingOptional) {
1941 if (size_t(found._tokenstart) > optionalEnd) {
1942 evaluatingOptional = false;
1945 found.disabled = true;
1948 int optend = params;
1949 while (interval_.par[optend] == '[') {
1950 // discard optional parameters
1951 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
1953 if (optend > params) {
1954 key += interval_.par.substr(params, optend-params);
1955 evaluatingOptional = true;
1956 optionalEnd = optend;
1958 string token = sub.str(5);
1959 int closings = found.parenthesiscount;
1960 if (found.parenthesiscount == 1) {
1961 found.head = "\\" + key + "{";
1963 else if (found.parenthesiscount > 1) {
1965 found.head = sub.str(0) + "{";
1966 closings = found.parenthesiscount - 1;
1969 found.head = "\\" + key + "{";
1972 found._tokensize = found.head.length();
1973 found._dataStart = found._tokenstart + found.head.length();
1974 if (found.keytype == KeyInfo::doRemove) {
1975 int endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1976 found._dataStart = endpar;
1977 found._tokensize = found._dataStart - found._tokenstart;
1980 if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
1981 found._dataStart += 15;
1985 endpos = found._dataStart - 1;
1987 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1988 if (found.keytype == KeyInfo::isList) {
1989 // Check if it really is list env
1990 static regex const listre("^([a-z]+)$");
1992 if (!regex_match(token, sub2, listre)) {
1993 // Change the key of this entry. It is not in a list/item environment
1994 found.keytype = KeyInfo::endArguments;
1997 if (found.keytype == KeyInfo::noMain) {
1998 evaluatingCode = true;
2000 codeStart = found._dataStart;
2002 else if (evaluatingCode) {
2003 if (size_t(found._dataStart) > codeEnd)
2004 evaluatingCode = false;
2005 else if (found.keytype == KeyInfo::isMain) {
2006 // Disable this key, treate it as standard
2007 found.keytype = KeyInfo::isStandard;
2008 found.disabled = true;
2009 if ((codeEnd == interval_.par.length()) &&
2010 (found._tokenstart == codeStart)) {
2011 // trickery, because the code inset starts
2012 // with \selectlanguage ...
2014 if (entries_.size() > 1) {
2015 entries_[entries_.size()-1]._dataEnd = codeEnd;
2020 if ((endpos == interval_.par.length()) &&
2021 (found.keytype == KeyInfo::doRemove)) {
2022 // Missing closing => error in latex-input?
2023 // therefore do not delete remaining data
2024 found._dataStart -= 1;
2025 found._dataEnd = found._dataStart;
2028 found._dataEnd = endpos;
2030 if (isPatternString) {
2031 keys[key].used = true;
2034 entries_.push_back(found);
2038 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2040 stringstream s(keysstring);
2042 const char delim = '|';
2043 while (getline(s, key, delim)) {
2044 KeyInfo keyII(keyI);
2045 if (isPatternString) {
2048 else if ( !keys[key].used)
2049 keyII.disabled = true;
2054 void LatexInfo::buildKeys(bool isPatternString)
2057 static bool keysBuilt = false;
2058 if (keysBuilt && !isPatternString) return;
2060 // Keys to ignore in any case
2061 makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2062 // Known standard keys with 1 parameter.
2063 // Split is done, if not at start of region
2064 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2065 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2066 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2067 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2068 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2069 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2071 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2072 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2073 makeKey("section*|subsection*|subsubsection*|paragraph*",
2074 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2075 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2076 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2078 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2080 // Split is done, if not at start of region
2081 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2082 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2084 // Split is done always.
2085 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2089 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2090 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2091 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2092 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2094 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2095 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2096 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2097 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2099 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2100 // Custom space/skip, remove the content (== length value)
2101 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2102 // Found in fr/UserGuide.lyx
2103 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2105 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2106 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2107 // Known macros to remove (including their parameter)
2109 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2110 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2111 // handle like standard keys with 1 parameter.
2112 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2114 // Ignore deleted text
2115 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2116 // but preserve added text
2117 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2119 // Macros to remove, but let the parameter survive
2121 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2123 // Remove language spec from content of these insets
2124 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2126 // Same effect as previous, parameter will survive (because there is no one anyway)
2128 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2129 // Remove table decorations
2130 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2131 // Discard shape-header.
2132 // For footnote or shortcut too, because of lang settings
2133 // and wrong handling if used 'KeyInfo::noMain'
2134 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2135 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2136 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2137 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2138 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2139 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2140 // like ('tiny{}' or '\tiny ' ... )
2141 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2143 // Survives, like known character
2144 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2145 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2147 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2148 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2149 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2151 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2152 // Remove RTL/LTR marker
2153 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2154 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2155 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2156 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2157 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2158 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2159 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2160 if (isPatternString) {
2161 // Allow the first searched string to rebuild the keys too
2165 // no need to rebuild again
2171 * Keep the list of actual opened parentheses actual
2172 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2174 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2177 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2181 if (c == '\\') skip = 1;
2182 else if (c == '{') {
2185 else if (c == '}') {
2186 handleCloseP(i, closingAllowed);
2192 string Intervall::show(int lastpos)
2194 int idx = 0; /* int intervalls */
2197 for (idx = 0; idx <= ignoreidx; idx++) {
2198 while (i < lastpos) {
2200 if (i <= borders[idx].low) {
2201 if (borders[idx].low > lastpos)
2202 printsize = lastpos - i;
2204 printsize = borders[idx].low - i;
2205 s += par.substr(i, printsize);
2207 if (i >= borders[idx].low)
2208 i = borders[idx].upper;
2211 i = borders[idx].upper;
2217 s += par.substr(i, lastpos-i);
2223 void Intervall::output(ostringstream &os, int lastpos)
2225 // get number of chars to output
2226 int idx = 0; /* int intervalls */
2229 string startTitle = titleValue;
2230 for (idx = 0; idx <= ignoreidx; idx++) {
2232 if (i <= borders[idx].low) {
2234 if (borders[idx].low > lastpos)
2235 printsize = lastpos - i;
2237 printsize = borders[idx].low - i;
2238 if (printsize > 0) {
2239 os << startTitle << par.substr(i, printsize);
2241 printed += printsize;
2244 handleParentheses(i, false);
2245 if (i >= borders[idx].low)
2246 i = borders[idx].upper;
2249 i = borders[idx].upper;
2256 os << startTitle << par.substr(i, lastpos-i);
2257 printed += lastpos-i;
2259 handleParentheses(lastpos, false);
2261 if (keys["foreignlanguage"].disabled)
2262 startindex = actualdeptindex-langcount;
2264 startindex = actualdeptindex;
2265 for (int i = startindex; i > 0; --i) {
2268 if (hasTitle && (printed > 0))
2270 if (! isPatternString_)
2272 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2275 void LatexInfo::processRegion(int start, int region_end)
2277 while (start < region_end) { /* Let {[} and {]} survive */
2278 int cnt = interval_.isOpeningPar(start);
2280 // Closing is allowed past the region
2281 int closing = interval_.findclosing(start+1, interval_.par.length());
2282 interval_.addIntervall(start, start+1);
2283 interval_.addIntervall(closing, closing+1);
2287 start = interval_.nextNotIgnored(start+1);
2291 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2293 if (actual.parenthesiscount == 0) {
2294 // "{\tiny{} ...}" ==> "{{} ...}"
2295 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2298 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2299 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2300 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2304 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2307 switch (actual.keytype)
2309 case KeyInfo::isTitle: {
2311 nextKeyIdx = getNextKey();
2314 case KeyInfo::cleanToStart: {
2315 actual._dataEnd = actual._dataStart;
2316 nextKeyIdx = getNextKey();
2317 // Search for end of arguments
2318 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2320 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2321 entries_[i].disabled = true;
2323 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2325 while (interval_.par[actual._dataEnd] == ' ')
2327 interval_.addIntervall(0, actual._dataEnd+1);
2328 interval_.actualdeptindex = 0;
2329 interval_.depts[0] = actual._dataEnd+1;
2330 interval_.closes[0] = -1;
2333 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2334 if (actual.disabled)
2335 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2337 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2340 case KeyInfo::isChar: {
2341 nextKeyIdx = getNextKey();
2344 case KeyInfo::isSize: {
2345 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2346 processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
2347 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2348 nextKeyIdx = getNextKey();
2350 // Here _dataStart points to '{', so correct it
2351 actual._dataStart += 1;
2352 actual._tokensize += 1;
2353 actual.parenthesiscount = 1;
2354 if (interval_.par[actual._dataStart] == '}') {
2355 // Determine the end if used like '{\tiny{}...}'
2356 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2357 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2360 // Determine the end if used like '\tiny{...}'
2361 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2363 // Split on this key if not at start
2364 int start = interval_.nextNotIgnored(previousStart);
2365 if (start < actual._tokenstart) {
2366 interval_.output(os, actual._tokenstart);
2367 interval_.addIntervall(start, actual._tokenstart);
2369 // discard entry if at end of actual
2370 nextKeyIdx = process(os, actual);
2374 case KeyInfo::endArguments: {
2375 // Remove trailing '{}' too
2376 actual._dataStart += 1;
2377 actual._dataEnd += 1;
2378 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2379 nextKeyIdx = getNextKey();
2382 case KeyInfo::noMain:
2384 case KeyInfo::isStandard: {
2385 if (actual.disabled) {
2387 processRegion(actual._dataStart, actual._dataStart+1);
2388 nextKeyIdx = getNextKey();
2390 // Split on this key if not at datastart of calling entry
2391 int start = interval_.nextNotIgnored(previousStart);
2392 if (start < actual._tokenstart) {
2393 interval_.output(os, actual._tokenstart);
2394 interval_.addIntervall(start, actual._tokenstart);
2396 // discard entry if at end of actual
2397 nextKeyIdx = process(os, actual);
2401 case KeyInfo::removeWithArg: {
2402 nextKeyIdx = getNextKey();
2403 // Search for end of arguments
2404 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2406 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2407 entries_[i].disabled = true;
2409 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2411 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2414 case KeyInfo::doRemove: {
2415 // Remove the key with all parameters and following spaces
2417 for (pos = actual._dataEnd+1; pos < interval_.par.length(); pos++) {
2418 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2421 // Remove also enclosing parentheses [] and {}
2424 while (actual._tokenstart > numpars) {
2425 if (pos+numpars >= interval_.par.size())
2427 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2429 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2435 if (interval_.par[pos+numpars] == ' ')
2439 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2440 nextKeyIdx = getNextKey();
2443 case KeyInfo::isList: {
2444 // Discard space before _tokenstart
2446 for (count = 0; count < actual._tokenstart; count++) {
2447 if (interval_.par[actual._tokenstart-count-1] != ' ')
2450 nextKeyIdx = getNextKey();
2451 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2453 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2455 // How else can we catch this one?
2456 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2457 entries_[i].disabled = true;
2459 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2461 else if (nextKeyIdx > 0) {
2462 // Ignore any lang entries inside data region
2463 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2464 if (entries_[i].keytype == KeyInfo::isMain)
2465 entries_[i].disabled = true;
2468 if (actual.disabled) {
2469 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2472 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2474 if (interval_.par[actual._dataEnd+1] == '[') {
2475 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2476 if ((interval_.par[actual._dataEnd+2] == '{') &&
2477 (interval_.par[posdown-1] == '}')) {
2478 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2479 interval_.addIntervall(posdown-1, posdown+1);
2482 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2483 interval_.addIntervall(posdown, posdown+1);
2485 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2486 if (blk > posdown) {
2487 // Discard at most 1 space after empty item
2489 for (count = 0; count < 1; count++) {
2490 if (interval_.par[blk+count] != ' ')
2494 interval_.addIntervall(blk, blk+count);
2499 case KeyInfo::isSectioning: {
2500 // Discard spaces before _tokenstart
2502 int val = actual._tokenstart;
2503 for (count = 0; count < actual._tokenstart;) {
2504 val = interval_.previousNotIgnored(val-1);
2505 if (val < 0 || interval_.par[val] != ' ')
2508 count = actual._tokenstart - val;
2511 if (actual.disabled) {
2512 removeHead(actual, count);
2513 nextKeyIdx = getNextKey();
2515 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2516 nextKeyIdx = process(os, actual);
2520 case KeyInfo::isMath: {
2521 // Same as regex, use the content unchanged
2522 nextKeyIdx = getNextKey();
2525 case KeyInfo::isRegex: {
2526 // DO NOT SPLIT ON REGEX
2528 nextKeyIdx = getNextKey();
2531 case KeyInfo::isIgnored: {
2532 // Treat like a character for now
2533 nextKeyIdx = getNextKey();
2536 case KeyInfo::isMain: {
2537 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2538 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2539 if (actual._tokenstart > 0) {
2540 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2541 if ((prev >= 0) && interval_.par[prev] == '%')
2542 interval_.addIntervall(prev, prev+1);
2544 if (actual.disabled) {
2546 interval_.langcount++;
2547 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2548 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2549 // Discard also the space before math-equation
2550 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2552 nextKeyIdx = getNextKey();
2553 // interval.resetOpenedP(actual._dataStart-1);
2556 if (actual._tokenstart < 26) {
2557 // for the first (and maybe dummy) language
2558 interval_.setForDefaultLang(actual);
2560 interval_.resetOpenedP(actual._dataStart-1);
2564 case KeyInfo::invalid:
2565 case KeyInfo::headRemove:
2566 // These two cases cannot happen, already handled
2569 // LYXERR(Debug::INFO, "Unhandled keytype");
2570 nextKeyIdx = getNextKey();
2577 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2579 int end = interval_.nextNotIgnored(actual._dataEnd);
2580 int oldStart = actual._dataStart;
2581 int nextKeyIdx = getNextKey();
2583 if ((nextKeyIdx < 0) ||
2584 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2585 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2586 if (oldStart <= end) {
2587 processRegion(oldStart, end);
2592 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2594 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2595 (void) dispatch(os, actual._dataStart, nextKey);
2596 end = nextKey._tokenstart;
2599 processRegion(oldStart, nextKey._tokenstart);
2600 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2602 oldStart = nextKey._dataEnd+1;
2604 // now nextKey is either invalid or is outside of actual._dataEnd
2605 // output the remaining and discard myself
2606 if (oldStart <= end) {
2607 processRegion(oldStart, end);
2609 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2611 // This is the normal case.
2612 // But if using the firstlanguage, the closing may be missing
2614 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2616 if (actual._dataEnd < end)
2617 output_end = interval_.nextNotIgnored(actual._dataEnd);
2619 output_end = interval_.nextNotIgnored(end);
2620 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2621 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2623 // Remove possible empty data
2624 int dstart = interval_.nextNotIgnored(actual._dataStart);
2625 while (interval_.isOpeningPar(dstart) == 1) {
2626 interval_.addIntervall(dstart, dstart+1);
2627 int dend = interval_.findclosing(dstart+1, output_end);
2628 interval_.addIntervall(dend, dend+1);
2629 dstart = interval_.nextNotIgnored(dstart+1);
2631 if (dstart < output_end)
2632 interval_.output(os, output_end);
2633 interval_.addIntervall(actual._tokenstart, end);
2637 string splitOnKnownMacros(string par, bool isPatternString)
2640 LatexInfo li(par, isPatternString);
2641 // LYXERR(Debug::INFO, "Berfore split: " << par);
2642 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2644 DummyKey._tokensize = 0;
2645 DummyKey._dataStart = 0;
2646 DummyKey._dataEnd = par.length();
2647 DummyKey.disabled = true;
2648 int firstkeyIdx = li.getFirstKey();
2650 if (firstkeyIdx >= 0) {
2651 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2652 DummyKey._tokenstart = firstKey._tokenstart;
2654 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2655 // Use dummy firstKey
2656 firstKey = DummyKey;
2657 (void) li.setNextKey(firstkeyIdx);
2660 if (par.substr(firstKey._dataStart, 2) == "% ")
2661 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2663 nextkeyIdx = li.process(os, firstKey);
2664 while (nextkeyIdx >= 0) {
2665 // Check for a possible gap between the last
2666 // entry and this one
2667 int datastart = li.nextNotIgnored(firstKey._dataStart);
2668 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2669 if ((nextKey._tokenstart > datastart)) {
2671 firstKey._dataStart = datastart;
2672 firstKey._dataEnd = par.length();
2673 (void) li.setNextKey(nextkeyIdx);
2674 // Fake the last opened parenthesis
2675 li.setForDefaultLang(firstKey);
2676 nextkeyIdx = li.process(os, firstKey);
2679 if (nextKey.keytype != KeyInfo::isMain) {
2680 firstKey._dataStart = datastart;
2681 firstKey._dataEnd = nextKey._dataEnd+1;
2682 (void) li.setNextKey(nextkeyIdx);
2683 li.setForDefaultLang(firstKey);
2684 nextkeyIdx = li.process(os, firstKey);
2687 nextkeyIdx = li.process(os, nextKey);
2691 // Handle the remaining
2692 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2693 firstKey._dataEnd = par.length();
2695 if ((firstKey._dataStart < firstKey._dataEnd) &&
2696 (par[firstKey._dataStart] != '}')) {
2697 li.setForDefaultLang(firstKey);
2698 (void) li.process(os, firstKey);
2702 // return string definitelly impossible to match
2703 s = "\\foreignlanguage{ignore}{ }";
2707 s = par; /* no known macros found */
2708 // LYXERR(Debug::INFO, "After split: " << s);
2713 * Try to unify the language specs in the latexified text.
2714 * Resulting modified string is set to "", if
2715 * the searched tex does not contain all the features in the search pattern
2717 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2719 static Features regex_f;
2720 static int missed = 0;
2721 static bool regex_with_format = false;
2723 int parlen = par.length();
2725 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2728 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2729 // Happens to be there in case of description or labeling environment
2734 // Split the latex input into pieces which
2735 // can be digested by our search engine
2736 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2737 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2738 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2741 result = par.substr(0, parlen);
2742 if (isPatternString) {
2745 regex_f = identifyFeatures(result);
2746 string features = "";
2747 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2748 string a = it->first;
2749 regex_with_format = true;
2750 features += " " + a;
2751 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2753 LYXERR(Debug::FIND, "Identified Features" << features);
2756 } else if (regex_with_format) {
2757 Features info = identifyFeatures(result);
2758 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2759 string a = it->first;
2760 bool b = it->second;
2761 if (b && ! info[a]) {
2763 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2769 // LYXERR(Debug::INFO, "No regex formats");
2775 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2776 static int identifyClosing(string & t)
2778 int open_braces = 0;
2780 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2781 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2783 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2785 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2787 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2796 static int num_replaced = 0;
2797 static bool previous_single_replace = true;
2799 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2800 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2802 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2803 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2804 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2805 if (opt.replace_all && previous_single_replace) {
2806 previous_single_replace = false;
2809 else if (!opt.replace_all) {
2810 num_replaced = 0; // count number of replaced strings
2811 previous_single_replace = true;
2813 // When using regexp, braces are hacked already by escape_for_regex()
2814 par_as_string = normalize(ds, !use_regexp);
2816 close_wildcards = 0;
2818 size_t lead_size = 0;
2819 // correct the language settings
2820 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2821 if (opt.ignoreformat) {
2823 // if par_as_string_nolead were emty,
2824 // the following call to findAux will always *find* the string
2825 // in the checked data, and thus always using the slow
2826 // examining of the current text part.
2827 par_as_string_nolead = par_as_string;
2830 lead_size = identifyLeading(par_as_string);
2831 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2832 lead_as_string = par_as_string.substr(0, lead_size);
2833 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2837 open_braces = identifyClosing(par_as_string);
2838 identifyClosing(par_as_string_nolead);
2839 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2840 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2842 string lead_as_regexp;
2843 if (lead_size > 0) {
2844 // @todo No need to search for \regexp{} insets in leading material
2845 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2846 par_as_string = par_as_string_nolead;
2847 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2848 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2850 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
2851 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2852 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2853 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2855 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2856 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2857 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2858 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2859 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2860 || regex_replace(par_as_string, par_as_string,
2861 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2862 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2863 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2867 if (!opt.ignoreformat) {
2868 // Remove extra '\}' at end if not part of \{\.\}
2869 size_t lng = par_as_string.size();
2871 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
2873 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
2882 if (lng < par_as_string.size())
2883 par_as_string = par_as_string.substr(0,lng);
2886 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2887 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2888 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2889 // replace '[^...]' with '[^...\}\{\\]'
2890 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2891 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2892 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2894 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2897 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2898 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2899 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
2900 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2902 // If entered regexp must match at begin of searched string buffer
2903 // Kornel: Added parentheses to use $1 for size of the leading string
2907 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2908 // Unfortunately is '\1', '\2', etc not working for strings with extra format
2909 // so the convert has no effect in that case
2910 for (int i = 8; i > 0; --i) {
2911 string orig = "\\\\" + std::to_string(i);
2912 string dest = "\\" + std::to_string(i+1);
2913 while (regex_replace(par_as_string, par_as_string, orig, dest));
2915 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2916 regexp2_str = "(" + lead_as_regexp + ").*?" + par_as_string;
2918 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2919 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2920 if (! opt.casesensitive) {
2921 regexp = regex(regexp_str, std::regex_constants::icase);
2922 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2925 regexp = regex(regexp_str);
2926 regexp2 = regex(regexp2_str);
2932 // Count number of characters in string
2936 // \\[a-zA-Z]+ ==> 1
2937 static int computeSize(string s, int len)
2943 for (int i = 0; i < len; i += skip, count++) {
2946 if (isalpha(s[i+1])) {
2947 for (int j = 2; i+j < len; j++) {
2948 if (! isalpha(s[i+j])) {
2951 else if ((s[i+j] == '{') && s[i+j+1] == '}')
2953 else if ((s[i+j] == '{') && (i + j + 1 >= len))
2961 else if (s[i] == '{') {
2967 else if (s[i] == '-') {
2968 if (s[i+1] == '-') {
2984 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2989 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2992 docstring docstr = stringifyFromForSearch(opt, cur, len);
2994 if (use_regexp || opt.casesensitive)
2995 str = normalize(docstr, true);
2997 str = normalize(lowercase(docstr), true);
2998 if (!opt.ignoreformat) {
2999 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3002 mres.match_len = -1;
3005 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
3006 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3009 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3010 regex const *p_regexp;
3011 regex_constants::match_flag_type flags;
3013 flags = regex_constants::match_continuous;
3016 flags = regex_constants::match_default;
3017 p_regexp = ®exp2;
3019 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3020 if (re_it == sregex_iterator())
3022 match_results<string::const_iterator> const & m = *re_it;
3024 // Check braces on segments that matched all (.*?) subexpressions,
3025 // except the last "padding" one inserted by lyx.
3026 for (size_t i = 1; i < m.size() - 1; ++i)
3027 if (!braces_match(m[i].first, m[i].second, open_braces))
3030 // Exclude from the returned match length any length
3031 // due to close wildcards added at end of regexp
3032 // and also the length of the leading (e.g. '\emph{}')
3034 // Whole found string, including the leading: m[0].second - m[0].first
3035 // Size of the leading string: m[1].second - m[1].first
3036 int leadingsize = 0;
3038 leadingsize = m[1].second - m[1].first;
3040 for (size_t i = 0; i < m.size(); i++) {
3041 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
3043 if (close_wildcards == 0)
3044 result = m[0].second - m[0].first;
3047 result = m[m.size() - close_wildcards].first - m[0].first;
3049 size_t pos = m.position(size_t(0));
3050 // Ignore last closing characters
3051 while (result > 0) {
3052 if (str[pos+result-1] == '}')
3057 if (result > leadingsize)
3058 result -= leadingsize;
3061 mres.match_len = computeSize(str.substr(pos+leadingsize,result), result);
3062 mres.match2end = str.size() - pos - leadingsize;
3063 mres.pos = pos+leadingsize;
3067 // else !use_regexp: but all code paths above return
3068 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3069 << par_as_string << "', str='" << str << "'");
3070 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3071 << lead_as_string << "', par_as_string_nolead='"
3072 << par_as_string_nolead << "'");
3075 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3076 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3077 if (str.substr(0, par_as_string.size()) == par_as_string) {
3078 mres.match_len = par_as_string.size();
3079 mres.match2end = str.size();
3084 // Start the search _after_ the leading part
3085 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3086 if (pos != string::npos) {
3087 mres.match_len = par_as_string.size();
3088 mres.match2end = str.size() - pos;
3097 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3099 MatchResult mres = findAux(cur, len, at_begin);
3100 int res = mres.match_len;
3102 "res=" << res << ", at_begin=" << at_begin
3103 << ", matchword=" << opt.matchword
3104 << ", inTexted=" << cur.inTexted());
3105 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
3107 if ((len > 0) && (res < len)) {
3111 Paragraph const & par = cur.paragraph();
3112 bool ws_left = (cur.pos() > 0)
3113 ? par.isWordSeparator(cur.pos() - 1)
3119 ws_right = (cur.pos() + len < par.size())
3120 ? par.isWordSeparator(cur.pos() + len)
3124 "cur.pos()=" << cur.pos() << ", res=" << res
3125 << ", separ: " << ws_left << ", " << ws_right
3128 if (ws_left && ws_right) {
3129 // Check for word separators inside the found 'word'
3130 for (int i = 0; i < len; i++) {
3131 if (par.isWordSeparator(cur.pos() + i)) {
3143 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
3146 t = lyx::to_utf8(s);
3147 // Remove \n at begin
3148 while (!t.empty() && t[0] == '\n')
3151 while (!t.empty() && t[t.size() - 1] == '\n')
3152 t = t.substr(0, t.size() - 1);
3154 // Handle all other '\n'
3155 while ((pos = t.find("\n")) != string::npos) {
3156 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3158 if (isAlnumASCII(t[pos+1])) {
3159 t.replace(pos-2, 3, " ");
3162 t.replace(pos-2, 3, "");
3165 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3166 // '\n' adjacent to non-alpha-numerics, discard
3167 t.replace(pos, 1, "");
3170 // Replace all other \n with spaces
3171 t.replace(pos, 1, " ");
3174 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3175 // Kornel: Added textsl, textsf, textit, texttt and noun
3176 // + allow to seach for colored text too
3177 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3178 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3179 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3180 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3181 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3183 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3184 // FIXME - check what preceeds the brace
3186 if (opt.ignoreformat)
3187 while (regex_replace(t, t, "\\{", "_x_<")
3188 || regex_replace(t, t, "\\}", "_x_>"))
3189 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3191 while (regex_replace(t, t, "\\\\\\{", "_x_<")
3192 || regex_replace(t, t, "\\\\\\}", "_x_>"))
3193 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3200 docstring stringifyFromCursor(DocIterator const & cur, int len)
3202 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3203 if (cur.inTexted()) {
3204 Paragraph const & par = cur.paragraph();
3205 // TODO what about searching beyond/across paragraph breaks ?
3206 // TODO Try adding a AS_STR_INSERTS as last arg
3207 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3208 int(par.size()) : cur.pos() + len;
3209 // OutputParams runparams(&cur.buffer()->params().encoding());
3210 OutputParams runparams(encodings.fromLyXName("utf8"));
3211 runparams.nice = true;
3212 runparams.flavor = Flavor::XeTeX;
3213 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3214 // No side effect of file copying and image conversion
3215 runparams.dryrun = true;
3216 runparams.for_search = true;
3217 LYXERR(Debug::FIND, "Stringifying with cur: "
3218 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3219 return par.asString(cur.pos(), end,
3220 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3222 } else if (cur.inMathed()) {
3223 CursorSlice cs = cur.top();
3224 MathData md = cs.cell();
3225 MathData::const_iterator it_end =
3226 (( len == -1 || cs.pos() + len > int(md.size()))
3228 : md.begin() + cs.pos() + len );
3230 for (MathData::const_iterator it = md.begin() + cs.pos();
3233 docstring s = asString(md2);
3234 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3237 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3242 /** Computes the LaTeX export of buf starting from cur and ending len positions
3243 * after cur, if len is positive, or at the paragraph or innermost inset end
3246 docstring latexifyFromCursor(DocIterator const & cur, int len)
3248 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3249 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3250 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3251 Buffer const & buf = *cur.buffer();
3253 odocstringstream ods;
3255 //OutputParams runparams(&buf.params().encoding());
3256 OutputParams runparams(encodings.fromLyXName("utf8"));
3257 runparams.nice = false;
3258 runparams.flavor = Flavor::XeTeX;
3259 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3260 // No side effect of file copying and image conversion
3261 runparams.dryrun = true;
3262 runparams.for_search = true;
3264 if (cur.inTexted()) {
3265 // @TODO what about searching beyond/across paragraph breaks ?
3266 pos_type endpos = cur.paragraph().size();
3267 if (len != -1 && endpos > cur.pos() + len)
3268 endpos = cur.pos() + len;
3269 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3270 string(), cur.pos(), endpos);
3271 string s = lyx::to_utf8(ods.str());
3272 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3273 return(lyx::from_utf8(s));
3274 } else if (cur.inMathed()) {
3275 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3276 for (int s = cur.depth() - 1; s >= 0; --s) {
3277 CursorSlice const & cs = cur[s];
3278 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3280 cs.asInsetMath()->asHullInset()->header_write(ws);
3285 CursorSlice const & cs = cur.top();
3286 MathData md = cs.cell();
3287 MathData::const_iterator it_end =
3288 ((len == -1 || cs.pos() + len > int(md.size()))
3290 : md.begin() + cs.pos() + len);
3292 for (MathData::const_iterator it = md.begin() + cs.pos();
3296 ods << asString(md2);
3297 // Retrieve the math environment type, and add '$' or '$]'
3298 // or others (\end{equation}) accordingly
3299 for (int s = cur.depth() - 1; s >= 0; --s) {
3300 CursorSlice const & cs2 = cur[s];
3301 InsetMath * inset = cs2.asInsetMath();
3302 if (inset && inset->asHullInset()) {
3304 inset->asHullInset()->footer_write(ws);
3308 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3310 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3316 /** Finalize an advanced find operation, advancing the cursor to the innermost
3317 ** position that matches, plus computing the length of the matching text to
3320 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
3322 // Search the foremost position that matches (avoids find of entire math
3323 // inset when match at start of it)
3325 DocIterator old_cur(cur.buffer());
3327 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
3331 } while (cur && cur.depth() > d && match(cur).match_len > 0);
3333 int max_match = match(cur).match_len; /* match valid only if not searching whole words */
3334 if (max_match <= 0) return 0;
3335 LYXERR(Debug::FIND, "Ok");
3337 // Compute the match length
3339 if (cur.pos() + len > cur.lastpos())
3341 if (match.opt.matchword) {
3342 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3343 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3345 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3347 // Length of matched text (different from len param)
3348 int old_match = match(cur, len).match_len;
3352 // Greedy behaviour while matching regexps
3353 while ((new_match = match(cur, len + 1).match_len) > old_match) {
3355 old_match = new_match;
3356 LYXERR(Debug::FIND, "verifying match with len = " << len);
3363 int maxl = cur.lastpos() - cur.pos();
3364 // Greedy behaviour while matching regexps
3365 while (maxl > minl) {
3366 int actual_match = match(cur, len).match_len;
3367 if (actual_match >= max_match) {
3368 // actual_match > max_match _can_ happen,
3369 // if the search area splits
3370 // some following word so that the regex
3371 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3373 // This means, the len value is too big
3375 len = (int)((maxl + minl)/2);
3378 // (actual_match < max_match)
3380 len = (int)((maxl + minl)/2);
3384 // Search for real start of matched characters
3389 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3390 if (cur.depth() < old_cur.depth()) {
3392 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3395 if (cur.pos() != old_cur.pos()) {
3396 // OK, forwarded 1 pos in actual inset
3397 actual_match = match(cur, len-1).match_len;
3398 if (actual_match == max_match) {
3399 // Ha, got it! The shorter selection has the same match length
3404 // OK, the shorter selection matches less chars, revert to previous value
3410 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3411 actual_match = match(cur, len).match_len;
3412 if (actual_match == max_match)
3422 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
3426 while (!theApp()->longOperationCancelled() && cur) {
3427 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3428 MatchResult mres = match(cur, -1, false);
3429 int match_len = mres.match_len;
3430 LYXERR(Debug::FIND, "match_len: " << match_len);
3431 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3432 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3435 if (match_len > 0) {
3436 // Try to find the begin of searched string
3437 int increment = mres.pos/2;
3438 while (mres.pos > 5 && (increment > 5)) {
3439 DocIterator old_cur = cur;
3440 for (int i = 0; i < increment && cur; cur.forwardPos(), i++) {
3442 if (! cur || (cur.pit() > old_cur.pit())) {
3443 // Are we outside of the paragraph?
3444 // This can happen if moving past some UTF8-encoded chars
3449 MatchResult mres2 = match(cur, -1, false);
3450 if ((mres2.match2end < mres.match2end) ||
3451 (mres2.match_len < mres.match_len)) {
3458 if (increment > mres.pos/2)
3459 increment = mres.pos/2;
3463 int match_len_zero_count = 0;
3464 for (int i = 0; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
3466 int remaining_len = match(cur, -1, false).match_len;
3467 if (remaining_len <= 0) {
3468 // Apparently the searched string is not in the remaining part
3475 LYXERR(Debug::FIND, "Advancing cur: " << cur);
3476 int match_len3 = match(cur, 1).match_len;
3479 int match_len2 = match(cur).match_len;
3480 LYXERR(Debug::FIND, "match_len2: " << match_len2);
3481 if (match_len2 > 0) {
3482 // Sometimes in finalize we understand it wasn't a match
3483 // and we need to continue the outest loop
3484 int len = findAdvFinalize(cur, match);
3489 if (match_len2 >= 0) {
3490 if (match_len2 == 0)
3491 match_len_zero_count++;
3493 match_len_zero_count = 0;
3496 if (++match_len_zero_count > 3) {
3497 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
3505 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
3506 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
3509 // This should exit nested insets, if any, or otherwise undefine the currsor.
3510 cur.pos() = cur.lastpos();
3511 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3519 /// Find the most backward consecutive match within same paragraph while searching backwards.
3520 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3522 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3523 DocIterator tmp_cur = cur;
3524 int len = findAdvFinalize(tmp_cur, match);
3525 Inset & inset = cur.inset();
3526 for (; cur != cur_begin; cur.backwardPos()) {
3527 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3528 DocIterator new_cur = cur;
3529 new_cur.backwardPos();
3530 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3532 int new_len = findAdvFinalize(new_cur, match);
3537 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3543 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3547 // Backup of original position
3548 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3549 if (cur == cur_begin)
3552 DocIterator cur_orig(cur);
3553 bool pit_changed = false;
3556 bool found_match = (match(cur, -1, false).match_len > 0);
3560 cur.pos() = cur.lastpos();
3562 cur.pos() = cur_orig.pos();
3563 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3564 DocIterator cur_prev_iter;
3566 found_match = (match(cur).match_len > 0);
3567 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3568 << found_match << ", cur: " << cur);
3570 return findMostBackwards(cur, match);
3572 // Stop if begin of document reached
3573 if (cur == cur_begin)
3575 cur_prev_iter = cur;
3579 if (cur == cur_begin)
3586 } while (!theApp()->longOperationCancelled());
3594 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3595 DocIterator const & cur, int len)
3597 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3599 if (!opt.ignoreformat)
3600 return latexifyFromCursor(cur, len);
3602 return stringifyFromCursor(cur, len);
3606 FindAndReplaceOptions::FindAndReplaceOptions(
3607 docstring const & _find_buf_name, bool _casesensitive,
3608 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3609 docstring const & _repl_buf_name, bool _keep_case,
3610 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3611 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3612 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3613 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3621 /** Check if 'len' letters following cursor are all non-lowercase */
3622 static bool allNonLowercase(Cursor const & cur, int len)
3624 pos_type beg_pos = cur.selectionBegin().pos();
3625 pos_type end_pos = cur.selectionBegin().pos() + len;
3626 if (len > cur.lastpos() + 1 - beg_pos) {
3627 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3628 len = cur.lastpos() + 1 - beg_pos;
3629 end_pos = beg_pos + len;
3631 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3632 if (isLowerCase(cur.paragraph().getChar(pos)))
3638 /** Check if first letter is upper case and second one is lower case */
3639 static bool firstUppercase(Cursor const & cur)
3642 pos_type pos = cur.selectionBegin().pos();
3643 if (pos >= cur.lastpos() - 1) {
3644 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3647 ch1 = cur.paragraph().getChar(pos);
3648 ch2 = cur.paragraph().getChar(pos + 1);
3649 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3650 LYXERR(Debug::FIND, "firstUppercase(): "
3651 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3652 << ch2 << "(" << char(ch2) << ")"
3653 << ", result=" << result << ", cur=" << cur);
3658 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3660 ** \fixme What to do with possible further paragraphs in replace buffer ?
3662 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3664 ParagraphList::iterator pit = buffer.paragraphs().begin();
3665 LASSERT(!pit->empty(), /**/);
3666 pos_type right = pos_type(1);
3667 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3668 right = pit->size();
3669 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3675 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3677 Cursor & cur = bv->cursor();
3678 if (opt.repl_buf_name.empty()
3679 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3680 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3683 DocIterator sel_beg = cur.selectionBegin();
3684 DocIterator sel_end = cur.selectionEnd();
3685 if (&sel_beg.inset() != &sel_end.inset()
3686 || sel_beg.pit() != sel_end.pit()
3687 || sel_beg.idx() != sel_end.idx())
3689 int sel_len = sel_end.pos() - sel_beg.pos();
3690 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3691 << ", sel_len: " << sel_len << endl);
3694 LASSERT(sel_len > 0, return 0);
3696 if (!matchAdv(sel_beg, sel_len).match_len)
3699 // Build a copy of the replace buffer, adapted to the KeepCase option
3700 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
3702 repl_buffer_orig.write(oss);
3703 string lyx = oss.str();
3704 Buffer repl_buffer("", false);
3705 repl_buffer.setUnnamed(true);
3706 LASSERT(repl_buffer.readString(lyx), return 0);
3707 if (opt.keep_case && sel_len >= 2) {
3708 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
3709 if (cur.inTexted()) {
3710 if (firstUppercase(cur))
3711 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
3712 else if (allNonLowercase(cur, sel_len))
3713 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
3716 cap::cutSelection(cur, false);
3717 if (cur.inTexted()) {
3718 repl_buffer.changeLanguage(
3719 repl_buffer.language(),
3720 cur.getFont().language());
3721 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
3722 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
3723 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
3724 repl_buffer.params().documentClassPtr(),
3725 bv->buffer().errorList("Paste"));
3726 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
3727 sel_len = repl_buffer.paragraphs().begin()->size();
3728 } else if (cur.inMathed()) {
3729 odocstringstream ods;
3731 // OutputParams runparams(&repl_buffer.params().encoding());
3732 OutputParams runparams(encodings.fromLyXName("utf8"));
3733 runparams.nice = false;
3734 runparams.flavor = Flavor::XeTeX;
3735 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3736 runparams.dryrun = true;
3737 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
3738 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
3739 docstring repl_latex = ods.str();
3740 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
3742 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
3743 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
3744 repl_latex = from_utf8(s);
3745 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
3746 MathData ar(cur.buffer());
3747 asArray(repl_latex, ar, Parse::NORMAL);
3749 sel_len = ar.size();
3750 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3752 if (cur.pos() >= sel_len)
3753 cur.pos() -= sel_len;
3756 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3757 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
3758 bv->processUpdateFlags(Update::Force);
3763 /// Perform a FindAdv operation.
3764 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
3769 // e.g., when invoking word-findadv from mini-buffer wither with
3770 // wrong options syntax or before ever opening advanced F&R pane
3771 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3775 MatchStringAdv matchAdv(bv->buffer(), opt);
3776 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
3778 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
3779 num_replaced += findAdvReplace(bv, opt, matchAdv);
3782 match_len = findForwardAdv(cur, matchAdv);
3784 match_len = findBackwardsAdv(cur, matchAdv);
3786 // This may only be raised by lyx::regex()
3787 bv->message(_("Invalid regular expression!"));
3791 if (match_len == 0) {
3792 if (num_replaced > 0) {
3793 switch (num_replaced)
3796 bv->message(_("One match has been replaced."));
3799 bv->message(_("Two matches have been replaced."));
3802 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
3808 bv->message(_("Match not found."));
3813 if (num_replaced > 0)
3814 bv->message(_("Match has been replaced."));
3816 bv->message(_("Match found."));
3818 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
3819 bv->putSelectionAt(cur, match_len, !opt.forward);
3825 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
3827 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
3828 << opt.casesensitive << ' '
3829 << opt.matchword << ' '
3830 << opt.forward << ' '
3831 << opt.expandmacros << ' '
3832 << opt.ignoreformat << ' '
3833 << opt.replace_all << ' '
3834 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
3835 << opt.keep_case << ' '
3836 << int(opt.scope) << ' '
3839 LYXERR(Debug::FIND, "built: " << os.str());
3845 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
3847 LYXERR(Debug::FIND, "parsing");
3851 while (line != "EOSS") {
3855 if (is.eof()) // Tolerate malformed request
3859 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
3860 opt.find_buf_name = from_utf8(s);
3861 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
3862 is.get(); // Waste space before replace string
3865 while (line != "EOSS") {
3869 if (is.eof()) // Tolerate malformed request
3873 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
3874 opt.repl_buf_name = from_utf8(s);
3875 is >> opt.keep_case;
3878 opt.scope = FindAndReplaceOptions::SearchScope(i);
3880 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
3882 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
3883 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
3884 << opt.scope << ' ' << opt.restr);