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 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
775 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
779 if (sub.str(4) == "backslash") {
782 sregex_iterator it2 = it;
785 if (sub2.str(3) == "{")
787 else if (sub2.str(3) == "}")
791 else if (sub.str(4) == "mathcircumflex")
793 else if (withformat && (sub.str(3) == "{"))
794 replace = accents["braceleft"];
795 else if (withformat && (sub.str(3) == "}"))
796 replace = accents["braceright"];
798 replace = sub.str(3);
800 if (lastpos < (size_t) sub.position(2))
801 s += t.substr(lastpos, sub.position(2) - lastpos);
803 lastpos = sub.position(2) + sub.length(2);
807 else if (lastpos < t.length())
808 s += t.substr(lastpos, t.length() - lastpos);
812 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
813 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
814 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
815 string escape_for_regex(string s, bool withformat)
819 while (lastpos < s.size()) {
820 size_t regex_pos = s.find("\\regexp{", lastpos);
821 if (regex_pos == string::npos) {
822 regex_pos = s.size();
824 if (regex_pos > lastpos) {
825 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
827 if (lastpos == s.size())
830 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
831 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
832 lastpos = end_pos + 13;
838 /// Wrapper for lyx::regex_replace with simpler interface
839 bool regex_replace(string const & s, string & t, string const & searchstr,
840 string const & replacestr)
842 regex e(searchstr, regex_constants::ECMAScript);
844 ostream_iterator<char, char> it(oss);
845 regex_replace(it, s.begin(), s.end(), e, replacestr);
846 // tolerate t and s be references to the same variable
847 bool rv = (s != oss.str());
853 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
855 ** Verify that closed braces exactly match open braces. This avoids that, for example,
856 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
859 ** Number of open braces that must remain open at the end for the verification to succeed.
862 bool braces_match(QString const & beg,
865 bool braces_match(string const & beg,
871 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg.toStdString() << "'");
873 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg << "'");
875 int lastidx = beg.size();
876 for (int i=0; i < lastidx; ++i) {
877 // Skip escaped braces in the count
887 } else if (c == '{') {
889 } else if (c == '}') {
890 if (open_pars == 0) {
891 LYXERR(Debug::FIND, "Found unmatched closed brace");
897 if (open_pars != unmatched) {
898 LYXERR(Debug::FIND, "Found " << open_pars
899 << " instead of " << unmatched
900 << " unmatched open braces at the end of count");
903 LYXERR(Debug::FIND, "Braces match as expected");
922 vector <string> result = vector <string>();
923 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
926 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
928 int range = oldres.match_len;
929 if (range > 0) range--;
930 if (newres.match2end < oldres.match2end - oldres.match_len)
931 return MatchResult::newIsTooFar;
932 if (newres.match_len < oldres.match_len)
933 return MatchResult::newIsTooFar;
934 if ((newres.match_len == oldres.match_len) &&
935 (newres.match2end < oldres.match2end + range) &&
936 (newres.match2end > oldres.match2end - range)) {
937 return MatchResult::newIsBetter;
939 return MatchResult::newIsInvalid;
942 /** The class performing a match between a position in the document and the FindAdvOptions.
945 class MatchStringAdv {
947 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
949 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
950 ** constructor as opt.search, under the opt.* options settings.
953 ** If set, then match is searched only against beginning of text starting at cur.
954 ** If unset, then match is searched anywhere in text starting at cur.
957 ** The length of the matching text, or zero if no match was found.
959 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
968 /// first buffer on which search was started
969 lyx::Buffer * const p_first_buf;
971 FindAndReplaceOptions const & opt;
974 /// Auxiliary find method (does not account for opt.matchword)
975 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
976 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
978 /** Normalize a stringified or latexified LyX paragraph.
982 ** <li>if search is not casesensitive, then lowercase the string;
983 ** <li>remove any newline at begin or end of the string;
984 ** <li>replace any newline in the middle of the string with a simple space;
985 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
988 ** @todo Normalization should also expand macros, if the corresponding
989 ** search option was checked.
991 string normalize(docstring const & s) const;
992 // normalized string to search
993 string par_as_string;
994 // regular expression to use for searching
995 // regexp2 is same as regexp, but prefixed with a ".*?"
997 QRegularExpression regexp;
998 QRegularExpression regexp2;
1003 // leading format material as string
1004 string lead_as_string;
1005 // par_as_string after removal of lead_as_string
1006 string par_as_string_nolead;
1007 // unmatched open braces in the search string/regexp
1009 // number of (.*?) subexpressions added at end of search regexp for closing
1010 // environments, math mode, styles, etc...
1011 int close_wildcards;
1013 // Are we searching with regular expressions ?
1015 static int valid_matches;
1016 static vector <string> matches;
1017 void FillResults(MatchResult &found_mr);
1020 int MatchStringAdv::valid_matches = 0;
1021 vector <string> MatchStringAdv::matches = vector <string>(10);
1023 void MatchStringAdv::FillResults(MatchResult &found_mr)
1025 if (found_mr.match_len > 0) {
1026 valid_matches = found_mr.result.size();
1027 for (size_t i = 0; i < found_mr.result.size(); i++)
1028 matches[i] = found_mr.result[i];
1034 static docstring buffer_to_latex(Buffer & buffer)
1036 //OutputParams runparams(&buffer.params().encoding());
1037 OutputParams runparams(encodings.fromLyXName("utf8"));
1038 odocstringstream ods;
1040 runparams.nice = true;
1041 runparams.flavor = Flavor::XeTeX;
1042 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1043 // No side effect of file copying and image conversion
1044 runparams.dryrun = true;
1045 runparams.for_search = true;
1046 pit_type const endpit = buffer.paragraphs().size();
1047 for (pit_type pit = 0; pit != endpit; ++pit) {
1048 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
1049 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
1055 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1058 if (!opt.ignoreformat) {
1059 str = buffer_to_latex(buffer);
1061 // OutputParams runparams(&buffer.params().encoding());
1062 OutputParams runparams(encodings.fromLyXName("utf8"));
1063 runparams.nice = true;
1064 runparams.flavor = Flavor::XeTeX;
1065 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1066 runparams.dryrun = true;
1067 runparams.for_search = true;
1068 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1069 Paragraph const & par = buffer.paragraphs().at(pit);
1070 LYXERR(Debug::FIND, "Adding to search string: '"
1071 << par.asString(pos_type(0), par.size(),
1072 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1075 str += par.asString(pos_type(0), par.size(),
1076 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1079 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1080 string t = to_utf8(str);
1081 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
1088 /// Return separation pos between the leading material and the rest
1089 static size_t identifyLeading(string const & s)
1092 // @TODO Support \item[text]
1093 // Kornel: Added textsl, textsf, textit, texttt and noun
1094 // + allow to search for colored text too
1095 while (regex_replace(t, t, "^\\\\(("
1096 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1097 "lyxaddress|lyxrightaddress|"
1098 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1099 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1100 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1101 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1102 || regex_replace(t, t, "^\\$", "")
1103 || regex_replace(t, t, "^\\\\\\[", "")
1104 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1105 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1107 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1112 * Given a latexified string, retrieve some handled features
1113 * The features of the regex will later be compared with the features
1114 * of the searched text. If the regex features are not a
1115 * subset of the analized, then, in not format ignoring search
1116 * we can early stop the search in the relevant inset.
1118 typedef map<string, bool> Features;
1120 static Features identifyFeatures(string const & s)
1122 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1123 static regex const valid("^("
1125 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1126 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1127 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1128 "(u|uu)line|(s|x)out|uwave|"
1129 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1130 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1135 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1138 if (sub.str(1).compare("regexp") == 0) {
1142 string token = sub.str(1);
1144 if (regex_match(token, sub2, valid)) {
1152 if (sub.str(1).compare("endregexp") == 0) {
1162 * defines values features of a key "\\[a-z]+{"
1167 /* Char type with content discarded
1168 * like \hspace{1cm} */
1170 /* Char, like \backslash */
1172 /* replace starting backslash with '#' */
1174 /* \part, \section*, ... */
1176 /* title, author etc */
1178 /* \foreignlanguage{ngerman}, ... */
1181 * to discard language in content */
1184 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1186 /* fonts, colors, markups, ... */
1188 /* footnotesize, ... large, ...
1189 * Ignore all of them */
1192 /* inputencoding, ...
1193 * Discard also content, because they do not help in search */
1196 * like remove, but also all arguments */
1198 /* item, listitem */
1200 /* tex, latex, ... like isChar */
1202 /* like \lettrine[lines=5]{}{} */
1204 // like isStandard, but always remove head
1206 /* End of arguments marker for lettrine,
1207 * so that they can be ignored */
1210 KeyInfo() = default;
1211 KeyInfo(KeyType type, int parcount, bool disable)
1213 parenthesiscount(parcount),
1214 disabled(disable) {}
1215 KeyType keytype = invalid;
1217 int _tokensize = -1;
1218 int _tokenstart = -1;
1219 int _dataStart = -1;
1221 int parenthesiscount = 1;
1222 bool disabled = false;
1223 bool used = false; /* by pattern */
1228 Border(int l=0, int u=0) : low(l), upper(u) {};
1233 #define MAXOPENED 30
1235 bool isPatternString_;
1237 explicit Intervall(bool isPattern, string const & p) :
1238 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1239 hasTitle(false), langcount(0)
1247 static vector<Border> borders;
1248 int depts[MAXOPENED];
1249 int closes[MAXOPENED];
1250 int actualdeptindex;
1251 int previousNotIgnored(int) const;
1252 int nextNotIgnored(int) const;
1253 void handleOpenP(int i);
1254 void handleCloseP(int i, bool closingAllowed);
1255 void resetOpenedP(int openPos);
1256 void addIntervall(int upper);
1257 void addIntervall(int low, int upper); /* if explicit */
1258 void removeAccents();
1259 void setForDefaultLang(KeyInfo const & defLang) const;
1260 int findclosing(int start, int end, char up, char down, int repeat);
1261 void handleParentheses(int lastpos, bool closingAllowed);
1263 int langcount; // Number of disabled language specs up to current position in actual interval
1264 int isOpeningPar(int pos) const;
1266 void output(ostringstream &os, int lastpos);
1267 // string show(int lastpos);
1270 vector<Border> Intervall::borders = vector<Border>(30);
1272 int Intervall::isOpeningPar(int pos) const
1274 if ((pos < 0) || (size_t(pos) >= par.size()))
1276 if (par[pos] != '{')
1278 if (size_t(pos) + 2 >= par.size())
1280 if (par[pos+2] != '}')
1282 if (par[pos+1] == '[' || par[pos+1] == ']')
1287 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1289 // Enable the use of first token again
1290 if (ignoreidx >= 0) {
1291 int value = defLang._tokenstart + defLang._tokensize;
1297 if (borders[borderidx].low < value)
1298 borders[borderidx].low = value;
1299 if (borders[borderidx].upper < value)
1300 borders[borderidx].upper = value;
1305 static void checkDepthIndex(int val)
1307 static int maxdepthidx = MAXOPENED-2;
1308 static int lastmaxdepth = 0;
1309 if (val > lastmaxdepth) {
1310 LYXERR(Debug::INFO, "Depth reached " << val);
1313 if (val > maxdepthidx) {
1315 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1320 // Not needed, because borders are now dynamically expanded
1321 static void checkIgnoreIdx(int val)
1323 static int lastmaxignore = -1;
1324 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1325 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1326 lastmaxignore = val;
1332 * Expand the region of ignored parts of the input latex string
1333 * The region is only relevant in output()
1335 void Intervall::addIntervall(int low, int upper)
1338 if (low == upper) return;
1339 for (idx = ignoreidx+1; idx > 0; --idx) {
1340 if (low > borders[idx-1].upper) {
1344 Border br(low, upper);
1345 if (idx > ignoreidx) {
1346 if (borders.size() <= size_t(idx)) {
1347 borders.push_back(br);
1353 // checkIgnoreIdx(ignoreidx);
1357 // Expand only if one of the new bound is inside the interwall
1358 // We know here that br.low > borders[idx-1].upper
1359 if (br.upper < borders[idx].low) {
1360 // We have to insert at this pos
1361 if (size_t(ignoreidx+1) >= borders.size()) {
1362 borders.push_back(borders[ignoreidx]);
1365 borders[ignoreidx+1] = borders[ignoreidx];
1367 for (int i = ignoreidx; i > idx; --i) {
1368 borders[i] = borders[i-1];
1372 // checkIgnoreIdx(ignoreidx);
1375 // Here we know, that we are overlapping
1376 if (br.low > borders[idx].low)
1377 br.low = borders[idx].low;
1378 // check what has to be concatenated
1380 for (int i = idx; i <= ignoreidx; i++) {
1381 if (br.upper >= borders[i].low) {
1383 if (br.upper < borders[i].upper)
1384 br.upper = borders[i].upper;
1390 // count should be >= 1 here
1393 for (int i = idx + count; i <= ignoreidx; i++) {
1394 borders[i-count+1] = borders[i];
1396 ignoreidx -= count - 1;
1402 static void buildaccent(string n, string param, string values)
1406 const char delim = '|';
1407 while (getline(s, name, delim)) {
1409 for (char c : param) {
1410 string key = name + "{" + c + "}";
1411 // get the corresponding utf8-value
1412 if ((values[start] & 0xc0) != 0xc0) {
1413 // should not happen, utf8 encoding starts at least with 11xxxxxx
1414 // but value for '\dot{i}' is 'i', which is ascii
1415 if ((values[start] & 0x80) == 0) {
1417 accents[key] = values.substr(start, 1);
1418 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1423 for (int j = 1; ;j++) {
1424 if (start + j >= values.size()) {
1425 accents[key] = values.substr(start, j);
1426 start = values.size() - 1;
1429 else if ((values[start+j] & 0xc0) != 0x80) {
1430 // This is the first byte of following utf8 char
1431 accents[key] = values.substr(start, j);
1433 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1442 static string getutf8(unsigned uchar)
1445 string ret = string();
1447 if (uchar <= 0x7f) {
1448 c[maxc-1] = uchar & 0x7f;
1451 unsigned char rest = 0x40;
1452 unsigned char first = 0x80;
1454 for (int i = start; i >=0; --i) {
1456 c[i] = first + uchar;
1459 c[i] = 0x80 | (uchar & 0x3f);
1466 for (int i = 0; i < maxc; i++) {
1467 if (c[i] == 0) continue;
1473 static void buildAccentsMap()
1475 accents["imath"] = "ı";
1477 accents["jmath"] = "ȷ";
1478 accents["cdot"] = "·";
1479 accents["textasciicircum"] = "^";
1480 accents["mathcircumflex"] = "^";
1481 accents["sim"] = "~";
1482 accents["guillemotright"] = "»";
1483 accents["guillemotleft"] = "«";
1484 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1485 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1486 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1487 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1488 accents["negmedspace"] = getutf8(0xf0005);
1489 accents["thickspace"] = getutf8(0xf0006);
1490 accents["negthickspace"] = getutf8(0xf0007);
1491 accents["lyx"] = getutf8(0xf0010); // Used logos
1492 accents["LyX"] = getutf8(0xf0010);
1493 accents["tex"] = getutf8(0xf0011);
1494 accents["TeX"] = getutf8(0xf0011);
1495 accents["latex"] = getutf8(0xf0012);
1496 accents["LaTeX"] = getutf8(0xf0012);
1497 accents["latexe"] = getutf8(0xf0013);
1498 accents["LaTeXe"] = getutf8(0xf0013);
1499 accents["lyxarrow"] = getutf8(0xf0020);
1500 accents["braceleft"] = getutf8(0xf0030);
1501 accents["braceright"] = getutf8(0xf0031);
1502 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1503 accents["backslash LyX"] = getutf8(0xf0010);
1504 accents["backslash tex"] = getutf8(0xf0011);
1505 accents["backslash TeX"] = getutf8(0xf0011);
1506 accents["backslash latex"] = getutf8(0xf0012);
1507 accents["backslash LaTeX"] = getutf8(0xf0012);
1508 accents["backslash latexe"] = getutf8(0xf0013);
1509 accents["backslash LaTeXe"] = getutf8(0xf0013);
1510 accents["backslash lyxarrow"] = getutf8(0xf0020);
1511 accents["ddot{\\imath}"] = "ï";
1512 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1513 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1514 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1515 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1516 accents["acute{\\imath}"] = "í";
1517 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1518 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1519 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1520 buildaccent("mathring|r", "aAuUwy",
1522 accents["check{\\imath}"] = "ǐ";
1523 accents["check{\\jmath}"] = "ǰ";
1524 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1525 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1526 accents["hat{\\imath}"] = "î";
1527 accents["hat{\\jmath}"] = "ĵ";
1528 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1529 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1530 accents["bar{\\imath}"] = "ī";
1531 buildaccent("bar|=", "aAeEiIoOuUyY",
1532 "āĀēĒīĪōŌūŪȳȲ"); // macron
1533 accents["tilde{\\imath}"] = "ĩ";
1534 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1535 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1536 accents["breve{\\imath}"] = "ĭ";
1537 buildaccent("breve|u", "aAeEgGiIoOuU",
1538 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1539 accents["grave{\\imath}"] = "ì";
1540 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1541 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1542 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1543 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1544 buildaccent("ogonek|k", "AaEeIiUuOo",
1545 "ĄąĘęĮįŲųǪǫ"); // ogonek
1546 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1547 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1548 buildaccent("subring|textsubring", "Aa",
1550 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1551 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1552 buildaccent("subtilde|textsubtilde", "EeIiUu",
1553 "ḚḛḬḭṴṵ"); // subtilde
1554 accents["dgrave{\\imath}"] = "ȉ";
1555 accents["textdoublegrave{\\i}"] = "ȉ";
1556 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1557 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1558 accents["rcap{\\imath}"] = "ȉ";
1559 accents["textroundcap{\\i}"] = "ȉ";
1560 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1561 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1562 buildaccent("slashed", "oO",
1567 * Created accents in math or regexp environment
1568 * are macros, but we need the utf8 equivalent
1570 void Intervall::removeAccents()
1572 if (accents.empty())
1574 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1575 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1576 "|((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]))");
1578 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1580 string key = sub.str(1);
1581 if (accents.find(key) != accents.end()) {
1582 string val = accents[key];
1583 size_t pos = sub.position(size_t(0));
1584 for (size_t i = 0; i < val.size(); i++) {
1585 par[pos+i] = val[i];
1587 // Remove possibly following space too
1588 if (par[pos+sub.str(0).size()] == ' ')
1589 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1591 addIntervall(pos+val.size(), pos + sub.str(0).size());
1592 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1593 // remove traces of any remaining chars
1598 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1603 void Intervall::handleOpenP(int i)
1606 depts[actualdeptindex] = i+1;
1607 closes[actualdeptindex] = -1;
1608 checkDepthIndex(actualdeptindex);
1611 void Intervall::handleCloseP(int i, bool closingAllowed)
1613 if (actualdeptindex <= 0) {
1614 if (! closingAllowed)
1615 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1616 // if we are at the very end
1617 addIntervall(i, i+1);
1620 closes[actualdeptindex] = i+1;
1625 void Intervall::resetOpenedP(int openPos)
1627 // Used as initializer for foreignlanguage entry
1628 actualdeptindex = 1;
1629 depts[1] = openPos+1;
1633 int Intervall::previousNotIgnored(int start) const
1635 int idx = 0; /* int intervalls */
1636 for (idx = ignoreidx; idx >= 0; --idx) {
1637 if (start > borders[idx].upper)
1639 if (start >= borders[idx].low)
1640 start = borders[idx].low-1;
1645 int Intervall::nextNotIgnored(int start) const
1647 int idx = 0; /* int intervalls */
1648 for (idx = 0; idx <= ignoreidx; idx++) {
1649 if (start < borders[idx].low)
1651 if (start < borders[idx].upper)
1652 start = borders[idx].upper;
1657 typedef map<string, KeyInfo> KeysMap;
1658 typedef vector< KeyInfo> Entries;
1659 static KeysMap keys = map<string, KeyInfo>();
1665 Intervall interval_;
1666 void buildKeys(bool);
1667 void buildEntries(bool);
1668 void makeKey(const string &, KeyInfo, bool isPatternString);
1669 void processRegion(int start, int region_end); /* remove {} parts */
1670 void removeHead(KeyInfo const &, int count=0);
1673 LatexInfo(string const & par, bool isPatternString)
1674 : entidx_(-1), interval_(isPatternString, par)
1676 buildKeys(isPatternString);
1677 entries_ = vector<KeyInfo>();
1678 buildEntries(isPatternString);
1682 if (entries_.empty()) {
1685 if (entries_[0].keytype == KeyInfo::isTitle) {
1686 interval_.hasTitle = true;
1687 if (! entries_[0].disabled) {
1688 interval_.titleValue = entries_[0].head;
1691 interval_.titleValue = "";
1693 removeHead(entries_[0]);
1694 if (entries_.size() > 1)
1703 if (int(entries_.size()) > entidx_) {
1710 bool setNextKey(int idx) {
1711 if ((idx == entidx_) && (entidx_ >= 0)) {
1718 int find(int start, KeyInfo::KeyType keytype) const {
1722 while (tmpIdx < int(entries_.size())) {
1723 if (entries_[tmpIdx].keytype == keytype)
1729 int process(ostringstream & os, KeyInfo const & actual);
1730 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1731 // string show(int lastpos) { return interval.show(lastpos);};
1732 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1733 KeyInfo &getKeyInfo(int keyinfo) {
1734 static KeyInfo invalidInfo = KeyInfo();
1735 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1738 return entries_[keyinfo];
1740 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1741 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1745 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1749 for (int i = start; i < end; i += 1 + skip) {
1753 if (c == '\\') skip = 1;
1757 else if (c == down) {
1760 if ((repeat <= 0) || (par[i+1] != up))
1778 vector<MathEntry> entries_;
1783 void insert(string const & wait, size_t start, size_t end) {
1784 MathEntry m = MathEntry();
1786 m.mathStart = start;
1788 m.mathSize = end - start;
1789 entries_.push_back(m);
1791 bool empty() const { return entries_.empty(); };
1792 size_t getEndPos() const {
1793 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1796 return entries_[actualIdx_].mathEnd;
1798 size_t getStartPos() const {
1799 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1800 return 100000; /* definitely enough? */
1802 return entries_[actualIdx_].mathStart;
1804 size_t getFirstPos() {
1806 return getStartPos();
1808 size_t getSize() const {
1809 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1812 return entries_[actualIdx_].mathSize;
1814 void incrEntry() { actualIdx_++; };
1817 void LatexInfo::buildEntries(bool isPatternString)
1819 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1820 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1821 static bool disableLanguageOverride = false;
1822 smatch sub, submath;
1823 bool evaluatingRegexp = false;
1825 bool evaluatingMath = false;
1826 bool evaluatingCode = false;
1828 bool evaluatingOptional = false;
1829 size_t optionalEnd = 0;
1832 bool math_end_waiting = false;
1833 size_t math_pos = 10000;
1835 static vector<string> usedText = vector<string>();
1837 interval_.removeAccents();
1839 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1841 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1842 // prefixed by odd count of '\\'
1845 if (math_end_waiting) {
1846 size_t pos = submath.position(size_t(2));
1847 if ((math_end == "$") &&
1848 (submath.str(2) == "$")) {
1849 mi.insert("$", math_pos, pos + 1);
1850 math_end_waiting = false;
1852 else if ((math_end == "\\]") &&
1853 (submath.str(2) == "\\]")) {
1854 mi.insert("\\]", math_pos, pos + 2);
1855 math_end_waiting = false;
1857 else if ((submath.str(3).compare("end") == 0) &&
1858 (submath.str(4).compare(math_end) == 0)) {
1859 mi.insert(math_end, math_pos, pos + submath.str(2).length());
1860 math_end_waiting = false;
1866 if (submath.str(3).compare("begin") == 0) {
1867 math_end_waiting = true;
1868 math_end = submath.str(4);
1869 math_pos = submath.position(size_t(2));
1871 else if (submath.str(2).compare("\\[") == 0) {
1872 math_end_waiting = true;
1874 math_pos = submath.position(size_t(2));
1876 else if (submath.str(2) == "$") {
1877 size_t pos = submath.position(size_t(2));
1878 math_end_waiting = true;
1884 // Ignore language if there is math somewhere in pattern-string
1885 if (isPatternString) {
1886 for (auto s: usedText) {
1887 // Remove entries created in previous search runs
1890 usedText = vector<string>();
1893 keys["foreignlanguage"].disabled = true;
1894 disableLanguageOverride = true;
1897 disableLanguageOverride = false;
1900 if (disableLanguageOverride) {
1901 keys["foreignlanguage"].disabled = true;
1904 math_pos = mi.getFirstPos();
1905 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1907 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1908 // prefixed by odd count of '\\'
1911 string key = sub.str(5);
1913 if (sub.str(2)[0] == '\\')
1914 key = sub.str(2)[1];
1919 if (keys.find(key) != keys.end()) {
1920 if (keys[key].keytype == KeyInfo::headRemove) {
1921 KeyInfo found1 = keys[key];
1922 found1.disabled = true;
1923 found1.head = "\\" + key + "{";
1924 found1._tokenstart = sub.position(size_t(2));
1925 found1._tokensize = found1.head.length();
1926 found1._dataStart = found1._tokenstart + found1.head.length();
1927 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1928 found1._dataEnd = endpos;
1933 if (evaluatingRegexp) {
1934 if (sub.str(3).compare("endregexp") == 0) {
1935 evaluatingRegexp = false;
1936 // found._tokenstart already set
1937 found._dataEnd = sub.position(size_t(2)) + 13;
1938 found._dataStart = found._dataEnd;
1939 found._tokensize = found._dataEnd - found._tokenstart;
1940 found.parenthesiscount = 0;
1941 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1948 if (evaluatingMath) {
1949 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1951 evaluatingMath = false;
1953 math_pos = mi.getStartPos();
1955 if (keys.find(key) == keys.end()) {
1956 found = KeyInfo(KeyInfo::isStandard, 0, true);
1957 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1958 found = KeyInfo(KeyInfo::isText, 0, false);
1959 if (isPatternString) {
1960 found.keytype = KeyInfo::isChar;
1961 found.disabled = false;
1965 usedText.push_back(key);
1969 if (key.compare("regexp") == 0) {
1970 evaluatingRegexp = true;
1971 found._tokenstart = sub.position(size_t(2));
1972 found._tokensize = 0;
1976 // Handle the other params of key
1977 if (found.keytype == KeyInfo::isIgnored)
1979 else if (found.keytype == KeyInfo::isMath) {
1980 if (size_t(sub.position(size_t(2))) == math_pos) {
1982 found._tokenstart = sub.position(size_t(2));
1983 found._tokensize = mi.getSize();
1984 found._dataEnd = found._tokenstart + found._tokensize;
1985 found._dataStart = found._dataEnd;
1986 found.parenthesiscount = 0;
1987 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1988 evaluatingMath = true;
1991 // begin|end of unknown env, discard
1992 // First handle tables
1993 // longtable|tabular
1994 bool discardComment;
1996 found.keytype = KeyInfo::doRemove;
1997 if ((sub.str(7).compare("longtable") == 0) ||
1998 (sub.str(7).compare("tabular") == 0)) {
1999 discardComment = true; /* '%' */
2002 discardComment = false;
2003 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2005 string token = sub.str(7);
2006 if (regex_match(token, sub2, removeArgs)) {
2007 found.keytype = KeyInfo::removeWithArg;
2010 // discard spaces before pos(2)
2011 int pos = sub.position(size_t(2));
2013 for (count = 0; pos - count > 0; count++) {
2014 char c = interval_.par[pos-count-1];
2015 if (discardComment) {
2016 if ((c != ' ') && (c != '%'))
2022 found._tokenstart = pos - count;
2023 if (sub.str(3).compare(0, 5, "begin") == 0) {
2024 size_t pos1 = pos + sub.str(2).length();
2025 if (sub.str(7).compare("cjk") == 0) {
2026 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2027 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2029 found.keytype = KeyInfo::isMain;
2030 found._dataStart = pos1;
2031 found._dataEnd = interval_.par.length();
2032 found.disabled = keys["foreignlanguage"].disabled;
2033 found.used = keys["foreignlanguage"].used;
2034 found._tokensize = pos1 - found._tokenstart;
2035 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2038 // Swallow possible optional params
2039 while (interval_.par[pos1] == '[') {
2040 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2042 // Swallow also the eventual parameter
2043 if (interval_.par[pos1] == '{') {
2044 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2047 found._dataEnd = pos1;
2049 found._dataStart = found._dataEnd;
2050 found._tokensize = count + found._dataEnd - pos;
2051 found.parenthesiscount = 0;
2052 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2053 found.disabled = true;
2057 // Handle "\end{...}"
2058 found._dataStart = pos + sub.str(2).length();
2059 found._dataEnd = found._dataStart;
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 else if (found.keytype != KeyInfo::isRegex) {
2068 found._tokenstart = sub.position(size_t(2));
2069 if (found.parenthesiscount == 0) {
2070 // Probably to be discarded
2071 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2072 char following = interval_.par[following_pos];
2073 if (following == ' ')
2074 found.head = "\\" + sub.str(5) + " ";
2075 else if (following == '=') {
2076 // like \uldepth=1000pt
2077 found.head = sub.str(2);
2080 found.head = "\\" + key;
2081 found._tokensize = found.head.length();
2082 found._dataEnd = found._tokenstart + found._tokensize;
2083 found._dataStart = found._dataEnd;
2086 int params = found._tokenstart + key.length() + 1;
2087 if (evaluatingOptional) {
2088 if (size_t(found._tokenstart) > optionalEnd) {
2089 evaluatingOptional = false;
2092 found.disabled = true;
2095 int optend = params;
2096 while (interval_.par[optend] == '[') {
2097 // discard optional parameters
2098 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2100 if (optend > params) {
2101 key += interval_.par.substr(params, optend-params);
2102 evaluatingOptional = true;
2103 optionalEnd = optend;
2104 if (found.keytype == KeyInfo::isSectioning) {
2105 // Remove optional values (but still keep in header)
2106 interval_.addIntervall(params, optend);
2109 string token = sub.str(7);
2111 if (interval_.par[optend] != '{') {
2113 found.parenthesiscount = 0;
2114 found.head = "\\" + key;
2117 closings = found.parenthesiscount;
2118 if (found.parenthesiscount == 1) {
2119 found.head = "\\" + key + "{";
2121 else if (found.parenthesiscount > 1) {
2123 found.head = sub.str(2) + "{";
2124 closings = found.parenthesiscount - 1;
2127 found.head = "\\" + key + "{";
2130 found._tokensize = found.head.length();
2131 found._dataStart = found._tokenstart + found.head.length();
2132 if (found.keytype == KeyInfo::doRemove) {
2134 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2135 if (endpar >= interval_.par.length())
2136 found._dataStart = interval_.par.length();
2138 found._dataStart = endpar;
2139 found._tokensize = found._dataStart - found._tokenstart;
2142 found._dataStart = found._tokenstart + found._tokensize;
2146 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2147 found._dataStart += 15;
2151 endpos = found._dataStart - 1;
2153 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2154 if (found.keytype == KeyInfo::isList) {
2155 // Check if it really is list env
2156 static regex const listre("^([a-z]+)$");
2158 if (!regex_match(token, sub2, listre)) {
2159 // Change the key of this entry. It is not in a list/item environment
2160 found.keytype = KeyInfo::endArguments;
2163 if (found.keytype == KeyInfo::noMain) {
2164 evaluatingCode = true;
2166 codeStart = found._dataStart;
2168 else if (evaluatingCode) {
2169 if (size_t(found._dataStart) > codeEnd)
2170 evaluatingCode = false;
2171 else if (found.keytype == KeyInfo::isMain) {
2172 // Disable this key, treate it as standard
2173 found.keytype = KeyInfo::isStandard;
2174 found.disabled = true;
2175 if ((codeEnd +1 >= interval_.par.length()) &&
2176 (found._tokenstart == codeStart)) {
2177 // trickery, because the code inset starts
2178 // with \selectlanguage ...
2180 if (entries_.size() > 1) {
2181 entries_[entries_.size()-1]._dataEnd = codeEnd;
2186 if ((endpos == interval_.par.length()) &&
2187 (found.keytype == KeyInfo::doRemove)) {
2188 // Missing closing => error in latex-input?
2189 // therefore do not delete remaining data
2190 found._dataStart -= 1;
2191 found._dataEnd = found._dataStart;
2194 found._dataEnd = endpos;
2196 if (isPatternString) {
2197 keys[key].used = true;
2200 entries_.push_back(found);
2204 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2206 stringstream s(keysstring);
2208 const char delim = '|';
2209 while (getline(s, key, delim)) {
2210 KeyInfo keyII(keyI);
2211 if (isPatternString) {
2214 else if ( !keys[key].used)
2215 keyII.disabled = true;
2220 void LatexInfo::buildKeys(bool isPatternString)
2223 static bool keysBuilt = false;
2224 if (keysBuilt && !isPatternString) return;
2226 // Keys to ignore in any case
2227 makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2228 // Known standard keys with 1 parameter.
2229 // Split is done, if not at start of region
2230 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2231 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2232 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2233 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2234 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2235 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2237 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2238 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2239 makeKey("section*|subsection*|subsubsection*|paragraph*",
2240 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2241 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2242 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2244 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2246 // Split is done, if not at start of region
2247 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2248 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2250 // Split is done always.
2251 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2255 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2256 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2257 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2258 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2260 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2261 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2262 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2263 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2265 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2266 // Custom space/skip, remove the content (== length value)
2267 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2268 // Found in fr/UserGuide.lyx
2269 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2271 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2272 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2273 // Known macros to remove (including their parameter)
2275 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2276 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2277 // handle like standard keys with 1 parameter.
2278 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2280 // Ignore deleted text
2281 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2282 // but preserve added text
2283 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2285 // Macros to remove, but let the parameter survive
2287 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2289 // Remove language spec from content of these insets
2290 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2292 // Same effect as previous, parameter will survive (because there is no one anyway)
2294 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2295 // Remove table decorations
2296 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2297 // Discard shape-header.
2298 // For footnote or shortcut too, because of lang settings
2299 // and wrong handling if used 'KeyInfo::noMain'
2300 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2301 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2302 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2303 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2304 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2305 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2306 // like ('tiny{}' or '\tiny ' ... )
2307 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2309 // Survives, like known character
2310 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2311 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2312 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2314 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2315 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2316 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2318 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2319 // Remove RTL/LTR marker
2320 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2321 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2322 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2323 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2324 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2325 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2326 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2327 if (isPatternString) {
2328 // Allow the first searched string to rebuild the keys too
2332 // no need to rebuild again
2338 * Keep the list of actual opened parentheses actual
2339 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2341 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2344 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2348 if (c == '\\') skip = 1;
2349 else if (c == '{') {
2352 else if (c == '}') {
2353 handleCloseP(i, closingAllowed);
2359 string Intervall::show(int lastpos)
2361 int idx = 0; /* int intervalls */
2364 for (idx = 0; idx <= ignoreidx; idx++) {
2365 while (i < lastpos) {
2367 if (i <= borders[idx].low) {
2368 if (borders[idx].low > lastpos)
2369 printsize = lastpos - i;
2371 printsize = borders[idx].low - i;
2372 s += par.substr(i, printsize);
2374 if (i >= borders[idx].low)
2375 i = borders[idx].upper;
2378 i = borders[idx].upper;
2384 s += par.substr(i, lastpos-i);
2390 void Intervall::output(ostringstream &os, int lastpos)
2392 // get number of chars to output
2393 int idx = 0; /* int intervalls */
2396 string startTitle = titleValue;
2397 for (idx = 0; idx <= ignoreidx; idx++) {
2399 if (i <= borders[idx].low) {
2401 if (borders[idx].low > lastpos)
2402 printsize = lastpos - i;
2404 printsize = borders[idx].low - i;
2405 if (printsize > 0) {
2406 os << startTitle << par.substr(i, printsize);
2408 printed += printsize;
2411 handleParentheses(i, false);
2412 if (i >= borders[idx].low)
2413 i = borders[idx].upper;
2416 i = borders[idx].upper;
2423 os << startTitle << par.substr(i, lastpos-i);
2424 printed += lastpos-i;
2426 handleParentheses(lastpos, false);
2428 if (keys["foreignlanguage"].disabled)
2429 startindex = actualdeptindex-langcount;
2431 startindex = actualdeptindex;
2432 for (int i = startindex; i > 0; --i) {
2435 if (hasTitle && (printed > 0))
2437 if (! isPatternString_)
2439 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2442 void LatexInfo::processRegion(int start, int region_end)
2444 while (start < region_end) { /* Let {[} and {]} survive */
2445 int cnt = interval_.isOpeningPar(start);
2447 // Closing is allowed past the region
2448 int closing = interval_.findclosing(start+1, interval_.par.length());
2449 interval_.addIntervall(start, start+1);
2450 interval_.addIntervall(closing, closing+1);
2454 start = interval_.nextNotIgnored(start+1);
2458 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2460 if (actual.parenthesiscount == 0) {
2461 // "{\tiny{} ...}" ==> "{{} ...}"
2462 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2465 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2466 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2467 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2471 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2474 switch (actual.keytype)
2476 case KeyInfo::isTitle: {
2478 nextKeyIdx = getNextKey();
2481 case KeyInfo::cleanToStart: {
2482 actual._dataEnd = actual._dataStart;
2483 nextKeyIdx = getNextKey();
2484 // Search for end of arguments
2485 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2487 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2488 entries_[i].disabled = true;
2490 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2492 while (interval_.par[actual._dataEnd] == ' ')
2494 interval_.addIntervall(0, actual._dataEnd+1);
2495 interval_.actualdeptindex = 0;
2496 interval_.depts[0] = actual._dataEnd+1;
2497 interval_.closes[0] = -1;
2500 case KeyInfo::isText:
2501 interval_.par[actual._tokenstart] = '#';
2502 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2503 nextKeyIdx = getNextKey();
2505 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2506 if (actual.disabled)
2507 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2509 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2512 case KeyInfo::isChar: {
2513 nextKeyIdx = getNextKey();
2516 case KeyInfo::isSize: {
2517 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2518 if (actual.parenthesiscount == 0)
2519 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2521 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2523 nextKeyIdx = getNextKey();
2525 // Here _dataStart points to '{', so correct it
2526 actual._dataStart += 1;
2527 actual._tokensize += 1;
2528 actual.parenthesiscount = 1;
2529 if (interval_.par[actual._dataStart] == '}') {
2530 // Determine the end if used like '{\tiny{}...}'
2531 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2532 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2535 // Determine the end if used like '\tiny{...}'
2536 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2538 // Split on this key if not at start
2539 int start = interval_.nextNotIgnored(previousStart);
2540 if (start < actual._tokenstart) {
2541 interval_.output(os, actual._tokenstart);
2542 interval_.addIntervall(start, actual._tokenstart);
2544 // discard entry if at end of actual
2545 nextKeyIdx = process(os, actual);
2549 case KeyInfo::endArguments: {
2550 // Remove trailing '{}' too
2551 actual._dataStart += 1;
2552 actual._dataEnd += 1;
2553 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2554 nextKeyIdx = getNextKey();
2557 case KeyInfo::noMain:
2559 case KeyInfo::isStandard: {
2560 if (actual.disabled) {
2562 processRegion(actual._dataStart, actual._dataStart+1);
2563 nextKeyIdx = getNextKey();
2565 // Split on this key if not at datastart of calling entry
2566 int start = interval_.nextNotIgnored(previousStart);
2567 if (start < actual._tokenstart) {
2568 interval_.output(os, actual._tokenstart);
2569 interval_.addIntervall(start, actual._tokenstart);
2571 // discard entry if at end of actual
2572 nextKeyIdx = process(os, actual);
2576 case KeyInfo::removeWithArg: {
2577 nextKeyIdx = getNextKey();
2578 // Search for end of arguments
2579 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2581 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2582 entries_[i].disabled = true;
2584 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2586 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2589 case KeyInfo::doRemove: {
2590 // Remove the key with all parameters and following spaces
2593 if (interval_.par[actual._dataEnd-1] == ' ')
2594 start = actual._dataEnd;
2596 start = actual._dataEnd+1;
2597 for (pos = start; pos < interval_.par.length(); pos++) {
2598 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2601 // Remove also enclosing parentheses [] and {}
2604 while (actual._tokenstart > numpars) {
2605 if (pos+numpars >= interval_.par.size())
2607 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2609 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2615 if (interval_.par[pos+numpars] == ' ')
2619 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2620 nextKeyIdx = getNextKey();
2623 case KeyInfo::isList: {
2624 // Discard space before _tokenstart
2626 for (count = 0; count < actual._tokenstart; count++) {
2627 if (interval_.par[actual._tokenstart-count-1] != ' ')
2630 nextKeyIdx = getNextKey();
2631 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2633 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2635 // How else can we catch this one?
2636 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2637 entries_[i].disabled = true;
2639 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2641 else if (nextKeyIdx > 0) {
2642 // Ignore any lang entries inside data region
2643 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2644 if (entries_[i].keytype == KeyInfo::isMain)
2645 entries_[i].disabled = true;
2648 if (actual.disabled) {
2649 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2652 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2654 if (interval_.par[actual._dataEnd+1] == '[') {
2655 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2656 if ((interval_.par[actual._dataEnd+2] == '{') &&
2657 (interval_.par[posdown-1] == '}')) {
2658 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2659 interval_.addIntervall(posdown-1, posdown+1);
2662 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2663 interval_.addIntervall(posdown, posdown+1);
2665 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2666 if (blk > posdown) {
2667 // Discard at most 1 space after empty item
2669 for (count = 0; count < 1; count++) {
2670 if (interval_.par[blk+count] != ' ')
2674 interval_.addIntervall(blk, blk+count);
2679 case KeyInfo::isSectioning: {
2680 // Discard spaces before _tokenstart
2682 int val = actual._tokenstart;
2683 for (count = 0; count < actual._tokenstart;) {
2684 val = interval_.previousNotIgnored(val-1);
2685 if (val < 0 || interval_.par[val] != ' ')
2688 count = actual._tokenstart - val;
2691 if (actual.disabled) {
2692 removeHead(actual, count);
2693 nextKeyIdx = getNextKey();
2695 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2696 nextKeyIdx = process(os, actual);
2700 case KeyInfo::isMath: {
2701 // Same as regex, use the content unchanged
2702 nextKeyIdx = getNextKey();
2705 case KeyInfo::isRegex: {
2706 // DO NOT SPLIT ON REGEX
2708 nextKeyIdx = getNextKey();
2711 case KeyInfo::isIgnored: {
2712 // Treat like a character for now
2713 nextKeyIdx = getNextKey();
2716 case KeyInfo::isMain: {
2717 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2718 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2719 if (actual._tokenstart > 0) {
2720 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2721 if ((prev >= 0) && interval_.par[prev] == '%')
2722 interval_.addIntervall(prev, prev+1);
2724 if (actual.disabled) {
2726 interval_.langcount++;
2727 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2728 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2729 // Discard also the space before math-equation
2730 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2732 nextKeyIdx = getNextKey();
2733 // interval.resetOpenedP(actual._dataStart-1);
2736 if (actual._tokenstart < 26) {
2737 // for the first (and maybe dummy) language
2738 interval_.setForDefaultLang(actual);
2740 interval_.resetOpenedP(actual._dataStart-1);
2744 case KeyInfo::invalid:
2745 case KeyInfo::headRemove:
2746 // These two cases cannot happen, already handled
2749 // LYXERR(Debug::INFO, "Unhandled keytype");
2750 nextKeyIdx = getNextKey();
2757 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2759 int end = interval_.nextNotIgnored(actual._dataEnd);
2760 int oldStart = actual._dataStart;
2761 int nextKeyIdx = getNextKey();
2763 if ((nextKeyIdx < 0) ||
2764 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2765 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2766 if (oldStart <= end) {
2767 processRegion(oldStart, end);
2772 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2774 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2775 (void) dispatch(os, actual._dataStart, nextKey);
2776 end = nextKey._tokenstart;
2779 processRegion(oldStart, nextKey._tokenstart);
2780 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2782 oldStart = nextKey._dataEnd+1;
2784 // now nextKey is either invalid or is outside of actual._dataEnd
2785 // output the remaining and discard myself
2786 if (oldStart <= end) {
2787 processRegion(oldStart, end);
2789 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2791 // This is the normal case.
2792 // But if using the firstlanguage, the closing may be missing
2794 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2796 if (actual._dataEnd < end)
2797 output_end = interval_.nextNotIgnored(actual._dataEnd);
2798 else if (interval_.par.size() > (size_t) end)
2799 output_end = interval_.nextNotIgnored(end);
2801 output_end = interval_.par.size();
2802 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2803 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2805 // Remove possible empty data
2806 int dstart = interval_.nextNotIgnored(actual._dataStart);
2807 while (interval_.isOpeningPar(dstart) == 1) {
2808 interval_.addIntervall(dstart, dstart+1);
2809 int dend = interval_.findclosing(dstart+1, output_end);
2810 interval_.addIntervall(dend, dend+1);
2811 dstart = interval_.nextNotIgnored(dstart+1);
2813 if (dstart < output_end)
2814 interval_.output(os, output_end);
2815 interval_.addIntervall(actual._tokenstart, end);
2819 string splitOnKnownMacros(string par, bool isPatternString)
2822 LatexInfo li(par, isPatternString);
2823 // LYXERR(Debug::INFO, "Berfore split: " << par);
2824 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2826 DummyKey._tokensize = 0;
2827 DummyKey._dataStart = 0;
2828 DummyKey._dataEnd = par.length();
2829 DummyKey.disabled = true;
2830 int firstkeyIdx = li.getFirstKey();
2832 if (firstkeyIdx >= 0) {
2833 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2834 DummyKey._tokenstart = firstKey._tokenstart;
2836 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2837 // Use dummy firstKey
2838 firstKey = DummyKey;
2839 (void) li.setNextKey(firstkeyIdx);
2842 if (par.substr(firstKey._dataStart, 2) == "% ")
2843 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2845 nextkeyIdx = li.process(os, firstKey);
2846 while (nextkeyIdx >= 0) {
2847 // Check for a possible gap between the last
2848 // entry and this one
2849 int datastart = li.nextNotIgnored(firstKey._dataStart);
2850 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2851 if ((nextKey._tokenstart > datastart)) {
2853 firstKey._dataStart = datastart;
2854 firstKey._dataEnd = par.length();
2855 (void) li.setNextKey(nextkeyIdx);
2856 // Fake the last opened parenthesis
2857 li.setForDefaultLang(firstKey);
2858 nextkeyIdx = li.process(os, firstKey);
2861 if (nextKey.keytype != KeyInfo::isMain) {
2862 firstKey._dataStart = datastart;
2863 firstKey._dataEnd = nextKey._dataEnd+1;
2864 (void) li.setNextKey(nextkeyIdx);
2865 li.setForDefaultLang(firstKey);
2866 nextkeyIdx = li.process(os, firstKey);
2869 nextkeyIdx = li.process(os, nextKey);
2873 // Handle the remaining
2874 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2875 firstKey._dataEnd = par.length();
2877 if ((firstKey._dataStart < firstKey._dataEnd) &&
2878 (par[firstKey._dataStart] != '}')) {
2879 li.setForDefaultLang(firstKey);
2880 (void) li.process(os, firstKey);
2884 // return string definitelly impossible to match
2885 s = "\\foreignlanguage{ignore}{ }";
2889 s = par; /* no known macros found */
2890 // LYXERR(Debug::INFO, "After split: " << s);
2895 * Try to unify the language specs in the latexified text.
2896 * Resulting modified string is set to "", if
2897 * the searched tex does not contain all the features in the search pattern
2899 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2901 static Features regex_f;
2902 static int missed = 0;
2903 static bool regex_with_format = false;
2905 int parlen = par.length();
2907 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2910 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2911 // Happens to be there in case of description or labeling environment
2916 // Split the latex input into pieces which
2917 // can be digested by our search engine
2918 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2919 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2920 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2923 result = par.substr(0, parlen);
2924 if (isPatternString) {
2927 regex_f = identifyFeatures(result);
2928 string features = "";
2929 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2930 string a = it->first;
2931 regex_with_format = true;
2932 features += " " + a;
2933 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2935 LYXERR(Debug::FIND, "Identified Features" << features);
2938 } else if (regex_with_format) {
2939 Features info = identifyFeatures(result);
2940 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2941 string a = it->first;
2942 bool b = it->second;
2943 if (b && ! info[a]) {
2945 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2952 // LYXERR(Debug::INFO, "No regex formats");
2958 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2959 static int identifyClosing(string & t)
2961 int open_braces = 0;
2963 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2964 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2966 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2968 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2970 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2979 static int num_replaced = 0;
2980 static bool previous_single_replace = true;
2982 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2985 // Handle \w properly
2986 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2987 if (! opt.casesensitive) {
2988 popts |= QRegularExpression::CaseInsensitiveOption;
2990 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2991 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2993 if (regexp.isValid() && regexp2.isValid()) {
2994 regexIsValid = true;
2995 // Check '{', '}' pairs inside the regex
2998 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2999 char c = par_as_string[i];
3006 else if (c == '}') {
3013 if (balanced != 0) {
3014 regexIsValid = false;
3015 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3019 regexIsValid = false;
3020 if (!regexp.isValid())
3021 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3023 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3026 if (opt.casesensitive) {
3027 regexp = regex(regexp_str);
3028 regexp2 = regex(regexp2_str);
3031 regexp = regex(regexp_str, std::regex_constants::icase);
3032 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3037 static void modifyRegexForMatchWord(string &t)
3040 regex wordre("(\\\\)*((\\.|\\\\b))");
3043 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3045 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3048 else if (sub.str(2) == "\\\\b")
3050 if (lastpos < (size_t) sub.position(2))
3051 s += t.substr(lastpos, sub.position(2) - lastpos);
3053 lastpos = sub.position(2) + sub.length(2);
3056 s = "\\b" + t + "\\b";
3060 else if (lastpos < t.length())
3061 s += t.substr(lastpos, t.length() - lastpos);
3062 t = "\\b" + s + "\\b";
3065 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3066 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3068 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3069 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3070 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3071 if (opt.replace_all && previous_single_replace) {
3072 previous_single_replace = false;
3075 else if (!opt.replace_all) {
3076 num_replaced = 0; // count number of replaced strings
3077 previous_single_replace = true;
3079 // When using regexp, braces are hacked already by escape_for_regex()
3080 par_as_string = normalize(ds);
3082 close_wildcards = 0;
3084 size_t lead_size = 0;
3085 // correct the language settings
3086 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
3087 opt.matchstart = false;
3089 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3090 if (opt.ignoreformat) {
3094 lead_size = identifyLeading(par_as_string);
3096 lead_as_string = par_as_string.substr(0, lead_size);
3097 string lead_as_regex_string = string2regex(lead_as_string);
3098 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3099 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3100 /* Handle whole words too in this case
3102 if (opt.matchword) {
3103 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3104 opt.matchword = false;
3106 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3107 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3108 CreateRegexp(opt, regexp_str, regexp2_str);
3110 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3111 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3115 if (!opt.ignoreformat) {
3116 lead_size = identifyLeading(par_as_string);
3117 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3118 lead_as_string = par_as_string.substr(0, lead_size);
3119 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3122 // Here we are using regexp
3123 LASSERT(use_regexp, /**/);
3125 string lead_as_regexp;
3126 if (lead_size > 0) {
3127 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3128 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3129 par_as_string = par_as_string_nolead;
3130 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3131 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3133 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3134 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3135 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3136 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3137 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3139 size_t lng = par_as_string.size();
3140 if (!opt.ignoreformat) {
3141 // Remove extra '\}' at end if not part of \{\.\}
3143 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3145 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3154 if (lng < par_as_string.size())
3155 par_as_string = par_as_string.substr(0,lng);
3157 if ((lng > 0) && (par_as_string[0] == '^')) {
3158 par_as_string = par_as_string.substr(1);
3160 opt.matchstart = true;
3162 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3163 LYXERR(Debug::FIND, "Open braces: " << open_braces);
3164 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3166 // If entered regexp must match at begin of searched string buffer
3167 // Kornel: Added parentheses to use $1 for size of the leading string
3171 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3172 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3173 // so the convert has no effect in that case
3174 for (int i = 7; i > 0; --i) {
3175 string orig = "\\\\" + std::to_string(i);
3176 string dest = "\\" + std::to_string(i+2);
3177 while (regex_replace(par_as_string, par_as_string, orig, dest));
3179 if (opt.matchword) {
3180 modifyRegexForMatchWord(par_as_string);
3181 opt.matchword = false;
3183 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3184 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3186 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3187 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3188 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3193 // Count number of characters in string
3197 // \\[a-zA-Z]+ ==> 1
3199 static int computeSize(QStringRef s, int len)
3200 #define isLyxAlpha(arg) arg.isLetter()
3202 static int computeSize(string s, int len)
3203 #define isLyxAlpha(arg) isalpha(arg)
3210 for (int i = 0; i < len; i += skip, count++) {
3211 if (s.at(i) == '\\') {
3213 if (i + 1 < len && isLyxAlpha(s.at(i+1))) {
3214 for (int j = 2; i+j < len; j++) {
3215 if (! isLyxAlpha(s.at(i+j))) {
3216 if (s.at(i+j) == ' ')
3218 else if (s.at(i+j) == '{') {
3219 if (i+j+1 < len && s.at(i+j+1) == '}')
3221 else if (i + j + 1 >= len)
3230 else if (s.at(i) == '{') {
3231 if (i + 1 < len && s.at(i+1) == '}')
3236 else if (s.at(i) == '-') {
3237 if (i+1 < len && s.at(i+1) == '-') {
3238 if (i + 2 < len && s.at(i+2) == '-')
3254 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3258 mres.searched_size = len;
3260 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3263 docstring docstr = stringifyFromForSearch(opt, cur, len);
3265 if (use_regexp || opt.casesensitive)
3266 str = normalize(docstr);
3268 str = normalize(lowercase(docstr));
3269 if (!opt.ignoreformat) {
3270 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3271 // remove closing '}' and '\n' to allow for use of '$' in regex
3272 size_t lng = str.size();
3273 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3275 if (lng != str.size()) {
3276 str = str.substr(0, lng);
3280 mres.match_len = -1;
3283 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
3284 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3287 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3289 QString qstr = QString::fromStdString(str);
3290 QRegularExpression const *p_regexp;
3291 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3295 p_regexp = ®exp2;
3297 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3298 if (!match.hasMatch())
3301 regex const *p_regexp;
3302 regex_constants::match_flag_type flags;
3304 flags = regex_constants::match_continuous;
3307 flags = regex_constants::match_default;
3308 p_regexp = ®exp2;
3310 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3311 if (re_it == sregex_iterator())
3313 match_results<string::const_iterator> const & m = *re_it;
3315 // Whole found string, including the leading
3316 // std: m[0].second - m[0].first
3317 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3319 // Size of the leading string
3320 // std: m[1].second - m[1].first
3321 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3322 int leadingsize = 0;
3324 if (match.lastCapturedIndex() > 0) {
3325 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3330 leadingsize = m[1].second - m[1].first;
3334 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3335 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3336 // because of different number of closing at end of string
3337 // we have to 'unify' the length of the post-match.
3338 // Done by ignoring closing parenthesis and linefeeds at string end
3339 int matchend = match.capturedEnd(0);
3340 while (mres.match_len > 0) {
3341 QChar c = qstr.at(matchend - 1);
3342 if ((c == '\n') || (c == '}') || (c == '{')) {
3349 size_t strsize = qstr.size();
3350 while (strsize > (size_t) match.capturedEnd(0)) {
3351 QChar c = qstr.at(strsize-1);
3352 if ((c == '\n') || (c == '}')) {
3358 // LYXERR0(qstr.toStdString());
3359 mres.match2end = strsize - matchend;
3360 mres.pos = match.capturedStart(2);
3362 mres.match_prefix = m[2].second - m[2].first;
3363 mres.match_len = m[0].second - m[2].second;
3364 // ignore closing parenthesis and linefeeds at string end
3365 size_t strend = m[0].second - m[0].first;
3366 int matchend = strend;
3367 while (mres.match_len > 0) {
3368 char c = str.at(matchend - 1);
3369 if ((c == '\n') || (c == '}') || (c == '{')) {
3376 size_t strsize = str.size();
3377 while (strsize > strend) {
3378 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3385 mres.match2end = strsize - matchend;
3386 mres.pos = m[2].first - m[0].first;;
3388 if (mres.match2end < 0)
3390 mres.leadsize = leadingsize;
3392 if (mres.match_len > 0) {
3393 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3394 mres.result.push_back(a0);
3395 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3396 mres.result.push_back(match.captured(i).toStdString());
3400 if (mres.match_len > 0) {
3401 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3402 mres.result.push_back(a0);
3403 for (size_t i = 3; i < m.size(); i++) {
3404 mres.result.push_back(m[i]);
3411 // else !use_regexp: but all code paths above return
3412 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3413 << par_as_string << "', str='" << str << "'");
3414 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3415 << lead_as_string << "', par_as_string_nolead='"
3416 << par_as_string_nolead << "'");
3419 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3420 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3421 if (str.substr(0, par_as_string.size()) == par_as_string) {
3422 mres.match_len = par_as_string.size();
3423 mres.match2end = str.size();
3428 // Start the search _after_ the leading part
3429 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3430 if (pos != string::npos) {
3431 mres.match_len = par_as_string.size();
3432 mres.match2end = str.size() - pos;
3441 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3443 MatchResult mres = findAux(cur, len, at_begin);
3444 int res = mres.match_len;
3446 "res=" << res << ", at_begin=" << at_begin
3447 << ", matchstart=" << opt.matchstart
3448 << ", inTexted=" << cur.inTexted());
3449 if (opt.matchstart) {
3452 else if (mres.match_prefix > 0)
3461 static bool simple_replace(string &t, string from, string to)
3463 regex repl("(\\\\)*(" + from + ")");
3467 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3469 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3471 if (lastpos < (size_t) sub.position(2))
3472 s += t.substr(lastpos, sub.position(2) - lastpos);
3474 lastpos = sub.position(2) + sub.length(2);
3478 else if (lastpos < t.length())
3479 s += t.substr(lastpos, t.length() - lastpos);
3485 string MatchStringAdv::normalize(docstring const & s) const
3488 t = lyx::to_utf8(s);
3489 // Remove \n at begin
3490 while (!t.empty() && t[0] == '\n')
3493 while (!t.empty() && t[t.size() - 1] == '\n')
3494 t = t.substr(0, t.size() - 1);
3496 // Handle all other '\n'
3497 while ((pos = t.find("\n")) != string::npos) {
3498 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3500 if (isAlnumASCII(t[pos+1])) {
3501 t.replace(pos-2, 3, " ");
3504 t.replace(pos-2, 3, "");
3507 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3508 // '\n' adjacent to non-alpha-numerics, discard
3509 t.replace(pos, 1, "");
3512 // Replace all other \n with spaces
3513 t.replace(pos, 1, " ");
3516 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3517 // Kornel: Added textsl, textsf, textit, texttt and noun
3518 // + allow to seach for colored text too
3519 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3520 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3521 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3522 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3523 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3524 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3530 docstring stringifyFromCursor(DocIterator const & cur, int len)
3532 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3533 if (cur.inTexted()) {
3534 Paragraph const & par = cur.paragraph();
3535 // TODO what about searching beyond/across paragraph breaks ?
3536 // TODO Try adding a AS_STR_INSERTS as last arg
3537 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3538 int(par.size()) : cur.pos() + len;
3539 // OutputParams runparams(&cur.buffer()->params().encoding());
3540 OutputParams runparams(encodings.fromLyXName("utf8"));
3541 runparams.nice = true;
3542 runparams.flavor = Flavor::XeTeX;
3543 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3544 // No side effect of file copying and image conversion
3545 runparams.dryrun = true;
3546 runparams.for_search = true;
3547 LYXERR(Debug::FIND, "Stringifying with cur: "
3548 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3549 return par.asString(cur.pos(), end,
3550 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3552 } else if (cur.inMathed()) {
3553 CursorSlice cs = cur.top();
3554 MathData md = cs.cell();
3555 MathData::const_iterator it_end =
3556 (( len == -1 || cs.pos() + len > int(md.size()))
3558 : md.begin() + cs.pos() + len );
3560 for (MathData::const_iterator it = md.begin() + cs.pos();
3563 docstring s = asString(md2);
3564 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3567 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3572 /** Computes the LaTeX export of buf starting from cur and ending len positions
3573 * after cur, if len is positive, or at the paragraph or innermost inset end
3576 docstring latexifyFromCursor(DocIterator const & cur, int len)
3578 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3579 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3580 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3581 Buffer const & buf = *cur.buffer();
3583 odocstringstream ods;
3585 //OutputParams runparams(&buf.params().encoding());
3586 OutputParams runparams(encodings.fromLyXName("utf8"));
3587 runparams.nice = false;
3588 runparams.flavor = Flavor::XeTeX;
3589 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3590 // No side effect of file copying and image conversion
3591 runparams.dryrun = true;
3592 runparams.for_search = true;
3594 if (cur.inTexted()) {
3595 // @TODO what about searching beyond/across paragraph breaks ?
3596 pos_type endpos = cur.paragraph().size();
3597 if (len != -1 && endpos > cur.pos() + len)
3598 endpos = cur.pos() + len;
3599 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3600 string(), cur.pos(), endpos);
3601 string s = lyx::to_utf8(ods.str());
3602 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3603 return(lyx::from_utf8(s));
3604 } else if (cur.inMathed()) {
3605 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3606 for (int s = cur.depth() - 1; s >= 0; --s) {
3607 CursorSlice const & cs = cur[s];
3608 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3609 TeXMathStream ws(os);
3610 cs.asInsetMath()->asHullInset()->header_write(ws);
3615 CursorSlice const & cs = cur.top();
3616 MathData md = cs.cell();
3617 MathData::const_iterator it_end =
3618 ((len == -1 || cs.pos() + len > int(md.size()))
3620 : md.begin() + cs.pos() + len);
3622 for (MathData::const_iterator it = md.begin() + cs.pos();
3626 ods << asString(md2);
3627 // Retrieve the math environment type, and add '$' or '$]'
3628 // or others (\end{equation}) accordingly
3629 for (int s = cur.depth() - 1; s >= 0; --s) {
3630 CursorSlice const & cs2 = cur[s];
3631 InsetMath * inset = cs2.asInsetMath();
3632 if (inset && inset->asHullInset()) {
3633 TeXMathStream ws(os);
3634 inset->asHullInset()->footer_write(ws);
3638 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3640 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3645 #if defined(ResultsDebug)
3647 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3649 LYXERR0( "from:\t\t\t" << from);
3651 if (mres.pos_len > 0) {
3653 status = "FINALSEARCH";
3656 if (mres.match_len > 0) {
3657 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3658 status = "Good Match";
3660 status = "Matched in";
3663 status = "MissedSearch";
3666 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3667 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3668 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3669 if ((mres.pos > 0) || (mres.match_prefix > 0))
3670 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3671 for (size_t i = 0; i < mres.result.size(); i++)
3672 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3674 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3676 #define displayMres(s, txt, cur)
3679 /** Finalize an advanced find operation, advancing the cursor to the innermost
3680 ** position that matches, plus computing the length of the matching text to
3682 ** Return the cur.pos() difference between start and end of found match
3684 MatchResult &findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3686 // Search the foremost position that matches (avoids find of entire math
3687 // inset when match at start of it)
3688 DocIterator old_cur(cur.buffer());
3690 static MatchResult fail = MatchResult();
3691 static MatchResult max_match;
3692 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3693 // Happens with e.g. hyperlinks
3694 // either one sees "http://www.bla.bla" or nothing
3695 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3696 // and although we search for only 3 chars, we find the whole hyperlink inset
3697 bool at_begin = (expected.match_prefix == 0);
3698 LASSERT(at_begin, /**/);
3699 if (expected.match_len > 0 && at_begin) {
3700 // Search for deepest match
3702 max_match = expected;
3704 size_t d = cur.depth();
3708 if (cur.depth() < d)
3710 if (cur.depth() == d)
3713 while (cur && cur.depth() > lastd) {
3714 lastd = cur.depth();
3715 mres = match(cur, -1, at_begin);
3716 displayMres(mres, "Checking innermost", cur);
3717 if (mres.match_len > 0)
3722 if (mres.match_len < expected.match_len)
3730 // (expected.match_len <= 0)
3731 mres = match(cur); /* match valid only if not searching whole words */
3732 displayMres(mres, "Start with negative match", cur);
3735 if (max_match.match_len <= 0) return fail;
3736 LYXERR(Debug::FIND, "Ok");
3738 // Compute the match length
3740 if (cur.pos() + len > cur.lastpos())
3742 // regexp should use \w+, \S+, or \b(some string)\b
3743 // to search for whole words
3744 if (match.opt.matchword && !match.use_regexp) {
3745 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3746 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3748 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3750 // Length of matched text (different from len param)
3751 static MatchResult old_match = match(cur, len, at_begin);
3752 if (old_match.match_len < 0)
3754 MatchResult new_match;
3755 // Greedy behaviour while matching regexps
3756 while ((new_match = match(cur, len + 1, at_begin)).match_len > old_match.match_len) {
3758 old_match = new_match;
3759 LYXERR(Debug::FIND, "verifying match with len = " << len);
3761 displayMres(old_match, "SEARCH RESULT", cur)
3766 int maxl = cur.lastpos() - cur.pos();
3767 // Greedy behaviour while matching regexps
3768 while (maxl > minl) {
3770 mres2 = match(cur, len, at_begin);
3771 displayMres(mres2, "Finalize loop", cur);
3772 int actual_match_len = mres2.match_len;
3773 if (actual_match_len >= max_match.match_len) {
3774 // actual_match_len > max_match _can_ happen,
3775 // if the search area splits
3776 // some following word so that the regex
3777 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3779 // This means, the len value is too big
3780 actual_match_len = max_match.match_len;
3782 max_match.match_len = actual_match_len;
3784 if (maxl - minl < 4)
3785 len = (int)((maxl + minl)/2);
3787 len = (int)(minl + (maxl - minl + 3)/4);
3790 // (actual_match_len < max_match.match_len)
3792 len = (int)((maxl + minl)/2);
3797 // Search for real start of matched characters
3799 MatchResult actual_match;
3802 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3803 if (cur.depth() < old_cur.depth()) {
3805 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3808 if (cur.pos() != old_cur.pos()) {
3809 // OK, forwarded 1 pos in actual inset
3810 actual_match = match(cur, len-1, at_begin);
3811 if (actual_match.match_len == max_match.match_len) {
3812 // Ha, got it! The shorter selection has the same match length
3815 max_match = actual_match;
3818 // OK, the shorter selection matches less chars, revert to previous value
3824 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3825 actual_match = match(cur, len, at_begin);
3826 if (actual_match.match_len == max_match.match_len) {
3828 max_match = actual_match;
3835 max_match.pos_len = len;
3836 displayMres(max_match, "SEARCH RESULT", cur)
3843 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3847 bool repeat = false;
3848 while (!theApp()->longOperationCancelled() && cur) {
3849 //(void) findAdvForwardInnermost(cur);
3850 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3851 MatchResult mres = match(cur, -1, false);
3852 string msg = "Starting";
3855 displayMres(mres, msg + " findForwardAdv", cur)
3856 int match_len = mres.match_len;
3857 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3858 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3861 if (match_len <= 0) {
3862 // This should exit nested insets, if any, or otherwise undefine the currsor.
3863 cur.pos() = cur.lastpos();
3864 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3867 else { // match_len > 0
3868 // Try to find the begin of searched string
3870 int firstInvalid = 100000;
3872 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3873 int incrcur = (cur.lastpos() - cur.pos() + 1 )*3/4;
3874 if (incrcur < incrmatch)
3875 increment = incrcur;
3877 increment = incrmatch;
3881 LYXERR(Debug::FIND, "Set increment to " << increment);
3882 while (increment > 0) {
3883 DocIterator old_cur = cur;
3884 size_t skipping = cur.depth();
3885 for (int i = 0; i < increment && cur; i++) {
3887 while (cur && cur.depth() > skipping) {
3888 cur.pos() = cur.lastpos();
3892 if (! cur || (cur.pit() > old_cur.pit())) {
3893 // Are we outside of the paragraph?
3894 // This can happen if moving past some UTF8-encoded chars
3899 MatchResult mres2 = match(cur, -1, false);
3900 displayMres(mres2, "findForwardAdv loop", cur)
3901 switch (interpretMatch(mres, mres2)) {
3902 case MatchResult::newIsTooFar:
3903 // behind the expected match
3904 firstInvalid = increment;
3908 case MatchResult::newIsBetter:
3909 // not reached yet, but cur.pos()+increment is bettert
3911 firstInvalid -= increment;
3912 if (increment > firstInvalid*3/4)
3913 increment = firstInvalid*3/4;
3914 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3915 if (increment >= mres2.match_prefix)
3916 increment = (mres2.match_prefix+1)*3/4;
3921 // Handle not like MatchResult::newIsTooFar
3922 LYXERR0( "Something is wrong: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3924 increment = increment*3/4;
3930 if (mres.match_len > 0 && mres.match_prefix + mres.pos - mres.leadsize > 0) {
3935 // LYXERR0("Leaving first loop");
3936 LYXERR(Debug::FIND, "Finalizing 1");
3937 MatchResult found_match = findAdvFinalize(cur, match, mres);
3938 if (found_match.match_len > 0) {
3939 LASSERT(found_match.pos_len > 0, /**/);
3940 match.FillResults(found_match);
3941 return found_match.pos_len;
3944 // try next possible match
3955 /// Find the most backward consecutive match within same paragraph while searching backwards.
3956 MatchResult &findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3958 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3959 DocIterator tmp_cur = cur;
3960 static MatchResult mr = findAdvFinalize(tmp_cur, match, MatchResult(-1));
3961 Inset & inset = cur.inset();
3962 for (; cur != cur_begin; cur.backwardPos()) {
3963 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3964 DocIterator new_cur = cur;
3965 new_cur.backwardPos();
3966 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3968 MatchResult new_mr = findAdvFinalize(new_cur, match, MatchResult(-1));
3969 if (new_mr.match_len == mr.match_len)
3973 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3979 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3983 // Backup of original position
3984 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3985 if (cur == cur_begin)
3988 DocIterator cur_orig(cur);
3989 bool pit_changed = false;
3992 bool found_match = (match(cur, -1, false).match_len > 0);
3996 cur.pos() = cur.lastpos();
3998 cur.pos() = cur_orig.pos();
3999 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
4000 DocIterator cur_prev_iter;
4002 found_match = (match(cur).match_len > 0);
4003 LYXERR(Debug::FIND, "findBackAdv3: found_match="
4004 << found_match << ", cur: " << cur);
4006 MatchResult found_mr = findMostBackwards(cur, match);
4007 match.FillResults(found_mr);
4008 LASSERT(found_mr.pos_len > 0, /**/);
4009 return found_mr.pos_len;
4012 // Stop if begin of document reached
4013 if (cur == cur_begin)
4015 cur_prev_iter = cur;
4019 if (cur == cur_begin)
4026 } while (!theApp()->longOperationCancelled());
4034 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4035 DocIterator const & cur, int len)
4037 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4039 if (!opt.ignoreformat)
4040 return latexifyFromCursor(cur, len);
4042 return stringifyFromCursor(cur, len);
4046 FindAndReplaceOptions::FindAndReplaceOptions(
4047 docstring const & _find_buf_name, bool _casesensitive,
4048 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4049 docstring const & _repl_buf_name, bool _keep_case,
4050 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4051 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4052 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4053 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4061 /** Check if 'len' letters following cursor are all non-lowercase */
4062 static bool allNonLowercase(Cursor const & cur, int len)
4064 pos_type beg_pos = cur.selectionBegin().pos();
4065 pos_type end_pos = cur.selectionBegin().pos() + len;
4066 if (len > cur.lastpos() + 1 - beg_pos) {
4067 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4068 len = cur.lastpos() + 1 - beg_pos;
4069 end_pos = beg_pos + len;
4071 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4072 if (isLowerCase(cur.paragraph().getChar(pos)))
4078 /** Check if first letter is upper case and second one is lower case */
4079 static bool firstUppercase(Cursor const & cur)
4082 pos_type pos = cur.selectionBegin().pos();
4083 if (pos >= cur.lastpos() - 1) {
4084 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4087 ch1 = cur.paragraph().getChar(pos);
4088 ch2 = cur.paragraph().getChar(pos + 1);
4089 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4090 LYXERR(Debug::FIND, "firstUppercase(): "
4091 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4092 << ch2 << "(" << char(ch2) << ")"
4093 << ", result=" << result << ", cur=" << cur);
4098 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4100 ** \fixme What to do with possible further paragraphs in replace buffer ?
4102 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4104 ParagraphList::iterator pit = buffer.paragraphs().begin();
4105 LASSERT(!pit->empty(), /**/);
4106 pos_type right = pos_type(1);
4107 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4108 right = pit->size();
4109 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4114 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4116 // Should replace the string "$" + std::to_string(matchnum) with replacement
4117 // if the char '$' is not prefixed with odd number of char '\\'
4118 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4122 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4124 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4126 int num = stoi(sub.str(3), nullptr, 10);
4127 if (num >= maxmatchnum)
4129 if (lastpos < (size_t) sub.position(2))
4130 s += t.substr(lastpos, sub.position(2) - lastpos);
4131 s += replacements[num];
4132 lastpos = sub.position(2) + sub.length(2);
4136 else if (lastpos < t.length())
4137 s += t.substr(lastpos, t.length() - lastpos);
4144 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4146 Cursor & cur = bv->cursor();
4147 if (opt.repl_buf_name.empty()
4148 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4149 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4152 DocIterator sel_beg = cur.selectionBegin();
4153 DocIterator sel_end = cur.selectionEnd();
4154 if (&sel_beg.inset() != &sel_end.inset()
4155 || sel_beg.pit() != sel_end.pit()
4156 || sel_beg.idx() != sel_end.idx())
4158 int sel_len = sel_end.pos() - sel_beg.pos();
4159 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4160 << ", sel_len: " << sel_len << endl);
4163 LASSERT(sel_len > 0, return 0);
4165 if (!matchAdv(sel_beg, sel_len).match_len)
4168 // Build a copy of the replace buffer, adapted to the KeepCase option
4169 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4171 repl_buffer_orig.write(oss);
4172 string lyx = oss.str();
4173 if (matchAdv.valid_matches > 0) {
4174 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4176 Buffer repl_buffer("", false);
4177 repl_buffer.setUnnamed(true);
4178 LASSERT(repl_buffer.readString(lyx), return 0);
4179 if (opt.keep_case && sel_len >= 2) {
4180 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4181 if (cur.inTexted()) {
4182 if (firstUppercase(cur))
4183 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4184 else if (allNonLowercase(cur, sel_len))
4185 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4188 cap::cutSelection(cur, false);
4189 if (cur.inTexted()) {
4190 repl_buffer.changeLanguage(
4191 repl_buffer.language(),
4192 cur.getFont().language());
4193 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4194 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4195 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4196 repl_buffer.params().documentClassPtr(),
4197 bv->buffer().errorList("Paste"));
4198 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4199 sel_len = repl_buffer.paragraphs().begin()->size();
4200 } else if (cur.inMathed()) {
4201 odocstringstream ods;
4203 // OutputParams runparams(&repl_buffer.params().encoding());
4204 OutputParams runparams(encodings.fromLyXName("utf8"));
4205 runparams.nice = false;
4206 runparams.flavor = Flavor::XeTeX;
4207 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4208 runparams.dryrun = true;
4209 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4210 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4211 docstring repl_latex = ods.str();
4212 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4214 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4215 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4216 repl_latex = from_utf8(s);
4217 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4218 MathData ar(cur.buffer());
4219 asArray(repl_latex, ar, Parse::NORMAL);
4221 sel_len = ar.size();
4222 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4224 if (cur.pos() >= sel_len)
4225 cur.pos() -= sel_len;
4228 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4229 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4230 bv->processUpdateFlags(Update::Force);
4235 /// Perform a FindAdv operation.
4236 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4241 // e.g., when invoking word-findadv from mini-buffer wither with
4242 // wrong options syntax or before ever opening advanced F&R pane
4243 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4247 MatchStringAdv matchAdv(bv->buffer(), opt);
4249 if (!matchAdv.regexIsValid) {
4250 bv->message(lyx::from_utf8(matchAdv.regexError));
4254 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4256 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4257 num_replaced += findAdvReplace(bv, opt, matchAdv);
4260 pos_len = findForwardAdv(cur, matchAdv);
4262 pos_len = findBackwardsAdv(cur, matchAdv);
4263 } catch (exception & ex) {
4264 bv->message(from_utf8(ex.what()));
4269 if (num_replaced > 0) {
4270 switch (num_replaced)
4273 bv->message(_("One match has been replaced."));
4276 bv->message(_("Two matches have been replaced."));
4279 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4285 bv->message(_("Match not found."));
4290 if (num_replaced > 0)
4291 bv->message(_("Match has been replaced."));
4293 bv->message(_("Match found."));
4295 if (cur.pos() + pos_len > cur.lastpos()) {
4296 // Prevent crash in bv->putSelectionAt()
4297 // Should never happen, maybe LASSERT() here?
4298 pos_len = cur.lastpos() - cur.pos();
4300 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4301 bv->putSelectionAt(cur, pos_len, !opt.forward);
4307 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4309 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4310 << opt.casesensitive << ' '
4311 << opt.matchword << ' '
4312 << opt.forward << ' '
4313 << opt.expandmacros << ' '
4314 << opt.ignoreformat << ' '
4315 << opt.replace_all << ' '
4316 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4317 << opt.keep_case << ' '
4318 << int(opt.scope) << ' '
4321 LYXERR(Debug::FIND, "built: " << os.str());
4327 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4329 LYXERR(Debug::FIND, "parsing");
4333 while (line != "EOSS") {
4337 if (is.eof()) // Tolerate malformed request
4341 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4342 opt.find_buf_name = from_utf8(s);
4343 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4344 is.get(); // Waste space before replace string
4347 while (line != "EOSS") {
4351 if (is.eof()) // Tolerate malformed request
4355 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4356 opt.repl_buf_name = from_utf8(s);
4357 is >> opt.keep_case;
4360 opt.scope = FindAndReplaceOptions::SearchScope(i);
4362 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4364 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4365 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4366 << opt.scope << ' ' << opt.restr);