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"
55 //#define ResultsDebug
56 #define USE_QT_FOR_SEARCH
57 #if defined(USE_QT_FOR_SEARCH)
58 #include <QtCore> // sets QT_VERSION
59 #if (QT_VERSION >= 0x050000)
60 #include <QRegularExpression>
70 using namespace lyx::support;
74 typedef map<string, string> AccentsMap;
75 static AccentsMap accents = map<string, string>();
77 // Helper class for deciding what should be ignored
81 IgnoreFormats() = default;
83 bool getFamily() const { return ignoreFamily_; }
85 bool getSeries() const { return ignoreSeries_; }
87 bool getShape() const { return ignoreShape_; }
89 bool getUnderline() const { return ignoreUnderline_; }
91 bool getMarkUp() const { return ignoreMarkUp_; }
93 bool getStrikeOut() const { return ignoreStrikeOut_; }
95 bool getSectioning() const { return ignoreSectioning_; }
97 bool getFrontMatter() const { return ignoreFrontMatter_; }
99 bool getColor() const { return ignoreColor_; }
101 bool getLanguage() const { return ignoreLanguage_; }
103 void setIgnoreFormat(string const & type, bool value);
107 bool ignoreFamily_ = false;
109 bool ignoreSeries_ = false;
111 bool ignoreShape_ = false;
113 bool ignoreUnderline_ = false;
115 bool ignoreMarkUp_ = false;
117 bool ignoreStrikeOut_ = false;
119 bool ignoreSectioning_ = false;
121 bool ignoreFrontMatter_ = false;
123 bool ignoreColor_ = false;
125 bool ignoreLanguage_ = false;
129 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
131 if (type == "color") {
132 ignoreColor_ = value;
134 else if (type == "language") {
135 ignoreLanguage_ = value;
137 else if (type == "sectioning") {
138 ignoreSectioning_ = value;
139 ignoreFrontMatter_ = value;
141 else if (type == "font") {
142 ignoreSeries_ = value;
143 ignoreShape_ = value;
144 ignoreFamily_ = value;
146 else if (type == "series") {
147 ignoreSeries_ = value;
149 else if (type == "shape") {
150 ignoreShape_ = value;
152 else if (type == "family") {
153 ignoreFamily_ = value;
155 else if (type == "markup") {
156 ignoreMarkUp_ = value;
158 else if (type == "underline") {
159 ignoreUnderline_ = value;
161 else if (type == "strike") {
162 ignoreStrikeOut_ = value;
166 // The global variable that can be changed from outside
167 IgnoreFormats ignoreFormats;
170 void setIgnoreFormat(string const & type, bool value)
172 ignoreFormats.setIgnoreFormat(type, value);
178 bool parse_bool(docstring & howto)
183 howto = split(howto, var, ' ');
191 MatchString(docstring const & s, bool cs, bool mw)
192 : str(s), case_sens(cs), whole_words(mw)
195 // returns true if the specified string is at the specified position
196 // del specifies whether deleted strings in ct mode will be considered
197 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
199 return par.find(str, case_sens, whole_words, pos, del);
207 // match whole words only
212 int findForward(DocIterator & cur, MatchString const & match,
213 bool find_del = true)
215 for (; cur; cur.forwardChar())
216 if (cur.inTexted()) {
217 int len = match(cur.paragraph(), cur.pos(), find_del);
225 int findBackwards(DocIterator & cur, MatchString const & match,
226 bool find_del = true)
230 if (cur.inTexted()) {
231 int len = match(cur.paragraph(), cur.pos(), find_del);
240 bool searchAllowed(docstring const & str)
243 frontend::Alert::error(_("Search error"), _("Search string is empty"));
250 bool findOne(BufferView * bv, docstring const & searchstr,
251 bool case_sens, bool whole, bool forward,
252 bool find_del = true, bool check_wrap = false)
254 if (!searchAllowed(searchstr))
257 DocIterator cur = forward
258 ? bv->cursor().selectionEnd()
259 : bv->cursor().selectionBegin();
261 MatchString const match(searchstr, case_sens, whole);
263 int match_len = forward
264 ? findForward(cur, match, find_del)
265 : findBackwards(cur, match, find_del);
268 bv->putSelectionAt(cur, match_len, !forward);
269 else if (check_wrap) {
270 DocIterator cur_orig(bv->cursor());
273 q = _("End of file reached while searching forward.\n"
274 "Continue searching from the beginning?");
276 q = _("Beginning of file reached while searching backward.\n"
277 "Continue searching from the end?");
278 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
279 q, 0, 1, _("&Yes"), _("&No"));
280 if (wrap_answer == 0) {
282 bv->cursor().clear();
283 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
285 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
286 bv->cursor().backwardPos();
288 bv->clearSelection();
289 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
292 bv->cursor().setCursor(cur_orig);
296 return match_len > 0;
300 int replaceAll(BufferView * bv,
301 docstring const & searchstr, docstring const & replacestr,
302 bool case_sens, bool whole)
304 Buffer & buf = bv->buffer();
306 if (!searchAllowed(searchstr) || buf.isReadonly())
309 DocIterator cur_orig(bv->cursor());
311 MatchString const match(searchstr, case_sens, whole);
314 int const rsize = replacestr.size();
315 int const ssize = searchstr.size();
318 cur.setCursor(doc_iterator_begin(&buf));
319 int match_len = findForward(cur, match, false);
320 while (match_len > 0) {
321 // Backup current cursor position and font.
322 pos_type const pos = cur.pos();
323 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
325 int striked = ssize -
326 cur.paragraph().eraseChars(pos, pos + match_len,
327 buf.params().track_changes);
328 cur.paragraph().insert(pos, replacestr, font,
329 Change(buf.params().track_changes
331 : Change::UNCHANGED));
332 for (int i = 0; i < rsize + striked; ++i)
335 match_len = findForward(cur, match, false);
338 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
340 cur_orig.fixIfBroken();
341 bv->setCursor(cur_orig);
347 // the idea here is that we are going to replace the string that
348 // is selected IF it is the search string.
349 // if there is a selection, but it is not the search string, then
350 // we basically ignore it. (FIXME We ought to replace only within
352 // if there is no selection, then:
353 // (i) if some search string has been provided, then we find it.
354 // (think of how the dialog works when you hit "replace" the
356 // (ii) if no search string has been provided, then we treat the
357 // word the cursor is in as the search string. (why? i have no
358 // idea.) but this only works in text?
360 // returns the number of replacements made (one, if any) and
361 // whether anything at all was done.
362 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
363 docstring const & replacestr, bool case_sens,
364 bool whole, bool forward, bool findnext)
366 Cursor & cur = bv->cursor();
367 if (!cur.selection()) {
368 // no selection, non-empty search string: find it
369 if (!searchstr.empty()) {
370 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
371 return make_pair(found, 0);
373 // empty search string
376 return make_pair(false, 0);
377 // select current word and treat it as the search string.
378 // This causes a minor bug as undo will restore this selection,
379 // which the user did not create (#8986).
380 cur.innerText()->selectWord(cur, WHOLE_WORD);
381 searchstr = cur.selectionAsString(false, true);
384 // if we still don't have a search string, report the error
386 if (!searchAllowed(searchstr))
387 return make_pair(false, 0);
389 bool have_selection = cur.selection();
390 docstring const selected = cur.selectionAsString(false, true);
393 ? searchstr == selected
394 : compare_no_case(searchstr, selected) == 0;
396 // no selection or current selection is not search word:
397 // just find the search word
398 if (!have_selection || !match) {
399 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
400 return make_pair(found, 0);
403 // we're now actually ready to replace. if the buffer is
404 // read-only, we can't, though.
405 if (bv->buffer().isReadonly())
406 return make_pair(false, 0);
408 cap::replaceSelectionWithString(cur, replacestr);
410 cur.pos() += replacestr.length();
411 LASSERT(cur.pos() <= cur.lastpos(),
412 cur.pos() = cur.lastpos());
415 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
417 return make_pair(true, 1);
423 docstring const find2string(docstring const & search,
424 bool casesensitive, bool matchword, bool forward)
428 << int(casesensitive) << ' '
429 << int(matchword) << ' '
435 docstring const replace2string(docstring const & replace,
436 docstring const & search,
437 bool casesensitive, bool matchword,
438 bool all, bool forward, bool findnext)
441 ss << replace << '\n'
443 << int(casesensitive) << ' '
444 << int(matchword) << ' '
446 << int(forward) << ' '
452 bool lyxfind(BufferView * bv, FuncRequest const & ev)
454 if (!bv || ev.action() != LFUN_WORD_FIND)
457 //lyxerr << "find called, cmd: " << ev << endl;
459 // data is of the form
461 // <casesensitive> <matchword> <forward>"
463 docstring howto = split(ev.argument(), search, '\n');
465 bool casesensitive = parse_bool(howto);
466 bool matchword = parse_bool(howto);
467 bool forward = parse_bool(howto);
469 return findOne(bv, search, casesensitive, matchword, forward, false, true);
473 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
475 if (!bv || ev.action() != LFUN_WORD_REPLACE)
478 // data is of the form
481 // <casesensitive> <matchword> <all> <forward> <findnext>"
484 docstring howto = split(ev.argument(), rplc, '\n');
485 howto = split(howto, search, '\n');
487 bool casesensitive = parse_bool(howto);
488 bool matchword = parse_bool(howto);
489 bool all = parse_bool(howto);
490 bool forward = parse_bool(howto);
491 bool findnext = howto.empty() ? true : parse_bool(howto);
495 int replace_count = 0;
497 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
498 update = replace_count > 0;
501 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
503 replace_count = rv.second;
506 Buffer const & buf = bv->buffer();
508 // emit message signal.
509 buf.message(_("String not found."));
511 if (replace_count == 0) {
512 buf.message(_("String found."));
513 } else if (replace_count == 1) {
514 buf.message(_("String has been replaced."));
516 docstring const str =
517 bformat(_("%1$d strings have been replaced."), replace_count);
525 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
527 for (; cur; cur.forwardPos())
528 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
532 DocIterator cur_orig(bv->cursor());
533 docstring q = _("End of file reached while searching forward.\n"
534 "Continue searching from the beginning?");
535 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
536 q, 0, 1, _("&Yes"), _("&No"));
537 if (wrap_answer == 0) {
538 bv->cursor().clear();
539 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
540 bv->clearSelection();
541 cur.setCursor(bv->cursor().selectionBegin());
542 if (findNextChange(bv, cur, false))
545 bv->cursor().setCursor(cur_orig);
552 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
554 for (cur.backwardPos(); cur; cur.backwardPos()) {
555 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
560 DocIterator cur_orig(bv->cursor());
561 docstring q = _("Beginning of file reached while searching backward.\n"
562 "Continue searching from the end?");
563 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
564 q, 0, 1, _("&Yes"), _("&No"));
565 if (wrap_answer == 0) {
566 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
567 bv->cursor().backwardPos();
568 bv->clearSelection();
569 cur.setCursor(bv->cursor().selectionBegin());
570 if (findPreviousChange(bv, cur, false))
573 bv->cursor().setCursor(cur_orig);
580 bool selectChange(Cursor & cur, bool forward)
582 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
584 Change ch = cur.paragraph().lookupChange(cur.pos());
586 CursorSlice tip1 = cur.top();
587 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
588 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
589 if (!ch2.isSimilarTo(ch))
592 CursorSlice tip2 = cur.top();
593 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
595 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
596 if (!ch2.isSimilarTo(ch)) {
597 // take a step forward to correctly set the selection
605 cur.bv().mouseSetCursor(cur, false);
607 cur.bv().mouseSetCursor(cur, true);
615 bool findChange(BufferView * bv, bool forward)
618 cur.setCursor(forward ? bv->cursor().selectionEnd()
619 : bv->cursor().selectionBegin());
620 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
621 return selectChange(cur, forward);
626 bool findNextChange(BufferView * bv)
628 return findChange(bv, true);
632 bool findPreviousChange(BufferView * bv)
634 return findChange(bv, false);
641 typedef vector<pair<string, string> > Escapes;
643 /// A map of symbols and their escaped equivalent needed within a regex.
644 /// @note Beware of order
646 Escapes const & get_regexp_escapes()
648 typedef std::pair<std::string, std::string> P;
650 static Escapes escape_map;
651 if (escape_map.empty()) {
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("[", "_x_["));
656 escape_map.push_back(P("]", "_x_]"));
657 escape_map.push_back(P("(", "_x_("));
658 escape_map.push_back(P(")", "_x_)"));
659 escape_map.push_back(P("+", "_x_+"));
660 escape_map.push_back(P("*", "_x_*"));
661 escape_map.push_back(P(".", "_x_."));
662 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
663 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
664 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
665 escape_map.push_back(P("_x_", "\\"));
671 /// A map of lyx escaped strings and their unescaped equivalent.
673 Escapes const & get_lyx_unescapes()
675 typedef std::pair<std::string, std::string> P;
677 static Escapes escape_map;
678 if (escape_map.empty()) {
679 escape_map.push_back(P("\\%", "%"));
680 escape_map.push_back(P("\\{", "{"));
681 escape_map.push_back(P("\\}", "}"));
682 escape_map.push_back(P("\\mathcircumflex ", "^"));
683 escape_map.push_back(P("\\mathcircumflex", "^"));
684 escape_map.push_back(P("\\backslash ", "\\"));
685 escape_map.push_back(P("\\backslash", "\\"));
686 escape_map.push_back(P("\\sim ", "~"));
687 escape_map.push_back(P("\\sim", "~"));
693 /// A map of escapes turning a regexp matching text to one matching latex.
695 Escapes const & get_regexp_latex_escapes()
697 typedef std::pair<std::string, std::string> P;
699 static Escapes escape_map;
700 if (escape_map.empty()) {
701 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
702 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
703 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
704 escape_map.push_back(P("\\[", "\\{\\[\\}"));
705 escape_map.push_back(P("\\]", "\\{\\]\\}"));
706 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
707 escape_map.push_back(P("%", "\\\\\\%"));
708 escape_map.push_back(P("#", "\\\\#"));
714 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
715 ** the found occurrence were escaped.
718 string apply_escapes(string s, Escapes const & escape_map)
720 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
721 Escapes::const_iterator it;
722 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
723 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
724 unsigned int pos = 0;
725 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
726 s.replace(pos, it->first.length(), it->second);
727 LYXERR(Debug::FIND, "After escape: " << s);
728 pos += it->second.length();
729 // LYXERR(Debug::FIND, "pos: " << pos);
732 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
738 string string2regex(string in)
740 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
741 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
746 while (fl_pos < temp.size()) {
747 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
748 if (fl_pos == string::npos)
751 temp2 += temp.substr(lastpos, fl_pos - lastpos);
757 if (lastpos < temp.size()) {
758 temp2 += temp.substr(lastpos, temp.size() - lastpos);
763 string correctRegex(string t, bool withformat)
765 /* Convert \backslash => \
766 * and \{, \}, \[, \] => {, }, [, ]
769 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
772 bool backslashed = false;
773 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
776 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
780 if (sub.str(4) == "backslash") {
783 // tranforms '\backslash \{' into '\{'
785 sregex_iterator it2 = it;
788 if ((sub2.str(3) == "{") || (sub2.str(3) == "}")) {
794 else if (sub.str(4) == "mathcircumflex")
796 else if (backslashed) {
798 if (withformat && (sub.str(3) == "{"))
799 replace = accents["braceleft"];
800 else if (withformat && (sub.str(3) == "}"))
801 replace = accents["braceright"];
803 // else part should not exist
808 replace = sub.str(3);
810 if (lastpos < (size_t) sub.position(2))
811 s += t.substr(lastpos, sub.position(2) - lastpos);
813 lastpos = sub.position(2) + sub.length(2);
817 else if (lastpos < t.length())
818 s += t.substr(lastpos, t.length() - lastpos);
822 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
823 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
824 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
825 string escape_for_regex(string s, bool withformat)
829 while (lastpos < s.size()) {
830 size_t regex_pos = s.find("\\regexp{", lastpos);
831 if (regex_pos == string::npos) {
832 regex_pos = s.size();
834 if (regex_pos > lastpos) {
835 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
837 if (lastpos == s.size())
840 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
841 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
842 lastpos = end_pos + 13;
848 /// Wrapper for lyx::regex_replace with simpler interface
849 bool regex_replace(string const & s, string & t, string const & searchstr,
850 string const & replacestr)
852 regex e(searchstr, regex_constants::ECMAScript);
854 ostream_iterator<char, char> it(oss);
855 regex_replace(it, s.begin(), s.end(), e, replacestr);
856 // tolerate t and s be references to the same variable
857 bool rv = (s != oss.str());
863 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
865 ** Verify that closed braces exactly match open braces. This avoids that, for example,
866 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
869 ** Number of open braces that must remain open at the end for the verification to succeed.
872 bool braces_match(QString const & beg,
875 bool braces_match(string const & beg,
881 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg.toStdString() << "'");
883 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg << "'");
885 int lastidx = beg.size();
886 for (int i=0; i < lastidx; ++i) {
887 // Skip escaped braces in the count
897 } else if (c == '{') {
899 } else if (c == '}') {
900 if (open_pars == 0) {
901 LYXERR(Debug::FIND, "Found unmatched closed brace");
907 if (open_pars != unmatched) {
908 LYXERR(Debug::FIND, "Found " << open_pars
909 << " instead of " << unmatched
910 << " unmatched open braces at the end of count");
913 LYXERR(Debug::FIND, "Braces match as expected");
932 vector <string> result = vector <string>();
933 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
936 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
938 int range = oldres.match_len;
939 if (range > 0) range--;
940 if (newres.match2end < oldres.match2end - oldres.match_len)
941 return MatchResult::newIsTooFar;
942 if (newres.match_len < oldres.match_len)
943 return MatchResult::newIsTooFar;
944 if ((newres.match_len == oldres.match_len) &&
945 (newres.match2end < oldres.match2end + range) &&
946 (newres.match2end > oldres.match2end - range)) {
947 return MatchResult::newIsBetter;
949 return MatchResult::newIsInvalid;
952 /** The class performing a match between a position in the document and the FindAdvOptions.
955 class MatchStringAdv {
957 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
959 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
960 ** constructor as opt.search, under the opt.* options settings.
963 ** If set, then match is searched only against beginning of text starting at cur.
964 ** If unset, then match is searched anywhere in text starting at cur.
967 ** The length of the matching text, or zero if no match was found.
969 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
978 /// first buffer on which search was started
979 lyx::Buffer * const p_first_buf;
981 FindAndReplaceOptions const & opt;
984 /// Auxiliary find method (does not account for opt.matchword)
985 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
986 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
988 /** Normalize a stringified or latexified LyX paragraph.
992 ** <li>if search is not casesensitive, then lowercase the string;
993 ** <li>remove any newline at begin or end of the string;
994 ** <li>replace any newline in the middle of the string with a simple space;
995 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
998 ** @todo Normalization should also expand macros, if the corresponding
999 ** search option was checked.
1001 string normalize(docstring const & s) const;
1002 // normalized string to search
1003 string par_as_string;
1004 // regular expression to use for searching
1005 // regexp2 is same as regexp, but prefixed with a ".*?"
1007 QRegularExpression regexp;
1008 QRegularExpression regexp2;
1013 // leading format material as string
1014 string lead_as_string;
1015 // par_as_string after removal of lead_as_string
1016 string par_as_string_nolead;
1017 // unmatched open braces in the search string/regexp
1019 // number of (.*?) subexpressions added at end of search regexp for closing
1020 // environments, math mode, styles, etc...
1021 int close_wildcards;
1023 // Are we searching with regular expressions ?
1025 static int valid_matches;
1026 static vector <string> matches;
1027 void FillResults(MatchResult &found_mr);
1030 int MatchStringAdv::valid_matches = 0;
1031 vector <string> MatchStringAdv::matches = vector <string>(10);
1033 void MatchStringAdv::FillResults(MatchResult &found_mr)
1035 if (found_mr.match_len > 0) {
1036 valid_matches = found_mr.result.size();
1037 for (size_t i = 0; i < found_mr.result.size(); i++)
1038 matches[i] = found_mr.result[i];
1044 static docstring buffer_to_latex(Buffer & buffer)
1046 //OutputParams runparams(&buffer.params().encoding());
1047 OutputParams runparams(encodings.fromLyXName("utf8"));
1048 odocstringstream ods;
1050 runparams.nice = true;
1051 runparams.flavor = Flavor::XeTeX;
1052 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1053 // No side effect of file copying and image conversion
1054 runparams.dryrun = true;
1055 runparams.for_search = true;
1056 pit_type const endpit = buffer.paragraphs().size();
1057 for (pit_type pit = 0; pit != endpit; ++pit) {
1058 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
1059 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
1065 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1068 if (!opt.ignoreformat) {
1069 str = buffer_to_latex(buffer);
1071 // OutputParams runparams(&buffer.params().encoding());
1072 OutputParams runparams(encodings.fromLyXName("utf8"));
1073 runparams.nice = true;
1074 runparams.flavor = Flavor::XeTeX;
1075 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1076 runparams.dryrun = true;
1077 runparams.for_search = true;
1078 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1079 Paragraph const & par = buffer.paragraphs().at(pit);
1080 LYXERR(Debug::FIND, "Adding to search string: '"
1081 << par.asString(pos_type(0), par.size(),
1082 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1085 str += par.asString(pos_type(0), par.size(),
1086 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1089 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1090 string t = to_utf8(str);
1091 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
1098 /// Return separation pos between the leading material and the rest
1099 static size_t identifyLeading(string const & s)
1102 // @TODO Support \item[text]
1103 // Kornel: Added textsl, textsf, textit, texttt and noun
1104 // + allow to search for colored text too
1105 while (regex_replace(t, t, "^\\\\(("
1106 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1107 "lyxaddress|lyxrightaddress|"
1108 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1109 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1110 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1111 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1112 || regex_replace(t, t, "^\\$", "")
1113 || regex_replace(t, t, "^\\\\\\[", "")
1114 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1115 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1117 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1122 * Given a latexified string, retrieve some handled features
1123 * The features of the regex will later be compared with the features
1124 * of the searched text. If the regex features are not a
1125 * subset of the analized, then, in not format ignoring search
1126 * we can early stop the search in the relevant inset.
1128 typedef map<string, bool> Features;
1130 static Features identifyFeatures(string const & s)
1132 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1133 static regex const valid("^("
1135 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1136 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1137 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1138 "(u|uu)line|(s|x)out|uwave|"
1139 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1140 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1145 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1148 if (sub.str(1).compare("regexp") == 0) {
1152 string token = sub.str(1);
1154 if (regex_match(token, sub2, valid)) {
1162 if (sub.str(1).compare("endregexp") == 0) {
1172 * defines values features of a key "\\[a-z]+{"
1177 /* Char type with content discarded
1178 * like \hspace{1cm} */
1180 /* Char, like \backslash */
1182 /* replace starting backslash with '#' */
1184 /* \part, \section*, ... */
1186 /* title, author etc */
1188 /* \foreignlanguage{ngerman}, ... */
1191 * to discard language in content */
1194 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1196 /* fonts, colors, markups, ... */
1198 /* footnotesize, ... large, ...
1199 * Ignore all of them */
1202 /* inputencoding, ...
1203 * Discard also content, because they do not help in search */
1206 * like remove, but also all arguments */
1208 /* item, listitem */
1210 /* tex, latex, ... like isChar */
1212 /* like \lettrine[lines=5]{}{} */
1214 // like isStandard, but always remove head
1216 /* End of arguments marker for lettrine,
1217 * so that they can be ignored */
1220 KeyInfo() = default;
1221 KeyInfo(KeyType type, int parcount, bool disable)
1223 parenthesiscount(parcount),
1224 disabled(disable) {}
1225 KeyType keytype = invalid;
1227 int _tokensize = -1;
1228 int _tokenstart = -1;
1229 int _dataStart = -1;
1231 int parenthesiscount = 1;
1232 bool disabled = false;
1233 bool used = false; /* by pattern */
1238 Border(int l=0, int u=0) : low(l), upper(u) {};
1243 #define MAXOPENED 30
1245 bool isPatternString_;
1247 explicit Intervall(bool isPattern, string const & p) :
1248 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1249 hasTitle(false), langcount(0)
1257 static vector<Border> borders;
1258 int depts[MAXOPENED];
1259 int closes[MAXOPENED];
1260 int actualdeptindex;
1261 int previousNotIgnored(int) const;
1262 int nextNotIgnored(int) const;
1263 void handleOpenP(int i);
1264 void handleCloseP(int i, bool closingAllowed);
1265 void resetOpenedP(int openPos);
1266 void addIntervall(int upper);
1267 void addIntervall(int low, int upper); /* if explicit */
1268 void removeAccents();
1269 void setForDefaultLang(KeyInfo const & defLang) const;
1270 int findclosing(int start, int end, char up, char down, int repeat);
1271 void handleParentheses(int lastpos, bool closingAllowed);
1273 int langcount; // Number of disabled language specs up to current position in actual interval
1274 int isOpeningPar(int pos) const;
1276 void output(ostringstream &os, int lastpos);
1277 // string show(int lastpos);
1280 vector<Border> Intervall::borders = vector<Border>(30);
1282 int Intervall::isOpeningPar(int pos) const
1284 if ((pos < 0) || (size_t(pos) >= par.size()))
1286 if (par[pos] != '{')
1288 if (size_t(pos) + 2 >= par.size())
1290 if (par[pos+2] != '}')
1292 if (par[pos+1] == '[' || par[pos+1] == ']')
1297 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1299 // Enable the use of first token again
1300 if (ignoreidx >= 0) {
1301 int value = defLang._tokenstart + defLang._tokensize;
1307 if (borders[borderidx].low < value)
1308 borders[borderidx].low = value;
1309 if (borders[borderidx].upper < value)
1310 borders[borderidx].upper = value;
1315 static void checkDepthIndex(int val)
1317 static int maxdepthidx = MAXOPENED-2;
1318 static int lastmaxdepth = 0;
1319 if (val > lastmaxdepth) {
1320 LYXERR(Debug::INFO, "Depth reached " << val);
1323 if (val > maxdepthidx) {
1325 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1330 // Not needed, because borders are now dynamically expanded
1331 static void checkIgnoreIdx(int val)
1333 static int lastmaxignore = -1;
1334 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1335 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1336 lastmaxignore = val;
1342 * Expand the region of ignored parts of the input latex string
1343 * The region is only relevant in output()
1345 void Intervall::addIntervall(int low, int upper)
1348 if (low == upper) return;
1349 for (idx = ignoreidx+1; idx > 0; --idx) {
1350 if (low > borders[idx-1].upper) {
1354 Border br(low, upper);
1355 if (idx > ignoreidx) {
1356 if (borders.size() <= size_t(idx)) {
1357 borders.push_back(br);
1363 // checkIgnoreIdx(ignoreidx);
1367 // Expand only if one of the new bound is inside the interwall
1368 // We know here that br.low > borders[idx-1].upper
1369 if (br.upper < borders[idx].low) {
1370 // We have to insert at this pos
1371 if (size_t(ignoreidx+1) >= borders.size()) {
1372 borders.push_back(borders[ignoreidx]);
1375 borders[ignoreidx+1] = borders[ignoreidx];
1377 for (int i = ignoreidx; i > idx; --i) {
1378 borders[i] = borders[i-1];
1382 // checkIgnoreIdx(ignoreidx);
1385 // Here we know, that we are overlapping
1386 if (br.low > borders[idx].low)
1387 br.low = borders[idx].low;
1388 // check what has to be concatenated
1390 for (int i = idx; i <= ignoreidx; i++) {
1391 if (br.upper >= borders[i].low) {
1393 if (br.upper < borders[i].upper)
1394 br.upper = borders[i].upper;
1400 // count should be >= 1 here
1403 for (int i = idx + count; i <= ignoreidx; i++) {
1404 borders[i-count+1] = borders[i];
1406 ignoreidx -= count - 1;
1412 static void buildaccent(string n, string param, string values)
1416 const char delim = '|';
1417 while (getline(s, name, delim)) {
1419 for (char c : param) {
1420 string key = name + "{" + c + "}";
1421 // get the corresponding utf8-value
1422 if ((values[start] & 0xc0) != 0xc0) {
1423 // should not happen, utf8 encoding starts at least with 11xxxxxx
1424 // but value for '\dot{i}' is 'i', which is ascii
1425 if ((values[start] & 0x80) == 0) {
1427 accents[key] = values.substr(start, 1);
1428 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1433 for (int j = 1; ;j++) {
1434 if (start + j >= values.size()) {
1435 accents[key] = values.substr(start, j);
1436 start = values.size() - 1;
1439 else if ((values[start+j] & 0xc0) != 0x80) {
1440 // This is the first byte of following utf8 char
1441 accents[key] = values.substr(start, j);
1443 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1452 static string getutf8(unsigned uchar)
1455 string ret = string();
1457 if (uchar <= 0x7f) {
1458 c[maxc-1] = uchar & 0x7f;
1461 unsigned char rest = 0x40;
1462 unsigned char first = 0x80;
1464 for (int i = start; i >=0; --i) {
1466 c[i] = first + uchar;
1469 c[i] = 0x80 | (uchar & 0x3f);
1476 for (int i = 0; i < maxc; i++) {
1477 if (c[i] == 0) continue;
1483 static void buildAccentsMap()
1485 accents["imath"] = "ı";
1487 accents["jmath"] = "ȷ";
1488 accents["cdot"] = "·";
1489 accents["textasciicircum"] = "^";
1490 accents["mathcircumflex"] = "^";
1491 accents["sim"] = "~";
1492 accents["guillemotright"] = "»";
1493 accents["guillemotleft"] = "«";
1494 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1495 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1496 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1497 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1498 accents["negmedspace"] = getutf8(0xf0005);
1499 accents["thickspace"] = getutf8(0xf0006);
1500 accents["negthickspace"] = getutf8(0xf0007);
1501 accents["lyx"] = getutf8(0xf0010); // Used logos
1502 accents["LyX"] = getutf8(0xf0010);
1503 accents["tex"] = getutf8(0xf0011);
1504 accents["TeX"] = getutf8(0xf0011);
1505 accents["latex"] = getutf8(0xf0012);
1506 accents["LaTeX"] = getutf8(0xf0012);
1507 accents["latexe"] = getutf8(0xf0013);
1508 accents["LaTeXe"] = getutf8(0xf0013);
1509 accents["lyxarrow"] = getutf8(0xf0020);
1510 accents["braceleft"] = getutf8(0xf0030);
1511 accents["braceright"] = getutf8(0xf0031);
1512 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1513 accents["backslash LyX"] = getutf8(0xf0010);
1514 accents["backslash tex"] = getutf8(0xf0011);
1515 accents["backslash TeX"] = getutf8(0xf0011);
1516 accents["backslash latex"] = getutf8(0xf0012);
1517 accents["backslash LaTeX"] = getutf8(0xf0012);
1518 accents["backslash latexe"] = getutf8(0xf0013);
1519 accents["backslash LaTeXe"] = getutf8(0xf0013);
1520 accents["backslash lyxarrow"] = getutf8(0xf0020);
1521 accents["ddot{\\imath}"] = "ï";
1522 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1523 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1524 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1525 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1526 accents["acute{\\imath}"] = "í";
1527 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1528 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1529 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1530 buildaccent("mathring|r", "aAuUwy",
1532 accents["check{\\imath}"] = "ǐ";
1533 accents["check{\\jmath}"] = "ǰ";
1534 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1535 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1536 accents["hat{\\imath}"] = "î";
1537 accents["hat{\\jmath}"] = "ĵ";
1538 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1539 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1540 accents["bar{\\imath}"] = "ī";
1541 buildaccent("bar|=", "aAeEiIoOuUyY",
1542 "āĀēĒīĪōŌūŪȳȲ"); // macron
1543 accents["tilde{\\imath}"] = "ĩ";
1544 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1545 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1546 accents["breve{\\imath}"] = "ĭ";
1547 buildaccent("breve|u", "aAeEgGiIoOuU",
1548 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1549 accents["grave{\\imath}"] = "ì";
1550 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1551 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1552 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1553 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1554 buildaccent("ogonek|k", "AaEeIiUuOo",
1555 "ĄąĘęĮįŲųǪǫ"); // ogonek
1556 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1557 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1558 buildaccent("subring|textsubring", "Aa",
1560 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1561 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1562 buildaccent("subtilde|textsubtilde", "EeIiUu",
1563 "ḚḛḬḭṴṵ"); // subtilde
1564 accents["dgrave{\\imath}"] = "ȉ";
1565 accents["textdoublegrave{\\i}"] = "ȉ";
1566 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1567 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1568 accents["rcap{\\imath}"] = "ȉ";
1569 accents["textroundcap{\\i}"] = "ȉ";
1570 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1571 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1572 buildaccent("slashed", "oO",
1577 * Created accents in math or regexp environment
1578 * are macros, but we need the utf8 equivalent
1580 void Intervall::removeAccents()
1582 if (accents.empty())
1584 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1585 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1586 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|(brace|guillemot)(left|right)|textasciicircum|mathcircumflex|sim)(?![a-zA-Z]))");
1588 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1590 string key = sub.str(1);
1591 if (accents.find(key) != accents.end()) {
1592 string val = accents[key];
1593 size_t pos = sub.position(size_t(0));
1594 for (size_t i = 0; i < val.size(); i++) {
1595 par[pos+i] = val[i];
1597 // Remove possibly following space too
1598 if (par[pos+sub.str(0).size()] == ' ')
1599 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1601 addIntervall(pos+val.size(), pos + sub.str(0).size());
1602 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1603 // remove traces of any remaining chars
1608 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1613 void Intervall::handleOpenP(int i)
1616 depts[actualdeptindex] = i+1;
1617 closes[actualdeptindex] = -1;
1618 checkDepthIndex(actualdeptindex);
1621 void Intervall::handleCloseP(int i, bool closingAllowed)
1623 if (actualdeptindex <= 0) {
1624 if (! closingAllowed)
1625 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1626 // if we are at the very end
1627 addIntervall(i, i+1);
1630 closes[actualdeptindex] = i+1;
1635 void Intervall::resetOpenedP(int openPos)
1637 // Used as initializer for foreignlanguage entry
1638 actualdeptindex = 1;
1639 depts[1] = openPos+1;
1643 int Intervall::previousNotIgnored(int start) const
1645 int idx = 0; /* int intervalls */
1646 for (idx = ignoreidx; idx >= 0; --idx) {
1647 if (start > borders[idx].upper)
1649 if (start >= borders[idx].low)
1650 start = borders[idx].low-1;
1655 int Intervall::nextNotIgnored(int start) const
1657 int idx = 0; /* int intervalls */
1658 for (idx = 0; idx <= ignoreidx; idx++) {
1659 if (start < borders[idx].low)
1661 if (start < borders[idx].upper)
1662 start = borders[idx].upper;
1667 typedef map<string, KeyInfo> KeysMap;
1668 typedef vector< KeyInfo> Entries;
1669 static KeysMap keys = map<string, KeyInfo>();
1675 Intervall interval_;
1676 void buildKeys(bool);
1677 void buildEntries(bool);
1678 void makeKey(const string &, KeyInfo, bool isPatternString);
1679 void processRegion(int start, int region_end); /* remove {} parts */
1680 void removeHead(KeyInfo const &, int count=0);
1683 LatexInfo(string const & par, bool isPatternString)
1684 : entidx_(-1), interval_(isPatternString, par)
1686 buildKeys(isPatternString);
1687 entries_ = vector<KeyInfo>();
1688 buildEntries(isPatternString);
1692 if (entries_.empty()) {
1695 if (entries_[0].keytype == KeyInfo::isTitle) {
1696 interval_.hasTitle = true;
1697 if (! entries_[0].disabled) {
1698 interval_.titleValue = entries_[0].head;
1701 interval_.titleValue = "";
1703 removeHead(entries_[0]);
1704 if (entries_.size() > 1)
1713 if (int(entries_.size()) > entidx_) {
1720 bool setNextKey(int idx) {
1721 if ((idx == entidx_) && (entidx_ >= 0)) {
1728 int find(int start, KeyInfo::KeyType keytype) const {
1732 while (tmpIdx < int(entries_.size())) {
1733 if (entries_[tmpIdx].keytype == keytype)
1739 int process(ostringstream & os, KeyInfo const & actual);
1740 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1741 // string show(int lastpos) { return interval.show(lastpos);};
1742 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1743 KeyInfo &getKeyInfo(int keyinfo) {
1744 static KeyInfo invalidInfo = KeyInfo();
1745 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1748 return entries_[keyinfo];
1750 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1751 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1755 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1759 for (int i = start; i < end; i += 1 + skip) {
1763 if (c == '\\') skip = 1;
1767 else if (c == down) {
1770 if ((repeat <= 0) || (par[i+1] != up))
1788 vector<MathEntry> entries_;
1793 void insert(string const & wait, size_t start, size_t end) {
1794 MathEntry m = MathEntry();
1796 m.mathStart = start;
1798 m.mathSize = end - start;
1799 entries_.push_back(m);
1801 bool empty() const { return entries_.empty(); };
1802 size_t getEndPos() const {
1803 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1806 return entries_[actualIdx_].mathEnd;
1808 size_t getStartPos() const {
1809 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1810 return 100000; /* definitely enough? */
1812 return entries_[actualIdx_].mathStart;
1814 size_t getFirstPos() {
1816 return getStartPos();
1818 size_t getSize() const {
1819 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1822 return entries_[actualIdx_].mathSize;
1824 void incrEntry() { actualIdx_++; };
1827 void LatexInfo::buildEntries(bool isPatternString)
1829 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1830 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1831 static bool disableLanguageOverride = false;
1832 smatch sub, submath;
1833 bool evaluatingRegexp = false;
1835 bool evaluatingMath = false;
1836 bool evaluatingCode = false;
1838 bool evaluatingOptional = false;
1839 size_t optionalEnd = 0;
1842 bool math_end_waiting = false;
1843 size_t math_pos = 10000;
1845 static vector<string> usedText = vector<string>();
1847 interval_.removeAccents();
1849 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1851 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1852 // prefixed by odd count of '\\'
1855 if (math_end_waiting) {
1856 size_t pos = submath.position(size_t(2));
1857 if ((math_end == "$") &&
1858 (submath.str(2) == "$")) {
1859 mi.insert("$", math_pos, pos + 1);
1860 math_end_waiting = false;
1862 else if ((math_end == "\\]") &&
1863 (submath.str(2) == "\\]")) {
1864 mi.insert("\\]", math_pos, pos + 2);
1865 math_end_waiting = false;
1867 else if ((submath.str(3).compare("end") == 0) &&
1868 (submath.str(4).compare(math_end) == 0)) {
1869 mi.insert(math_end, math_pos, pos + submath.str(2).length());
1870 math_end_waiting = false;
1876 if (submath.str(3).compare("begin") == 0) {
1877 math_end_waiting = true;
1878 math_end = submath.str(4);
1879 math_pos = submath.position(size_t(2));
1881 else if (submath.str(2).compare("\\[") == 0) {
1882 math_end_waiting = true;
1884 math_pos = submath.position(size_t(2));
1886 else if (submath.str(2) == "$") {
1887 size_t pos = submath.position(size_t(2));
1888 math_end_waiting = true;
1894 // Ignore language if there is math somewhere in pattern-string
1895 if (isPatternString) {
1896 for (auto s: usedText) {
1897 // Remove entries created in previous search runs
1900 usedText = vector<string>();
1903 keys["foreignlanguage"].disabled = true;
1904 disableLanguageOverride = true;
1907 disableLanguageOverride = false;
1910 if (disableLanguageOverride) {
1911 keys["foreignlanguage"].disabled = true;
1914 math_pos = mi.getFirstPos();
1915 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1917 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1918 // prefixed by odd count of '\\'
1921 string key = sub.str(5);
1923 if (sub.str(2)[0] == '\\')
1924 key = sub.str(2)[1];
1929 if (keys.find(key) != keys.end()) {
1930 if (keys[key].keytype == KeyInfo::headRemove) {
1931 KeyInfo found1 = keys[key];
1932 found1.disabled = true;
1933 found1.head = "\\" + key + "{";
1934 found1._tokenstart = sub.position(size_t(2));
1935 found1._tokensize = found1.head.length();
1936 found1._dataStart = found1._tokenstart + found1.head.length();
1937 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1938 found1._dataEnd = endpos;
1943 if (evaluatingRegexp) {
1944 if (sub.str(3).compare("endregexp") == 0) {
1945 evaluatingRegexp = false;
1946 // found._tokenstart already set
1947 found._dataEnd = sub.position(size_t(2)) + 13;
1948 found._dataStart = found._dataEnd;
1949 found._tokensize = found._dataEnd - found._tokenstart;
1950 found.parenthesiscount = 0;
1951 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1958 if (evaluatingMath) {
1959 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1961 evaluatingMath = false;
1963 math_pos = mi.getStartPos();
1965 if (keys.find(key) == keys.end()) {
1966 found = KeyInfo(KeyInfo::isStandard, 0, true);
1967 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1968 found = KeyInfo(KeyInfo::isText, 0, false);
1969 if (isPatternString) {
1970 found.keytype = KeyInfo::isChar;
1971 found.disabled = false;
1975 usedText.push_back(key);
1979 if (key.compare("regexp") == 0) {
1980 evaluatingRegexp = true;
1981 found._tokenstart = sub.position(size_t(2));
1982 found._tokensize = 0;
1986 // Handle the other params of key
1987 if (found.keytype == KeyInfo::isIgnored)
1989 else if (found.keytype == KeyInfo::isMath) {
1990 if (size_t(sub.position(size_t(2))) == math_pos) {
1992 found._tokenstart = sub.position(size_t(2));
1993 found._tokensize = mi.getSize();
1994 found._dataEnd = found._tokenstart + found._tokensize;
1995 found._dataStart = found._dataEnd;
1996 found.parenthesiscount = 0;
1997 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1998 evaluatingMath = true;
2001 // begin|end of unknown env, discard
2002 // First handle tables
2003 // longtable|tabular
2004 bool discardComment;
2006 found.keytype = KeyInfo::doRemove;
2007 if ((sub.str(7).compare("longtable") == 0) ||
2008 (sub.str(7).compare("tabular") == 0)) {
2009 discardComment = true; /* '%' */
2012 discardComment = false;
2013 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2015 string token = sub.str(7);
2016 if (regex_match(token, sub2, removeArgs)) {
2017 found.keytype = KeyInfo::removeWithArg;
2020 // discard spaces before pos(2)
2021 int pos = sub.position(size_t(2));
2023 for (count = 0; pos - count > 0; count++) {
2024 char c = interval_.par[pos-count-1];
2025 if (discardComment) {
2026 if ((c != ' ') && (c != '%'))
2032 found._tokenstart = pos - count;
2033 if (sub.str(3).compare(0, 5, "begin") == 0) {
2034 size_t pos1 = pos + sub.str(2).length();
2035 if (sub.str(7).compare("cjk") == 0) {
2036 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2037 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2039 found.keytype = KeyInfo::isMain;
2040 found._dataStart = pos1;
2041 found._dataEnd = interval_.par.length();
2042 found.disabled = keys["foreignlanguage"].disabled;
2043 found.used = keys["foreignlanguage"].used;
2044 found._tokensize = pos1 - found._tokenstart;
2045 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2048 // Swallow possible optional params
2049 while (interval_.par[pos1] == '[') {
2050 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2052 // Swallow also the eventual parameter
2053 if (interval_.par[pos1] == '{') {
2054 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2057 found._dataEnd = pos1;
2059 found._dataStart = found._dataEnd;
2060 found._tokensize = count + found._dataEnd - pos;
2061 found.parenthesiscount = 0;
2062 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2063 found.disabled = true;
2067 // Handle "\end{...}"
2068 found._dataStart = pos + sub.str(2).length();
2069 found._dataEnd = found._dataStart;
2070 found._tokensize = count + found._dataEnd - pos;
2071 found.parenthesiscount = 0;
2072 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2073 found.disabled = true;
2077 else if (found.keytype != KeyInfo::isRegex) {
2078 found._tokenstart = sub.position(size_t(2));
2079 if (found.parenthesiscount == 0) {
2080 // Probably to be discarded
2081 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2082 char following = interval_.par[following_pos];
2083 if (following == ' ')
2084 found.head = "\\" + sub.str(5) + " ";
2085 else if (following == '=') {
2086 // like \uldepth=1000pt
2087 found.head = sub.str(2);
2090 found.head = "\\" + key;
2091 found._tokensize = found.head.length();
2092 found._dataEnd = found._tokenstart + found._tokensize;
2093 found._dataStart = found._dataEnd;
2096 int params = found._tokenstart + key.length() + 1;
2097 if (evaluatingOptional) {
2098 if (size_t(found._tokenstart) > optionalEnd) {
2099 evaluatingOptional = false;
2102 found.disabled = true;
2105 int optend = params;
2106 while (interval_.par[optend] == '[') {
2107 // discard optional parameters
2108 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2110 if (optend > params) {
2111 key += interval_.par.substr(params, optend-params);
2112 evaluatingOptional = true;
2113 optionalEnd = optend;
2114 if (found.keytype == KeyInfo::isSectioning) {
2115 // Remove optional values (but still keep in header)
2116 interval_.addIntervall(params, optend);
2119 string token = sub.str(7);
2121 if (interval_.par[optend] != '{') {
2123 found.parenthesiscount = 0;
2124 found.head = "\\" + key;
2127 closings = found.parenthesiscount;
2128 if (found.parenthesiscount == 1) {
2129 found.head = "\\" + key + "{";
2131 else if (found.parenthesiscount > 1) {
2133 found.head = sub.str(2) + "{";
2134 closings = found.parenthesiscount - 1;
2137 found.head = "\\" + key + "{";
2140 found._tokensize = found.head.length();
2141 found._dataStart = found._tokenstart + found.head.length();
2142 if (found.keytype == KeyInfo::doRemove) {
2144 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2145 if (endpar >= interval_.par.length())
2146 found._dataStart = interval_.par.length();
2148 found._dataStart = endpar;
2149 found._tokensize = found._dataStart - found._tokenstart;
2152 found._dataStart = found._tokenstart + found._tokensize;
2156 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2157 found._dataStart += 15;
2161 endpos = found._dataStart - 1;
2163 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2164 if (found.keytype == KeyInfo::isList) {
2165 // Check if it really is list env
2166 static regex const listre("^([a-z]+)$");
2168 if (!regex_match(token, sub2, listre)) {
2169 // Change the key of this entry. It is not in a list/item environment
2170 found.keytype = KeyInfo::endArguments;
2173 if (found.keytype == KeyInfo::noMain) {
2174 evaluatingCode = true;
2176 codeStart = found._dataStart;
2178 else if (evaluatingCode) {
2179 if (size_t(found._dataStart) > codeEnd)
2180 evaluatingCode = false;
2181 else if (found.keytype == KeyInfo::isMain) {
2182 // Disable this key, treate it as standard
2183 found.keytype = KeyInfo::isStandard;
2184 found.disabled = true;
2185 if ((codeEnd +1 >= interval_.par.length()) &&
2186 (found._tokenstart == codeStart)) {
2187 // trickery, because the code inset starts
2188 // with \selectlanguage ...
2190 if (entries_.size() > 1) {
2191 entries_[entries_.size()-1]._dataEnd = codeEnd;
2196 if ((endpos == interval_.par.length()) &&
2197 (found.keytype == KeyInfo::doRemove)) {
2198 // Missing closing => error in latex-input?
2199 // therefore do not delete remaining data
2200 found._dataStart -= 1;
2201 found._dataEnd = found._dataStart;
2204 found._dataEnd = endpos;
2206 if (isPatternString) {
2207 keys[key].used = true;
2210 entries_.push_back(found);
2214 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2216 stringstream s(keysstring);
2218 const char delim = '|';
2219 while (getline(s, key, delim)) {
2220 KeyInfo keyII(keyI);
2221 if (isPatternString) {
2224 else if ( !keys[key].used)
2225 keyII.disabled = true;
2230 void LatexInfo::buildKeys(bool isPatternString)
2233 static bool keysBuilt = false;
2234 if (keysBuilt && !isPatternString) return;
2236 // Keys to ignore in any case
2237 makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2238 // Known standard keys with 1 parameter.
2239 // Split is done, if not at start of region
2240 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2241 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2242 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2243 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2244 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2245 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2247 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2248 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2249 makeKey("section*|subsection*|subsubsection*|paragraph*",
2250 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2251 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2252 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2254 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2256 // Split is done, if not at start of region
2257 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2258 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2260 // Split is done always.
2261 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2265 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2266 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2267 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2268 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2270 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2271 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2272 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2273 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2275 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2276 // Custom space/skip, remove the content (== length value)
2277 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2278 // Found in fr/UserGuide.lyx
2279 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2281 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2282 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2283 // Known macros to remove (including their parameter)
2285 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2286 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2287 // handle like standard keys with 1 parameter.
2288 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2290 // Ignore deleted text
2291 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2292 // but preserve added text
2293 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2295 // Macros to remove, but let the parameter survive
2297 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2299 // Remove language spec from content of these insets
2300 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2302 // Same effect as previous, parameter will survive (because there is no one anyway)
2304 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2305 // Remove table decorations
2306 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2307 // Discard shape-header.
2308 // For footnote or shortcut too, because of lang settings
2309 // and wrong handling if used 'KeyInfo::noMain'
2310 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2311 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2312 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2313 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2314 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2315 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2316 // like ('tiny{}' or '\tiny ' ... )
2317 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2319 // Survives, like known character
2320 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2321 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2322 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2324 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2325 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2326 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2328 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2329 // Remove RTL/LTR marker
2330 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2331 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2332 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2333 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2334 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2335 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2336 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2337 if (isPatternString) {
2338 // Allow the first searched string to rebuild the keys too
2342 // no need to rebuild again
2348 * Keep the list of actual opened parentheses actual
2349 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2351 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2354 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2358 if (c == '\\') skip = 1;
2359 else if (c == '{') {
2362 else if (c == '}') {
2363 handleCloseP(i, closingAllowed);
2369 string Intervall::show(int lastpos)
2371 int idx = 0; /* int intervalls */
2374 for (idx = 0; idx <= ignoreidx; idx++) {
2375 while (i < lastpos) {
2377 if (i <= borders[idx].low) {
2378 if (borders[idx].low > lastpos)
2379 printsize = lastpos - i;
2381 printsize = borders[idx].low - i;
2382 s += par.substr(i, printsize);
2384 if (i >= borders[idx].low)
2385 i = borders[idx].upper;
2388 i = borders[idx].upper;
2394 s += par.substr(i, lastpos-i);
2400 void Intervall::output(ostringstream &os, int lastpos)
2402 // get number of chars to output
2403 int idx = 0; /* int intervalls */
2406 string startTitle = titleValue;
2407 for (idx = 0; idx <= ignoreidx; idx++) {
2409 if (i <= borders[idx].low) {
2411 if (borders[idx].low > lastpos)
2412 printsize = lastpos - i;
2414 printsize = borders[idx].low - i;
2415 if (printsize > 0) {
2416 os << startTitle << par.substr(i, printsize);
2418 printed += printsize;
2421 handleParentheses(i, false);
2422 if (i >= borders[idx].low)
2423 i = borders[idx].upper;
2426 i = borders[idx].upper;
2433 os << startTitle << par.substr(i, lastpos-i);
2434 printed += lastpos-i;
2436 handleParentheses(lastpos, false);
2438 if (keys["foreignlanguage"].disabled)
2439 startindex = actualdeptindex-langcount;
2441 startindex = actualdeptindex;
2442 for (int i = startindex; i > 0; --i) {
2445 if (hasTitle && (printed > 0))
2447 if (! isPatternString_)
2449 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2452 void LatexInfo::processRegion(int start, int region_end)
2454 while (start < region_end) { /* Let {[} and {]} survive */
2455 int cnt = interval_.isOpeningPar(start);
2457 // Closing is allowed past the region
2458 int closing = interval_.findclosing(start+1, interval_.par.length());
2459 interval_.addIntervall(start, start+1);
2460 interval_.addIntervall(closing, closing+1);
2464 start = interval_.nextNotIgnored(start+1);
2468 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2470 if (actual.parenthesiscount == 0) {
2471 // "{\tiny{} ...}" ==> "{{} ...}"
2472 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2475 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2476 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2477 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2481 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2484 switch (actual.keytype)
2486 case KeyInfo::isTitle: {
2488 nextKeyIdx = getNextKey();
2491 case KeyInfo::cleanToStart: {
2492 actual._dataEnd = actual._dataStart;
2493 nextKeyIdx = getNextKey();
2494 // Search for end of arguments
2495 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2497 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2498 entries_[i].disabled = true;
2500 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2502 while (interval_.par[actual._dataEnd] == ' ')
2504 interval_.addIntervall(0, actual._dataEnd+1);
2505 interval_.actualdeptindex = 0;
2506 interval_.depts[0] = actual._dataEnd+1;
2507 interval_.closes[0] = -1;
2510 case KeyInfo::isText:
2511 interval_.par[actual._tokenstart] = '#';
2512 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2513 nextKeyIdx = getNextKey();
2515 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2516 if (actual.disabled)
2517 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2519 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2522 case KeyInfo::isChar: {
2523 nextKeyIdx = getNextKey();
2526 case KeyInfo::isSize: {
2527 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2528 if (actual.parenthesiscount == 0)
2529 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2531 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2533 nextKeyIdx = getNextKey();
2535 // Here _dataStart points to '{', so correct it
2536 actual._dataStart += 1;
2537 actual._tokensize += 1;
2538 actual.parenthesiscount = 1;
2539 if (interval_.par[actual._dataStart] == '}') {
2540 // Determine the end if used like '{\tiny{}...}'
2541 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2542 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2545 // Determine the end if used like '\tiny{...}'
2546 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2548 // Split on this key if not at start
2549 int start = interval_.nextNotIgnored(previousStart);
2550 if (start < actual._tokenstart) {
2551 interval_.output(os, actual._tokenstart);
2552 interval_.addIntervall(start, actual._tokenstart);
2554 // discard entry if at end of actual
2555 nextKeyIdx = process(os, actual);
2559 case KeyInfo::endArguments: {
2560 // Remove trailing '{}' too
2561 actual._dataStart += 1;
2562 actual._dataEnd += 1;
2563 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2564 nextKeyIdx = getNextKey();
2567 case KeyInfo::noMain:
2569 case KeyInfo::isStandard: {
2570 if (actual.disabled) {
2572 processRegion(actual._dataStart, actual._dataStart+1);
2573 nextKeyIdx = getNextKey();
2575 // Split on this key if not at datastart of calling entry
2576 int start = interval_.nextNotIgnored(previousStart);
2577 if (start < actual._tokenstart) {
2578 interval_.output(os, actual._tokenstart);
2579 interval_.addIntervall(start, actual._tokenstart);
2581 // discard entry if at end of actual
2582 nextKeyIdx = process(os, actual);
2586 case KeyInfo::removeWithArg: {
2587 nextKeyIdx = getNextKey();
2588 // Search for end of arguments
2589 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2591 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2592 entries_[i].disabled = true;
2594 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2596 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2599 case KeyInfo::doRemove: {
2600 // Remove the key with all parameters and following spaces
2603 if (interval_.par[actual._dataEnd-1] == ' ')
2604 start = actual._dataEnd;
2606 start = actual._dataEnd+1;
2607 for (pos = start; pos < interval_.par.length(); pos++) {
2608 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2611 // Remove also enclosing parentheses [] and {}
2614 while (actual._tokenstart > numpars) {
2615 if (pos+numpars >= interval_.par.size())
2617 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2619 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2625 if (interval_.par[pos+numpars] == ' ')
2629 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2630 nextKeyIdx = getNextKey();
2633 case KeyInfo::isList: {
2634 // Discard space before _tokenstart
2636 for (count = 0; count < actual._tokenstart; count++) {
2637 if (interval_.par[actual._tokenstart-count-1] != ' ')
2640 nextKeyIdx = getNextKey();
2641 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2643 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2645 // How else can we catch this one?
2646 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2647 entries_[i].disabled = true;
2649 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2651 else if (nextKeyIdx > 0) {
2652 // Ignore any lang entries inside data region
2653 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2654 if (entries_[i].keytype == KeyInfo::isMain)
2655 entries_[i].disabled = true;
2658 if (actual.disabled) {
2659 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2662 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2664 if (interval_.par[actual._dataEnd+1] == '[') {
2665 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2666 if ((interval_.par[actual._dataEnd+2] == '{') &&
2667 (interval_.par[posdown-1] == '}')) {
2668 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2669 interval_.addIntervall(posdown-1, posdown+1);
2672 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2673 interval_.addIntervall(posdown, posdown+1);
2675 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2676 if (blk > posdown) {
2677 // Discard at most 1 space after empty item
2679 for (count = 0; count < 1; count++) {
2680 if (interval_.par[blk+count] != ' ')
2684 interval_.addIntervall(blk, blk+count);
2689 case KeyInfo::isSectioning: {
2690 // Discard spaces before _tokenstart
2692 int val = actual._tokenstart;
2693 for (count = 0; count < actual._tokenstart;) {
2694 val = interval_.previousNotIgnored(val-1);
2695 if (val < 0 || interval_.par[val] != ' ')
2698 count = actual._tokenstart - val;
2701 if (actual.disabled) {
2702 removeHead(actual, count);
2703 nextKeyIdx = getNextKey();
2705 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2706 nextKeyIdx = process(os, actual);
2710 case KeyInfo::isMath: {
2711 // Same as regex, use the content unchanged
2712 nextKeyIdx = getNextKey();
2715 case KeyInfo::isRegex: {
2716 // DO NOT SPLIT ON REGEX
2718 nextKeyIdx = getNextKey();
2721 case KeyInfo::isIgnored: {
2722 // Treat like a character for now
2723 nextKeyIdx = getNextKey();
2726 case KeyInfo::isMain: {
2727 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2728 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2729 if (actual._tokenstart > 0) {
2730 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2731 if ((prev >= 0) && interval_.par[prev] == '%')
2732 interval_.addIntervall(prev, prev+1);
2734 if (actual.disabled) {
2736 interval_.langcount++;
2737 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2738 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2739 // Discard also the space before math-equation
2740 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2742 nextKeyIdx = getNextKey();
2743 // interval.resetOpenedP(actual._dataStart-1);
2746 if (actual._tokenstart < 26) {
2747 // for the first (and maybe dummy) language
2748 interval_.setForDefaultLang(actual);
2750 interval_.resetOpenedP(actual._dataStart-1);
2754 case KeyInfo::invalid:
2755 case KeyInfo::headRemove:
2756 // These two cases cannot happen, already handled
2759 // LYXERR(Debug::INFO, "Unhandled keytype");
2760 nextKeyIdx = getNextKey();
2767 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2769 int end = interval_.nextNotIgnored(actual._dataEnd);
2770 int oldStart = actual._dataStart;
2771 int nextKeyIdx = getNextKey();
2773 if ((nextKeyIdx < 0) ||
2774 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2775 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2776 if (oldStart <= end) {
2777 processRegion(oldStart, end);
2782 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2784 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2785 (void) dispatch(os, actual._dataStart, nextKey);
2786 end = nextKey._tokenstart;
2789 processRegion(oldStart, nextKey._tokenstart);
2790 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2792 oldStart = nextKey._dataEnd+1;
2794 // now nextKey is either invalid or is outside of actual._dataEnd
2795 // output the remaining and discard myself
2796 if (oldStart <= end) {
2797 processRegion(oldStart, end);
2799 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2801 // This is the normal case.
2802 // But if using the firstlanguage, the closing may be missing
2804 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2806 if (actual._dataEnd < end)
2807 output_end = interval_.nextNotIgnored(actual._dataEnd);
2808 else if (interval_.par.size() > (size_t) end)
2809 output_end = interval_.nextNotIgnored(end);
2811 output_end = interval_.par.size();
2812 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2813 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2815 // Remove possible empty data
2816 int dstart = interval_.nextNotIgnored(actual._dataStart);
2817 while (interval_.isOpeningPar(dstart) == 1) {
2818 interval_.addIntervall(dstart, dstart+1);
2819 int dend = interval_.findclosing(dstart+1, output_end);
2820 interval_.addIntervall(dend, dend+1);
2821 dstart = interval_.nextNotIgnored(dstart+1);
2823 if (dstart < output_end)
2824 interval_.output(os, output_end);
2825 interval_.addIntervall(actual._tokenstart, end);
2829 string splitOnKnownMacros(string par, bool isPatternString)
2832 LatexInfo li(par, isPatternString);
2833 // LYXERR(Debug::INFO, "Berfore split: " << par);
2834 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2836 DummyKey._tokensize = 0;
2837 DummyKey._dataStart = 0;
2838 DummyKey._dataEnd = par.length();
2839 DummyKey.disabled = true;
2840 int firstkeyIdx = li.getFirstKey();
2842 if (firstkeyIdx >= 0) {
2843 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2844 DummyKey._tokenstart = firstKey._tokenstart;
2846 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2847 // Use dummy firstKey
2848 firstKey = DummyKey;
2849 (void) li.setNextKey(firstkeyIdx);
2852 if (par.substr(firstKey._dataStart, 2) == "% ")
2853 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2855 nextkeyIdx = li.process(os, firstKey);
2856 while (nextkeyIdx >= 0) {
2857 // Check for a possible gap between the last
2858 // entry and this one
2859 int datastart = li.nextNotIgnored(firstKey._dataStart);
2860 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2861 if ((nextKey._tokenstart > datastart)) {
2863 firstKey._dataStart = datastart;
2864 firstKey._dataEnd = par.length();
2865 (void) li.setNextKey(nextkeyIdx);
2866 // Fake the last opened parenthesis
2867 li.setForDefaultLang(firstKey);
2868 nextkeyIdx = li.process(os, firstKey);
2871 if (nextKey.keytype != KeyInfo::isMain) {
2872 firstKey._dataStart = datastart;
2873 firstKey._dataEnd = nextKey._dataEnd+1;
2874 (void) li.setNextKey(nextkeyIdx);
2875 li.setForDefaultLang(firstKey);
2876 nextkeyIdx = li.process(os, firstKey);
2879 nextkeyIdx = li.process(os, nextKey);
2883 // Handle the remaining
2884 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2885 firstKey._dataEnd = par.length();
2887 if ((firstKey._dataStart < firstKey._dataEnd) &&
2888 (par[firstKey._dataStart] != '}')) {
2889 li.setForDefaultLang(firstKey);
2890 (void) li.process(os, firstKey);
2894 // return string definitelly impossible to match
2895 s = "\\foreignlanguage{ignore}{ }";
2899 s = par; /* no known macros found */
2900 // LYXERR(Debug::INFO, "After split: " << s);
2905 * Try to unify the language specs in the latexified text.
2906 * Resulting modified string is set to "", if
2907 * the searched tex does not contain all the features in the search pattern
2909 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2911 static Features regex_f;
2912 static int missed = 0;
2913 static bool regex_with_format = false;
2915 int parlen = par.length();
2917 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2920 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2921 // Happens to be there in case of description or labeling environment
2926 // Split the latex input into pieces which
2927 // can be digested by our search engine
2928 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2929 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2930 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2933 result = par.substr(0, parlen);
2934 if (isPatternString) {
2937 regex_f = identifyFeatures(result);
2938 string features = "";
2939 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2940 string a = it->first;
2941 regex_with_format = true;
2942 features += " " + a;
2943 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2945 LYXERR(Debug::FIND, "Identified Features" << features);
2948 } else if (regex_with_format) {
2949 Features info = identifyFeatures(result);
2950 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2951 string a = it->first;
2952 bool b = it->second;
2953 if (b && ! info[a]) {
2955 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2962 // LYXERR(Debug::INFO, "No regex formats");
2968 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2969 static int identifyClosing(string & t)
2971 int open_braces = 0;
2973 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2974 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2976 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2978 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2980 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2989 static int num_replaced = 0;
2990 static bool previous_single_replace = true;
2992 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2995 // Handle \w properly
2996 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2997 if (! opt.casesensitive) {
2998 popts |= QRegularExpression::CaseInsensitiveOption;
3000 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3001 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3003 if (regexp.isValid() && regexp2.isValid()) {
3004 regexIsValid = true;
3005 // Check '{', '}' pairs inside the regex
3008 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3009 char c = par_as_string[i];
3016 else if (c == '}') {
3023 if (balanced != 0) {
3024 regexIsValid = false;
3025 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3029 regexIsValid = false;
3030 if (!regexp.isValid())
3031 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3033 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3036 if (opt.casesensitive) {
3037 regexp = regex(regexp_str);
3038 regexp2 = regex(regexp2_str);
3041 regexp = regex(regexp_str, std::regex_constants::icase);
3042 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3047 static void modifyRegexForMatchWord(string &t)
3050 regex wordre("(\\\\)*((\\.|\\\\b))");
3053 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3055 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3058 else if (sub.str(2) == "\\\\b")
3060 if (lastpos < (size_t) sub.position(2))
3061 s += t.substr(lastpos, sub.position(2) - lastpos);
3063 lastpos = sub.position(2) + sub.length(2);
3066 s = "\\b" + t + "\\b";
3070 else if (lastpos < t.length())
3071 s += t.substr(lastpos, t.length() - lastpos);
3072 t = "\\b" + s + "\\b";
3075 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3076 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3078 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3079 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3080 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3081 if (opt.replace_all && previous_single_replace) {
3082 previous_single_replace = false;
3085 else if (!opt.replace_all) {
3086 num_replaced = 0; // count number of replaced strings
3087 previous_single_replace = true;
3089 // When using regexp, braces are hacked already by escape_for_regex()
3090 par_as_string = normalize(ds);
3092 close_wildcards = 0;
3094 size_t lead_size = 0;
3095 // correct the language settings
3096 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
3097 opt.matchstart = false;
3099 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3100 if (opt.ignoreformat) {
3104 lead_size = identifyLeading(par_as_string);
3106 lead_as_string = par_as_string.substr(0, lead_size);
3107 string lead_as_regex_string = string2regex(lead_as_string);
3108 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3109 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3110 /* Handle whole words too in this case
3112 if (opt.matchword) {
3113 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3114 opt.matchword = false;
3116 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3117 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3118 CreateRegexp(opt, regexp_str, regexp2_str);
3120 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3121 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3125 if (!opt.ignoreformat) {
3126 lead_size = identifyLeading(par_as_string);
3127 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3128 lead_as_string = par_as_string.substr(0, lead_size);
3129 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3132 // Here we are using regexp
3133 LASSERT(use_regexp, /**/);
3135 string lead_as_regexp;
3136 if (lead_size > 0) {
3137 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3138 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3139 par_as_string = par_as_string_nolead;
3140 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3141 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3143 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3144 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3145 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3146 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3147 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3149 size_t lng = par_as_string.size();
3150 if (!opt.ignoreformat) {
3151 // Remove extra '\}' at end if not part of \{\.\}
3153 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3155 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3164 if (lng < par_as_string.size())
3165 par_as_string = par_as_string.substr(0,lng);
3167 if ((lng > 0) && (par_as_string[0] == '^')) {
3168 par_as_string = par_as_string.substr(1);
3170 opt.matchstart = true;
3172 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3173 LYXERR(Debug::FIND, "Open braces: " << open_braces);
3174 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3176 // If entered regexp must match at begin of searched string buffer
3177 // Kornel: Added parentheses to use $1 for size of the leading string
3181 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3182 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3183 // so the convert has no effect in that case
3184 for (int i = 7; i > 0; --i) {
3185 string orig = "\\\\" + std::to_string(i);
3186 string dest = "\\" + std::to_string(i+2);
3187 while (regex_replace(par_as_string, par_as_string, orig, dest));
3189 if (opt.matchword) {
3190 modifyRegexForMatchWord(par_as_string);
3191 opt.matchword = false;
3193 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3194 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3196 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3197 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3198 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3203 // Count number of characters in string
3207 // \\[a-zA-Z]+ ==> 1
3209 static int computeSize(QStringRef s, int len)
3210 #define isLyxAlpha(arg) arg.isLetter()
3212 static int computeSize(string s, int len)
3213 #define isLyxAlpha(arg) isalpha(arg)
3220 for (int i = 0; i < len; i += skip, count++) {
3221 if (s.at(i) == '\\') {
3223 if (i + 1 < len && isLyxAlpha(s.at(i+1))) {
3224 for (int j = 2; i+j < len; j++) {
3225 if (! isLyxAlpha(s.at(i+j))) {
3226 if (s.at(i+j) == ' ')
3228 else if (s.at(i+j) == '{') {
3229 if (i+j+1 < len && s.at(i+j+1) == '}')
3231 else if (i + j + 1 >= len)
3240 else if (s.at(i) == '{') {
3241 if (i + 1 < len && s.at(i+1) == '}')
3246 else if (s.at(i) == '-') {
3247 if (i+1 < len && s.at(i+1) == '-') {
3248 if (i + 2 < len && s.at(i+2) == '-')
3264 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3268 mres.searched_size = len;
3270 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3273 docstring docstr = stringifyFromForSearch(opt, cur, len);
3275 if (use_regexp || opt.casesensitive)
3276 str = normalize(docstr);
3278 str = normalize(lowercase(docstr));
3279 if (!opt.ignoreformat) {
3280 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3281 // remove closing '}' and '\n' to allow for use of '$' in regex
3282 size_t lng = str.size();
3283 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3285 if (lng != str.size()) {
3286 str = str.substr(0, lng);
3290 mres.match_len = -1;
3293 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
3294 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3297 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3299 QString qstr = QString::fromStdString(str);
3300 QRegularExpression const *p_regexp;
3301 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3305 p_regexp = ®exp2;
3307 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3308 if (!match.hasMatch())
3311 regex const *p_regexp;
3312 regex_constants::match_flag_type flags;
3314 flags = regex_constants::match_continuous;
3317 flags = regex_constants::match_default;
3318 p_regexp = ®exp2;
3320 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3321 if (re_it == sregex_iterator())
3323 match_results<string::const_iterator> const & m = *re_it;
3325 // Whole found string, including the leading
3326 // std: m[0].second - m[0].first
3327 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3329 // Size of the leading string
3330 // std: m[1].second - m[1].first
3331 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3332 int leadingsize = 0;
3334 if (match.lastCapturedIndex() > 0) {
3335 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3340 leadingsize = m[1].second - m[1].first;
3344 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3345 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3346 // because of different number of closing at end of string
3347 // we have to 'unify' the length of the post-match.
3348 // Done by ignoring closing parenthesis and linefeeds at string end
3349 int matchend = match.capturedEnd(0);
3350 while (mres.match_len > 0) {
3351 QChar c = qstr.at(matchend - 1);
3352 if ((c == '\n') || (c == '}') || (c == '{')) {
3359 size_t strsize = qstr.size();
3360 while (strsize > (size_t) match.capturedEnd(0)) {
3361 QChar c = qstr.at(strsize-1);
3362 if ((c == '\n') || (c == '}')) {
3368 // LYXERR0(qstr.toStdString());
3369 mres.match2end = strsize - matchend;
3370 mres.pos = match.capturedStart(2);
3372 mres.match_prefix = m[2].second - m[2].first;
3373 mres.match_len = m[0].second - m[2].second;
3374 // ignore closing parenthesis and linefeeds at string end
3375 size_t strend = m[0].second - m[0].first;
3376 int matchend = strend;
3377 while (mres.match_len > 0) {
3378 char c = str.at(matchend - 1);
3379 if ((c == '\n') || (c == '}') || (c == '{')) {
3386 size_t strsize = str.size();
3387 while (strsize > strend) {
3388 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3395 mres.match2end = strsize - matchend;
3396 mres.pos = m[2].first - m[0].first;;
3398 if (mres.match2end < 0)
3400 mres.leadsize = leadingsize;
3402 if (mres.match_len > 0) {
3403 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3404 mres.result.push_back(a0);
3405 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3406 mres.result.push_back(match.captured(i).toStdString());
3410 if (mres.match_len > 0) {
3411 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3412 mres.result.push_back(a0);
3413 for (size_t i = 3; i < m.size(); i++) {
3414 mres.result.push_back(m[i]);
3421 // else !use_regexp: but all code paths above return
3422 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3423 << par_as_string << "', str='" << str << "'");
3424 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3425 << lead_as_string << "', par_as_string_nolead='"
3426 << par_as_string_nolead << "'");
3429 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3430 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3431 if (str.substr(0, par_as_string.size()) == par_as_string) {
3432 mres.match_len = par_as_string.size();
3433 mres.match2end = str.size();
3438 // Start the search _after_ the leading part
3439 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3440 if (pos != string::npos) {
3441 mres.match_len = par_as_string.size();
3442 mres.match2end = str.size() - pos;
3451 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3453 MatchResult mres = findAux(cur, len, at_begin);
3454 int res = mres.match_len;
3456 "res=" << res << ", at_begin=" << at_begin
3457 << ", matchstart=" << opt.matchstart
3458 << ", inTexted=" << cur.inTexted());
3459 if (opt.matchstart) {
3462 else if (mres.match_prefix > 0)
3471 static bool simple_replace(string &t, string from, string to)
3473 regex repl("(\\\\)*(" + from + ")");
3477 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3479 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3481 if (lastpos < (size_t) sub.position(2))
3482 s += t.substr(lastpos, sub.position(2) - lastpos);
3484 lastpos = sub.position(2) + sub.length(2);
3488 else if (lastpos < t.length())
3489 s += t.substr(lastpos, t.length() - lastpos);
3495 string MatchStringAdv::normalize(docstring const & s) const
3498 t = lyx::to_utf8(s);
3499 // Remove \n at begin
3500 while (!t.empty() && t[0] == '\n')
3503 while (!t.empty() && t[t.size() - 1] == '\n')
3504 t = t.substr(0, t.size() - 1);
3506 // Handle all other '\n'
3507 while ((pos = t.find("\n")) != string::npos) {
3508 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3510 if (isAlnumASCII(t[pos+1])) {
3511 t.replace(pos-2, 3, " ");
3514 t.replace(pos-2, 3, "");
3517 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3518 // '\n' adjacent to non-alpha-numerics, discard
3519 t.replace(pos, 1, "");
3522 // Replace all other \n with spaces
3523 t.replace(pos, 1, " ");
3526 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3527 // Kornel: Added textsl, textsf, textit, texttt and noun
3528 // + allow to seach for colored text too
3529 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3530 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3531 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3532 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3533 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3534 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3540 docstring stringifyFromCursor(DocIterator const & cur, int len)
3542 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3543 if (cur.inTexted()) {
3544 Paragraph const & par = cur.paragraph();
3545 // TODO what about searching beyond/across paragraph breaks ?
3546 // TODO Try adding a AS_STR_INSERTS as last arg
3547 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3548 int(par.size()) : cur.pos() + len;
3549 // OutputParams runparams(&cur.buffer()->params().encoding());
3550 OutputParams runparams(encodings.fromLyXName("utf8"));
3551 runparams.nice = true;
3552 runparams.flavor = Flavor::XeTeX;
3553 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3554 // No side effect of file copying and image conversion
3555 runparams.dryrun = true;
3556 runparams.for_search = true;
3557 LYXERR(Debug::FIND, "Stringifying with cur: "
3558 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3559 return par.asString(cur.pos(), end,
3560 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3562 } else if (cur.inMathed()) {
3563 CursorSlice cs = cur.top();
3564 MathData md = cs.cell();
3565 MathData::const_iterator it_end =
3566 (( len == -1 || cs.pos() + len > int(md.size()))
3568 : md.begin() + cs.pos() + len );
3570 for (MathData::const_iterator it = md.begin() + cs.pos();
3573 docstring s = asString(md2);
3574 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3577 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3582 /** Computes the LaTeX export of buf starting from cur and ending len positions
3583 * after cur, if len is positive, or at the paragraph or innermost inset end
3586 docstring latexifyFromCursor(DocIterator const & cur, int len)
3588 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3589 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3590 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3591 Buffer const & buf = *cur.buffer();
3593 odocstringstream ods;
3595 //OutputParams runparams(&buf.params().encoding());
3596 OutputParams runparams(encodings.fromLyXName("utf8"));
3597 runparams.nice = false;
3598 runparams.flavor = Flavor::XeTeX;
3599 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3600 // No side effect of file copying and image conversion
3601 runparams.dryrun = true;
3602 runparams.for_search = true;
3604 if (cur.inTexted()) {
3605 // @TODO what about searching beyond/across paragraph breaks ?
3606 pos_type endpos = cur.paragraph().size();
3607 if (len != -1 && endpos > cur.pos() + len)
3608 endpos = cur.pos() + len;
3609 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3610 string(), cur.pos(), endpos);
3611 string s = lyx::to_utf8(ods.str());
3612 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3613 return(lyx::from_utf8(s));
3614 } else if (cur.inMathed()) {
3615 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3616 for (int s = cur.depth() - 1; s >= 0; --s) {
3617 CursorSlice const & cs = cur[s];
3618 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3619 TeXMathStream ws(os);
3620 cs.asInsetMath()->asHullInset()->header_write(ws);
3625 CursorSlice const & cs = cur.top();
3626 MathData md = cs.cell();
3627 MathData::const_iterator it_end =
3628 ((len == -1 || cs.pos() + len > int(md.size()))
3630 : md.begin() + cs.pos() + len);
3632 for (MathData::const_iterator it = md.begin() + cs.pos();
3636 ods << asString(md2);
3637 // Retrieve the math environment type, and add '$' or '$]'
3638 // or others (\end{equation}) accordingly
3639 for (int s = cur.depth() - 1; s >= 0; --s) {
3640 CursorSlice const & cs2 = cur[s];
3641 InsetMath * inset = cs2.asInsetMath();
3642 if (inset && inset->asHullInset()) {
3643 TeXMathStream ws(os);
3644 inset->asHullInset()->footer_write(ws);
3648 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3650 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3655 #if defined(ResultsDebug)
3657 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3659 LYXERR0( "from:\t\t\t" << from);
3661 if (mres.pos_len > 0) {
3663 status = "FINALSEARCH";
3666 if (mres.match_len > 0) {
3667 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3668 status = "Good Match";
3670 status = "Matched in";
3673 status = "MissedSearch";
3676 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3677 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3678 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3679 if ((mres.pos > 0) || (mres.match_prefix > 0))
3680 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3681 for (size_t i = 0; i < mres.result.size(); i++)
3682 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3684 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3686 #define displayMres(s, txt, cur)
3689 /** Finalize an advanced find operation, advancing the cursor to the innermost
3690 ** position that matches, plus computing the length of the matching text to
3692 ** Return the cur.pos() difference between start and end of found match
3694 MatchResult &findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3696 // Search the foremost position that matches (avoids find of entire math
3697 // inset when match at start of it)
3698 DocIterator old_cur(cur.buffer());
3700 static MatchResult fail = MatchResult();
3701 static MatchResult max_match;
3702 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3703 // Happens with e.g. hyperlinks
3704 // either one sees "http://www.bla.bla" or nothing
3705 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3706 // and although we search for only 3 chars, we find the whole hyperlink inset
3707 bool at_begin = (expected.match_prefix == 0);
3708 LASSERT(at_begin, /**/);
3709 if (expected.match_len > 0 && at_begin) {
3710 // Search for deepest match
3712 max_match = expected;
3714 size_t d = cur.depth();
3718 if (cur.depth() < d)
3720 if (cur.depth() == d)
3723 while (cur && cur.depth() > lastd) {
3724 lastd = cur.depth();
3725 mres = match(cur, -1, at_begin);
3726 displayMres(mres, "Checking innermost", cur);
3727 if (mres.match_len > 0)
3732 if (mres.match_len < expected.match_len)
3740 // (expected.match_len <= 0)
3741 mres = match(cur); /* match valid only if not searching whole words */
3742 displayMres(mres, "Start with negative match", cur);
3745 if (max_match.match_len <= 0) return fail;
3746 LYXERR(Debug::FIND, "Ok");
3748 // Compute the match length
3750 if (cur.pos() + len > cur.lastpos())
3752 // regexp should use \w+, \S+, or \b(some string)\b
3753 // to search for whole words
3754 if (match.opt.matchword && !match.use_regexp) {
3755 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3756 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3758 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3760 // Length of matched text (different from len param)
3761 static MatchResult old_match = match(cur, len, at_begin);
3762 if (old_match.match_len < 0)
3764 MatchResult new_match;
3765 // Greedy behaviour while matching regexps
3766 while ((new_match = match(cur, len + 1, at_begin)).match_len > old_match.match_len) {
3768 old_match = new_match;
3769 LYXERR(Debug::FIND, "verifying match with len = " << len);
3771 displayMres(old_match, "SEARCH RESULT", cur)
3776 int maxl = cur.lastpos() - cur.pos();
3777 // Greedy behaviour while matching regexps
3778 while (maxl > minl) {
3780 mres2 = match(cur, len, at_begin);
3781 displayMres(mres2, "Finalize loop", cur);
3782 int actual_match_len = mres2.match_len;
3783 if (actual_match_len >= max_match.match_len) {
3784 // actual_match_len > max_match _can_ happen,
3785 // if the search area splits
3786 // some following word so that the regex
3787 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3789 // This means, the len value is too big
3790 actual_match_len = max_match.match_len;
3792 max_match.match_len = actual_match_len;
3794 if (maxl - minl < 4)
3795 len = (int)((maxl + minl)/2);
3797 len = (int)(minl + (maxl - minl + 3)/4);
3800 // (actual_match_len < max_match.match_len)
3802 len = (int)((maxl + minl)/2);
3807 // Search for real start of matched characters
3809 MatchResult actual_match;
3812 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3813 if (cur.depth() < old_cur.depth()) {
3815 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3818 if (cur.pos() != old_cur.pos()) {
3819 // OK, forwarded 1 pos in actual inset
3820 actual_match = match(cur, len-1, at_begin);
3821 if (actual_match.match_len == max_match.match_len) {
3822 // Ha, got it! The shorter selection has the same match length
3825 max_match = actual_match;
3828 // OK, the shorter selection matches less chars, revert to previous value
3834 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3835 actual_match = match(cur, len, at_begin);
3836 if (actual_match.match_len == max_match.match_len) {
3838 max_match = actual_match;
3845 max_match.pos_len = len;
3846 displayMres(max_match, "SEARCH RESULT", cur)
3853 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3857 bool repeat = false;
3858 while (!theApp()->longOperationCancelled() && cur) {
3859 //(void) findAdvForwardInnermost(cur);
3860 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3861 MatchResult mres = match(cur, -1, false);
3862 string msg = "Starting";
3865 displayMres(mres, msg + " findForwardAdv", cur)
3866 int match_len = mres.match_len;
3867 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3868 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3871 if (match_len <= 0) {
3872 // This should exit nested insets, if any, or otherwise undefine the currsor.
3873 cur.pos() = cur.lastpos();
3874 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3877 else { // match_len > 0
3878 // Try to find the begin of searched string
3880 int firstInvalid = 100000;
3882 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3883 int incrcur = (cur.lastpos() - cur.pos() + 1 )*3/4;
3884 if (incrcur < incrmatch)
3885 increment = incrcur;
3887 increment = incrmatch;
3891 LYXERR(Debug::FIND, "Set increment to " << increment);
3892 while (increment > 0) {
3893 DocIterator old_cur = cur;
3894 size_t skipping = cur.depth();
3895 for (int i = 0; i < increment && cur; i++) {
3897 while (cur && cur.depth() > skipping) {
3898 cur.pos() = cur.lastpos();
3902 if (! cur || (cur.pit() > old_cur.pit())) {
3903 // Are we outside of the paragraph?
3904 // This can happen if moving past some UTF8-encoded chars
3909 MatchResult mres2 = match(cur, -1, false);
3910 displayMres(mres2, "findForwardAdv loop", cur)
3911 switch (interpretMatch(mres, mres2)) {
3912 case MatchResult::newIsTooFar:
3913 // behind the expected match
3914 firstInvalid = increment;
3918 case MatchResult::newIsBetter:
3919 // not reached yet, but cur.pos()+increment is bettert
3921 firstInvalid -= increment;
3922 if (increment > firstInvalid*3/4)
3923 increment = firstInvalid*3/4;
3924 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3925 if (increment >= mres2.match_prefix)
3926 increment = (mres2.match_prefix+1)*3/4;
3931 // Handle not like MatchResult::newIsTooFar
3932 LYXERR0( "Something is wrong: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3934 increment = increment*3/4;
3940 if (mres.match_len > 0 && mres.match_prefix + mres.pos - mres.leadsize > 0) {
3945 // LYXERR0("Leaving first loop");
3946 LYXERR(Debug::FIND, "Finalizing 1");
3947 MatchResult found_match = findAdvFinalize(cur, match, mres);
3948 if (found_match.match_len > 0) {
3949 LASSERT(found_match.pos_len > 0, /**/);
3950 match.FillResults(found_match);
3951 return found_match.pos_len;
3954 // try next possible match
3965 /// Find the most backward consecutive match within same paragraph while searching backwards.
3966 MatchResult &findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3968 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3969 DocIterator tmp_cur = cur;
3970 static MatchResult mr = findAdvFinalize(tmp_cur, match, MatchResult(-1));
3971 Inset & inset = cur.inset();
3972 for (; cur != cur_begin; cur.backwardPos()) {
3973 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3974 DocIterator new_cur = cur;
3975 new_cur.backwardPos();
3976 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3978 MatchResult new_mr = findAdvFinalize(new_cur, match, MatchResult(-1));
3979 if (new_mr.match_len == mr.match_len)
3983 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3989 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3993 // Backup of original position
3994 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3995 if (cur == cur_begin)
3998 DocIterator cur_orig(cur);
3999 bool pit_changed = false;
4002 bool found_match = (match(cur, -1, false).match_len > 0);
4006 cur.pos() = cur.lastpos();
4008 cur.pos() = cur_orig.pos();
4009 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
4010 DocIterator cur_prev_iter;
4012 found_match = (match(cur).match_len > 0);
4013 LYXERR(Debug::FIND, "findBackAdv3: found_match="
4014 << found_match << ", cur: " << cur);
4016 MatchResult found_mr = findMostBackwards(cur, match);
4017 match.FillResults(found_mr);
4018 LASSERT(found_mr.pos_len > 0, /**/);
4019 return found_mr.pos_len;
4022 // Stop if begin of document reached
4023 if (cur == cur_begin)
4025 cur_prev_iter = cur;
4029 if (cur == cur_begin)
4036 } while (!theApp()->longOperationCancelled());
4044 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4045 DocIterator const & cur, int len)
4047 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4049 if (!opt.ignoreformat)
4050 return latexifyFromCursor(cur, len);
4052 return stringifyFromCursor(cur, len);
4056 FindAndReplaceOptions::FindAndReplaceOptions(
4057 docstring const & _find_buf_name, bool _casesensitive,
4058 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4059 docstring const & _repl_buf_name, bool _keep_case,
4060 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4061 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4062 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4063 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4071 /** Check if 'len' letters following cursor are all non-lowercase */
4072 static bool allNonLowercase(Cursor const & cur, int len)
4074 pos_type beg_pos = cur.selectionBegin().pos();
4075 pos_type end_pos = cur.selectionBegin().pos() + len;
4076 if (len > cur.lastpos() + 1 - beg_pos) {
4077 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4078 len = cur.lastpos() + 1 - beg_pos;
4079 end_pos = beg_pos + len;
4081 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4082 if (isLowerCase(cur.paragraph().getChar(pos)))
4088 /** Check if first letter is upper case and second one is lower case */
4089 static bool firstUppercase(Cursor const & cur)
4092 pos_type pos = cur.selectionBegin().pos();
4093 if (pos >= cur.lastpos() - 1) {
4094 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4097 ch1 = cur.paragraph().getChar(pos);
4098 ch2 = cur.paragraph().getChar(pos + 1);
4099 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4100 LYXERR(Debug::FIND, "firstUppercase(): "
4101 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4102 << ch2 << "(" << char(ch2) << ")"
4103 << ", result=" << result << ", cur=" << cur);
4108 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4110 ** \fixme What to do with possible further paragraphs in replace buffer ?
4112 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4114 ParagraphList::iterator pit = buffer.paragraphs().begin();
4115 LASSERT(!pit->empty(), /**/);
4116 pos_type right = pos_type(1);
4117 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4118 right = pit->size();
4119 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4124 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4126 // Should replace the string "$" + std::to_string(matchnum) with replacement
4127 // if the char '$' is not prefixed with odd number of char '\\'
4128 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4132 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4134 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4136 int num = stoi(sub.str(3), nullptr, 10);
4137 if (num >= maxmatchnum)
4139 if (lastpos < (size_t) sub.position(2))
4140 s += t.substr(lastpos, sub.position(2) - lastpos);
4141 s += replacements[num];
4142 lastpos = sub.position(2) + sub.length(2);
4146 else if (lastpos < t.length())
4147 s += t.substr(lastpos, t.length() - lastpos);
4154 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4156 Cursor & cur = bv->cursor();
4157 if (opt.repl_buf_name.empty()
4158 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4159 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4162 DocIterator sel_beg = cur.selectionBegin();
4163 DocIterator sel_end = cur.selectionEnd();
4164 if (&sel_beg.inset() != &sel_end.inset()
4165 || sel_beg.pit() != sel_end.pit()
4166 || sel_beg.idx() != sel_end.idx())
4168 int sel_len = sel_end.pos() - sel_beg.pos();
4169 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4170 << ", sel_len: " << sel_len << endl);
4173 LASSERT(sel_len > 0, return 0);
4175 if (!matchAdv(sel_beg, sel_len).match_len)
4178 // Build a copy of the replace buffer, adapted to the KeepCase option
4179 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4181 repl_buffer_orig.write(oss);
4182 string lyx = oss.str();
4183 if (matchAdv.valid_matches > 0) {
4184 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4186 Buffer repl_buffer("", false);
4187 repl_buffer.setUnnamed(true);
4188 LASSERT(repl_buffer.readString(lyx), return 0);
4189 if (opt.keep_case && sel_len >= 2) {
4190 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4191 if (cur.inTexted()) {
4192 if (firstUppercase(cur))
4193 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4194 else if (allNonLowercase(cur, sel_len))
4195 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4198 cap::cutSelection(cur, false);
4199 if (cur.inTexted()) {
4200 repl_buffer.changeLanguage(
4201 repl_buffer.language(),
4202 cur.getFont().language());
4203 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4204 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4205 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4206 repl_buffer.params().documentClassPtr(),
4207 bv->buffer().errorList("Paste"));
4208 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4209 sel_len = repl_buffer.paragraphs().begin()->size();
4210 } else if (cur.inMathed()) {
4211 odocstringstream ods;
4213 // OutputParams runparams(&repl_buffer.params().encoding());
4214 OutputParams runparams(encodings.fromLyXName("utf8"));
4215 runparams.nice = false;
4216 runparams.flavor = Flavor::XeTeX;
4217 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4218 runparams.dryrun = true;
4219 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4220 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4221 docstring repl_latex = ods.str();
4222 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4224 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4225 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4226 repl_latex = from_utf8(s);
4227 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4228 MathData ar(cur.buffer());
4229 asArray(repl_latex, ar, Parse::NORMAL);
4231 sel_len = ar.size();
4232 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4234 if (cur.pos() >= sel_len)
4235 cur.pos() -= sel_len;
4238 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4239 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4240 bv->processUpdateFlags(Update::Force);
4245 /// Perform a FindAdv operation.
4246 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4251 // e.g., when invoking word-findadv from mini-buffer wither with
4252 // wrong options syntax or before ever opening advanced F&R pane
4253 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4257 MatchStringAdv matchAdv(bv->buffer(), opt);
4259 if (!matchAdv.regexIsValid) {
4260 bv->message(lyx::from_utf8(matchAdv.regexError));
4264 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4266 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4267 num_replaced += findAdvReplace(bv, opt, matchAdv);
4270 pos_len = findForwardAdv(cur, matchAdv);
4272 pos_len = findBackwardsAdv(cur, matchAdv);
4273 } catch (exception & ex) {
4274 bv->message(from_utf8(ex.what()));
4279 if (num_replaced > 0) {
4280 switch (num_replaced)
4283 bv->message(_("One match has been replaced."));
4286 bv->message(_("Two matches have been replaced."));
4289 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4295 bv->message(_("Match not found."));
4300 if (num_replaced > 0)
4301 bv->message(_("Match has been replaced."));
4303 bv->message(_("Match found."));
4305 if (cur.pos() + pos_len > cur.lastpos()) {
4306 // Prevent crash in bv->putSelectionAt()
4307 // Should never happen, maybe LASSERT() here?
4308 pos_len = cur.lastpos() - cur.pos();
4310 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4311 bv->putSelectionAt(cur, pos_len, !opt.forward);
4317 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4319 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4320 << opt.casesensitive << ' '
4321 << opt.matchword << ' '
4322 << opt.forward << ' '
4323 << opt.expandmacros << ' '
4324 << opt.ignoreformat << ' '
4325 << opt.replace_all << ' '
4326 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4327 << opt.keep_case << ' '
4328 << int(opt.scope) << ' '
4331 LYXERR(Debug::FIND, "built: " << os.str());
4337 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4339 LYXERR(Debug::FIND, "parsing");
4343 while (line != "EOSS") {
4347 if (is.eof()) // Tolerate malformed request
4351 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4352 opt.find_buf_name = from_utf8(s);
4353 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4354 is.get(); // Waste space before replace string
4357 while (line != "EOSS") {
4361 if (is.eof()) // Tolerate malformed request
4365 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4366 opt.repl_buf_name = from_utf8(s);
4367 is >> opt.keep_case;
4370 opt.scope = FindAndReplaceOptions::SearchScope(i);
4372 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4374 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4375 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4376 << opt.scope << ' ' << opt.restr);