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;
75 // Helper class for deciding what should be ignored
79 IgnoreFormats() = default;
81 bool getFamily() const { return ignoreFamily_; }
83 bool getSeries() const { return ignoreSeries_; }
85 bool getShape() const { return ignoreShape_; }
87 bool getUnderline() const { return ignoreUnderline_; }
89 bool getMarkUp() const { return ignoreMarkUp_; }
91 bool getStrikeOut() const { return ignoreStrikeOut_; }
93 bool getSectioning() const { return ignoreSectioning_; }
95 bool getFrontMatter() const { return ignoreFrontMatter_; }
97 bool getColor() const { return ignoreColor_; }
99 bool getLanguage() const { return ignoreLanguage_; }
101 void setIgnoreFormat(string const & type, bool value);
105 bool ignoreFamily_ = false;
107 bool ignoreSeries_ = false;
109 bool ignoreShape_ = false;
111 bool ignoreUnderline_ = false;
113 bool ignoreMarkUp_ = false;
115 bool ignoreStrikeOut_ = false;
117 bool ignoreSectioning_ = false;
119 bool ignoreFrontMatter_ = false;
121 bool ignoreColor_ = false;
123 bool ignoreLanguage_ = false;
127 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
129 if (type == "color") {
130 ignoreColor_ = value;
132 else if (type == "language") {
133 ignoreLanguage_ = value;
135 else if (type == "sectioning") {
136 ignoreSectioning_ = value;
137 ignoreFrontMatter_ = value;
139 else if (type == "font") {
140 ignoreSeries_ = value;
141 ignoreShape_ = value;
142 ignoreFamily_ = value;
144 else if (type == "series") {
145 ignoreSeries_ = value;
147 else if (type == "shape") {
148 ignoreShape_ = value;
150 else if (type == "family") {
151 ignoreFamily_ = value;
153 else if (type == "markup") {
154 ignoreMarkUp_ = value;
156 else if (type == "underline") {
157 ignoreUnderline_ = value;
159 else if (type == "strike") {
160 ignoreStrikeOut_ = value;
164 // The global variable that can be changed from outside
165 IgnoreFormats ignoreFormats;
168 void setIgnoreFormat(string const & type, bool value)
170 ignoreFormats.setIgnoreFormat(type, value);
176 bool parse_bool(docstring & howto)
181 howto = split(howto, var, ' ');
189 MatchString(docstring const & s, bool cs, bool mw)
190 : str(s), case_sens(cs), whole_words(mw)
193 // returns true if the specified string is at the specified position
194 // del specifies whether deleted strings in ct mode will be considered
195 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
197 return par.find(str, case_sens, whole_words, pos, del);
205 // match whole words only
210 int findForward(DocIterator & cur, MatchString const & match,
211 bool find_del = true)
213 for (; cur; cur.forwardChar())
214 if (cur.inTexted()) {
215 int len = match(cur.paragraph(), cur.pos(), find_del);
223 int findBackwards(DocIterator & cur, MatchString const & match,
224 bool find_del = true)
228 if (cur.inTexted()) {
229 int len = match(cur.paragraph(), cur.pos(), find_del);
238 bool searchAllowed(docstring const & str)
241 frontend::Alert::error(_("Search error"), _("Search string is empty"));
248 bool findOne(BufferView * bv, docstring const & searchstr,
249 bool case_sens, bool whole, bool forward,
250 bool find_del = true, bool check_wrap = false)
252 if (!searchAllowed(searchstr))
255 DocIterator cur = forward
256 ? bv->cursor().selectionEnd()
257 : bv->cursor().selectionBegin();
259 MatchString const match(searchstr, case_sens, whole);
261 int match_len = forward
262 ? findForward(cur, match, find_del)
263 : findBackwards(cur, match, find_del);
266 bv->putSelectionAt(cur, match_len, !forward);
267 else if (check_wrap) {
268 DocIterator cur_orig(bv->cursor());
271 q = _("End of file reached while searching forward.\n"
272 "Continue searching from the beginning?");
274 q = _("Beginning of file reached while searching backward.\n"
275 "Continue searching from the end?");
276 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
277 q, 0, 1, _("&Yes"), _("&No"));
278 if (wrap_answer == 0) {
280 bv->cursor().clear();
281 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
283 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
284 bv->cursor().backwardPos();
286 bv->clearSelection();
287 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
290 bv->cursor().setCursor(cur_orig);
294 return match_len > 0;
298 int replaceAll(BufferView * bv,
299 docstring const & searchstr, docstring const & replacestr,
300 bool case_sens, bool whole)
302 Buffer & buf = bv->buffer();
304 if (!searchAllowed(searchstr) || buf.isReadonly())
307 DocIterator cur_orig(bv->cursor());
309 MatchString const match(searchstr, case_sens, whole);
312 int const rsize = replacestr.size();
313 int const ssize = searchstr.size();
316 cur.setCursor(doc_iterator_begin(&buf));
317 int match_len = findForward(cur, match, false);
318 while (match_len > 0) {
319 // Backup current cursor position and font.
320 pos_type const pos = cur.pos();
321 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
323 int striked = ssize -
324 cur.paragraph().eraseChars(pos, pos + match_len,
325 buf.params().track_changes);
326 cur.paragraph().insert(pos, replacestr, font,
327 Change(buf.params().track_changes
329 : Change::UNCHANGED));
330 for (int i = 0; i < rsize + striked; ++i)
333 match_len = findForward(cur, match, false);
336 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
338 cur_orig.fixIfBroken();
339 bv->setCursor(cur_orig);
345 // the idea here is that we are going to replace the string that
346 // is selected IF it is the search string.
347 // if there is a selection, but it is not the search string, then
348 // we basically ignore it. (FIXME We ought to replace only within
350 // if there is no selection, then:
351 // (i) if some search string has been provided, then we find it.
352 // (think of how the dialog works when you hit "replace" the
354 // (ii) if no search string has been provided, then we treat the
355 // word the cursor is in as the search string. (why? i have no
356 // idea.) but this only works in text?
358 // returns the number of replacements made (one, if any) and
359 // whether anything at all was done.
360 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
361 docstring const & replacestr, bool case_sens,
362 bool whole, bool forward, bool findnext)
364 Cursor & cur = bv->cursor();
365 if (!cur.selection()) {
366 // no selection, non-empty search string: find it
367 if (!searchstr.empty()) {
368 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
369 return make_pair(found, 0);
371 // empty search string
374 return make_pair(false, 0);
375 // select current word and treat it as the search string.
376 // This causes a minor bug as undo will restore this selection,
377 // which the user did not create (#8986).
378 cur.innerText()->selectWord(cur, WHOLE_WORD);
379 searchstr = cur.selectionAsString(false, true);
382 // if we still don't have a search string, report the error
384 if (!searchAllowed(searchstr))
385 return make_pair(false, 0);
387 bool have_selection = cur.selection();
388 docstring const selected = cur.selectionAsString(false, true);
391 ? searchstr == selected
392 : compare_no_case(searchstr, selected) == 0;
394 // no selection or current selection is not search word:
395 // just find the search word
396 if (!have_selection || !match) {
397 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
398 return make_pair(found, 0);
401 // we're now actually ready to replace. if the buffer is
402 // read-only, we can't, though.
403 if (bv->buffer().isReadonly())
404 return make_pair(false, 0);
406 cap::replaceSelectionWithString(cur, replacestr);
408 cur.pos() += replacestr.length();
409 LASSERT(cur.pos() <= cur.lastpos(),
410 cur.pos() = cur.lastpos());
413 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
415 return make_pair(true, 1);
421 docstring const find2string(docstring const & search,
422 bool casesensitive, bool matchword, bool forward)
426 << int(casesensitive) << ' '
427 << int(matchword) << ' '
433 docstring const replace2string(docstring const & replace,
434 docstring const & search,
435 bool casesensitive, bool matchword,
436 bool all, bool forward, bool findnext)
439 ss << replace << '\n'
441 << int(casesensitive) << ' '
442 << int(matchword) << ' '
444 << int(forward) << ' '
450 bool lyxfind(BufferView * bv, FuncRequest const & ev)
452 if (!bv || ev.action() != LFUN_WORD_FIND)
455 //lyxerr << "find called, cmd: " << ev << endl;
457 // data is of the form
459 // <casesensitive> <matchword> <forward>"
461 docstring howto = split(ev.argument(), search, '\n');
463 bool casesensitive = parse_bool(howto);
464 bool matchword = parse_bool(howto);
465 bool forward = parse_bool(howto);
467 return findOne(bv, search, casesensitive, matchword, forward, false, true);
471 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
473 if (!bv || ev.action() != LFUN_WORD_REPLACE)
476 // data is of the form
479 // <casesensitive> <matchword> <all> <forward> <findnext>"
482 docstring howto = split(ev.argument(), rplc, '\n');
483 howto = split(howto, search, '\n');
485 bool casesensitive = parse_bool(howto);
486 bool matchword = parse_bool(howto);
487 bool all = parse_bool(howto);
488 bool forward = parse_bool(howto);
489 bool findnext = howto.empty() ? true : parse_bool(howto);
493 int replace_count = 0;
495 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
496 update = replace_count > 0;
499 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
501 replace_count = rv.second;
504 Buffer const & buf = bv->buffer();
506 // emit message signal.
507 buf.message(_("String not found."));
509 if (replace_count == 0) {
510 buf.message(_("String found."));
511 } else if (replace_count == 1) {
512 buf.message(_("String has been replaced."));
514 docstring const str =
515 bformat(_("%1$d strings have been replaced."), replace_count);
523 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
525 for (; cur; cur.forwardPos())
526 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
530 DocIterator cur_orig(bv->cursor());
531 docstring q = _("End of file reached while searching forward.\n"
532 "Continue searching from the beginning?");
533 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
534 q, 0, 1, _("&Yes"), _("&No"));
535 if (wrap_answer == 0) {
536 bv->cursor().clear();
537 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
538 bv->clearSelection();
539 cur.setCursor(bv->cursor().selectionBegin());
540 if (findNextChange(bv, cur, false))
543 bv->cursor().setCursor(cur_orig);
550 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
552 for (cur.backwardPos(); cur; cur.backwardPos()) {
553 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
558 DocIterator cur_orig(bv->cursor());
559 docstring q = _("Beginning of file reached while searching backward.\n"
560 "Continue searching from the end?");
561 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
562 q, 0, 1, _("&Yes"), _("&No"));
563 if (wrap_answer == 0) {
564 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
565 bv->cursor().backwardPos();
566 bv->clearSelection();
567 cur.setCursor(bv->cursor().selectionBegin());
568 if (findPreviousChange(bv, cur, false))
571 bv->cursor().setCursor(cur_orig);
578 bool selectChange(Cursor & cur, bool forward)
580 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
582 Change ch = cur.paragraph().lookupChange(cur.pos());
584 CursorSlice tip1 = cur.top();
585 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
586 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
587 if (!ch2.isSimilarTo(ch))
590 CursorSlice tip2 = cur.top();
591 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
593 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
594 if (!ch2.isSimilarTo(ch)) {
595 // take a step forward to correctly set the selection
603 cur.bv().mouseSetCursor(cur, false);
605 cur.bv().mouseSetCursor(cur, true);
613 bool findChange(BufferView * bv, bool forward)
616 cur.setCursor(forward ? bv->cursor().selectionEnd()
617 : bv->cursor().selectionBegin());
618 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
619 return selectChange(cur, forward);
624 bool findNextChange(BufferView * bv)
626 return findChange(bv, true);
630 bool findPreviousChange(BufferView * bv)
632 return findChange(bv, false);
639 typedef vector<pair<string, string> > Escapes;
641 /// A map of symbols and their escaped equivalent needed within a regex.
642 /// @note Beware of order
644 Escapes const & get_regexp_escapes()
646 typedef std::pair<std::string, std::string> P;
648 static Escapes escape_map;
649 if (escape_map.empty()) {
650 escape_map.push_back(P("$", "_x_$"));
651 escape_map.push_back(P("{", "_x_{"));
652 escape_map.push_back(P("}", "_x_}"));
653 escape_map.push_back(P("[", "_x_["));
654 escape_map.push_back(P("]", "_x_]"));
655 escape_map.push_back(P("(", "_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("\\", "(?:\\\\|\\\\backslash)"));
661 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
662 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
663 escape_map.push_back(P("_x_", "\\"));
669 /// A map of lyx escaped strings and their unescaped equivalent.
671 Escapes const & get_lyx_unescapes()
673 typedef std::pair<std::string, std::string> P;
675 static Escapes escape_map;
676 if (escape_map.empty()) {
677 escape_map.push_back(P("\\%", "%"));
678 escape_map.push_back(P("\\{", "{"));
679 escape_map.push_back(P("\\}", "}"));
680 escape_map.push_back(P("\\mathcircumflex ", "^"));
681 escape_map.push_back(P("\\mathcircumflex", "^"));
682 escape_map.push_back(P("\\backslash ", "\\"));
683 escape_map.push_back(P("\\backslash", "\\"));
684 escape_map.push_back(P("\\sim ", "~"));
685 escape_map.push_back(P("\\sim", "~"));
691 /// A map of escapes turning a regexp matching text to one matching latex.
693 Escapes const & get_regexp_latex_escapes()
695 typedef std::pair<std::string, std::string> P;
697 static Escapes escape_map;
698 if (escape_map.empty()) {
699 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
700 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
701 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
702 escape_map.push_back(P("\\[", "\\{\\[\\}"));
703 escape_map.push_back(P("\\]", "\\{\\]\\}"));
704 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
705 escape_map.push_back(P("%", "\\\\\\%"));
706 escape_map.push_back(P("#", "\\\\#"));
712 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
713 ** the found occurrence were escaped.
716 string apply_escapes(string s, Escapes const & escape_map)
718 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
719 Escapes::const_iterator it;
720 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
721 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
722 unsigned int pos = 0;
723 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
724 s.replace(pos, it->first.length(), it->second);
725 LYXERR(Debug::FIND, "After escape: " << s);
726 pos += it->second.length();
727 // LYXERR(Debug::FIND, "pos: " << pos);
730 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
736 string string2regex(string in)
738 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
739 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
744 while (fl_pos < temp.size()) {
745 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
746 if (fl_pos == string::npos)
749 temp2 += temp.substr(lastpos, fl_pos - lastpos);
755 if (lastpos < temp.size()) {
756 temp2 += temp.substr(lastpos, temp.size() - lastpos);
761 string correctRegex(string t)
763 /* Convert \backslash => \
764 * and \{, \}, \[, \] => {, }, [, ]
767 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
770 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
773 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
777 if (sub.str(4) == "backslash")
779 else if (sub.str(4) == "mathcircumflex")
781 else if (sub.str(3) == "{")
782 replace = "\\braceleft";
783 else if (sub.str(3) == "}")
784 replace = "\\braceright";
786 replace = sub.str(3);
788 if (lastpos < (size_t) sub.position(2))
789 s += t.substr(lastpos, sub.position(2) - lastpos);
791 lastpos = sub.position(2) + sub.length(2);
795 else if (lastpos < t.length())
796 s += t.substr(lastpos, t.length() - lastpos);
800 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
801 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
802 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
803 string escape_for_regex(string s)
807 while (lastpos < s.size()) {
808 size_t regex_pos = s.find("\\regexp{", lastpos);
809 if (regex_pos == string::npos) {
810 regex_pos = s.size();
812 if (regex_pos > lastpos) {
813 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
815 if (lastpos == s.size())
818 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
819 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)));
820 lastpos = end_pos + 13;
826 /// Wrapper for lyx::regex_replace with simpler interface
827 bool regex_replace(string const & s, string & t, string const & searchstr,
828 string const & replacestr)
830 regex e(searchstr, regex_constants::ECMAScript);
832 ostream_iterator<char, char> it(oss);
833 regex_replace(it, s.begin(), s.end(), e, replacestr);
834 // tolerate t and s be references to the same variable
835 bool rv = (s != oss.str());
841 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
843 ** Verify that closed braces exactly match open braces. This avoids that, for example,
844 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
847 ** Number of open braces that must remain open at the end for the verification to succeed.
850 bool braces_match(QString const & beg,
853 bool braces_match(string const & beg,
859 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg.toStdString() << "'");
861 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg << "'");
863 int lastidx = beg.size();
864 for (int i=0; i < lastidx; ++i) {
865 // Skip escaped braces in the count
875 } else if (c == '{') {
877 } else if (c == '}') {
878 if (open_pars == 0) {
879 LYXERR(Debug::FIND, "Found unmatched closed brace");
885 if (open_pars != unmatched) {
886 LYXERR(Debug::FIND, "Found " << open_pars
887 << " instead of " << unmatched
888 << " unmatched open braces at the end of count");
891 LYXERR(Debug::FIND, "Braces match as expected");
910 vector <string> result = vector <string>();
911 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
914 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
916 int range = oldres.match_len;
917 if (range > 0) range--;
918 if (newres.match2end < oldres.match2end - oldres.match_len)
919 return MatchResult::newIsTooFar;
920 if (newres.match_len < oldres.match_len)
921 return MatchResult::newIsTooFar;
922 if ((newres.match_len == oldres.match_len) &&
923 (newres.match2end < oldres.match2end + range) &&
924 (newres.match2end > oldres.match2end - range)) {
925 return MatchResult::newIsBetter;
927 return MatchResult::newIsInvalid;
930 /** The class performing a match between a position in the document and the FindAdvOptions.
933 class MatchStringAdv {
935 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
937 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
938 ** constructor as opt.search, under the opt.* options settings.
941 ** If set, then match is searched only against beginning of text starting at cur.
942 ** If unset, then match is searched anywhere in text starting at cur.
945 ** The length of the matching text, or zero if no match was found.
947 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
956 /// first buffer on which search was started
957 lyx::Buffer * const p_first_buf;
959 FindAndReplaceOptions const & opt;
962 /// Auxiliary find method (does not account for opt.matchword)
963 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
964 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
966 /** Normalize a stringified or latexified LyX paragraph.
970 ** <li>if search is not casesensitive, then lowercase the string;
971 ** <li>remove any newline at begin or end of the string;
972 ** <li>replace any newline in the middle of the string with a simple space;
973 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
976 ** @todo Normalization should also expand macros, if the corresponding
977 ** search option was checked.
979 string normalize(docstring const & s) const;
980 // normalized string to search
981 string par_as_string;
982 // regular expression to use for searching
983 // regexp2 is same as regexp, but prefixed with a ".*?"
985 QRegularExpression regexp;
986 QRegularExpression regexp2;
991 // leading format material as string
992 string lead_as_string;
993 // par_as_string after removal of lead_as_string
994 string par_as_string_nolead;
995 // unmatched open braces in the search string/regexp
997 // number of (.*?) subexpressions added at end of search regexp for closing
998 // environments, math mode, styles, etc...
1001 // Are we searching with regular expressions ?
1003 static int valid_matches;
1004 static vector <string> matches;
1005 void FillResults(MatchResult &found_mr);
1008 int MatchStringAdv::valid_matches = 0;
1009 vector <string> MatchStringAdv::matches = vector <string>(10);
1011 void MatchStringAdv::FillResults(MatchResult &found_mr)
1013 if (found_mr.match_len > 0) {
1014 valid_matches = found_mr.result.size();
1015 for (size_t i = 0; i < found_mr.result.size(); i++)
1016 matches[i] = found_mr.result[i];
1022 static docstring buffer_to_latex(Buffer & buffer)
1024 //OutputParams runparams(&buffer.params().encoding());
1025 OutputParams runparams(encodings.fromLyXName("utf8"));
1026 odocstringstream ods;
1028 runparams.nice = true;
1029 runparams.flavor = Flavor::XeTeX;
1030 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1031 // No side effect of file copying and image conversion
1032 runparams.dryrun = true;
1033 runparams.for_search = true;
1034 pit_type const endpit = buffer.paragraphs().size();
1035 for (pit_type pit = 0; pit != endpit; ++pit) {
1036 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
1037 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
1043 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1046 if (!opt.ignoreformat) {
1047 str = buffer_to_latex(buffer);
1049 // OutputParams runparams(&buffer.params().encoding());
1050 OutputParams runparams(encodings.fromLyXName("utf8"));
1051 runparams.nice = true;
1052 runparams.flavor = Flavor::XeTeX;
1053 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1054 runparams.dryrun = true;
1055 runparams.for_search = true;
1056 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1057 Paragraph const & par = buffer.paragraphs().at(pit);
1058 LYXERR(Debug::FIND, "Adding to search string: '"
1059 << par.asString(pos_type(0), par.size(),
1060 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1063 str += par.asString(pos_type(0), par.size(),
1064 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1067 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1068 string t = to_utf8(str);
1069 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
1076 /// Return separation pos between the leading material and the rest
1077 static size_t identifyLeading(string const & s)
1080 // @TODO Support \item[text]
1081 // Kornel: Added textsl, textsf, textit, texttt and noun
1082 // + allow to search for colored text too
1083 while (regex_replace(t, t, "^\\\\(("
1084 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1085 "lyxaddress|lyxrightaddress|"
1086 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1087 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1088 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1089 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1090 || regex_replace(t, t, "^\\$", "")
1091 || regex_replace(t, t, "^\\\\\\[", "")
1092 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1093 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1095 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1100 * Given a latexified string, retrieve some handled features
1101 * The features of the regex will later be compared with the features
1102 * of the searched text. If the regex features are not a
1103 * subset of the analized, then, in not format ignoring search
1104 * we can early stop the search in the relevant inset.
1106 typedef map<string, bool> Features;
1108 static Features identifyFeatures(string const & s)
1110 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1111 static regex const valid("^("
1113 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1114 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1115 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1116 "(u|uu)line|(s|x)out|uwave|"
1117 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1118 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1123 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1126 if (sub.str(1).compare("regexp") == 0) {
1130 string token = sub.str(1);
1132 if (regex_match(token, sub2, valid)) {
1140 if (sub.str(1).compare("endregexp") == 0) {
1150 * defines values features of a key "\\[a-z]+{"
1155 /* Char type with content discarded
1156 * like \hspace{1cm} */
1158 /* Char, like \backslash */
1160 /* replace starting backslash with '#' */
1162 /* \part, \section*, ... */
1164 /* title, author etc */
1166 /* \foreignlanguage{ngerman}, ... */
1169 * to discard language in content */
1172 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1174 /* fonts, colors, markups, ... */
1176 /* footnotesize, ... large, ...
1177 * Ignore all of them */
1180 /* inputencoding, ...
1181 * Discard also content, because they do not help in search */
1184 * like remove, but also all arguments */
1186 /* item, listitem */
1188 /* tex, latex, ... like isChar */
1190 /* like \lettrine[lines=5]{}{} */
1192 // like isStandard, but always remove head
1194 /* End of arguments marker for lettrine,
1195 * so that they can be ignored */
1198 KeyInfo() = default;
1199 KeyInfo(KeyType type, int parcount, bool disable)
1201 parenthesiscount(parcount),
1202 disabled(disable) {}
1203 KeyType keytype = invalid;
1205 int _tokensize = -1;
1206 int _tokenstart = -1;
1207 int _dataStart = -1;
1209 int parenthesiscount = 1;
1210 bool disabled = false;
1211 bool used = false; /* by pattern */
1216 Border(int l=0, int u=0) : low(l), upper(u) {};
1221 #define MAXOPENED 30
1223 bool isPatternString_;
1225 explicit Intervall(bool isPattern, string const & p) :
1226 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1227 hasTitle(false), langcount(0)
1235 static vector<Border> borders;
1236 int depts[MAXOPENED];
1237 int closes[MAXOPENED];
1238 int actualdeptindex;
1239 int previousNotIgnored(int) const;
1240 int nextNotIgnored(int) const;
1241 void handleOpenP(int i);
1242 void handleCloseP(int i, bool closingAllowed);
1243 void resetOpenedP(int openPos);
1244 void addIntervall(int upper);
1245 void addIntervall(int low, int upper); /* if explicit */
1246 void removeAccents();
1247 void setForDefaultLang(KeyInfo const & defLang) const;
1248 int findclosing(int start, int end, char up, char down, int repeat);
1249 void handleParentheses(int lastpos, bool closingAllowed);
1251 int langcount; // Number of disabled language specs up to current position in actual interval
1252 int isOpeningPar(int pos) const;
1254 void output(ostringstream &os, int lastpos);
1255 // string show(int lastpos);
1258 vector<Border> Intervall::borders = vector<Border>(30);
1260 int Intervall::isOpeningPar(int pos) const
1262 if ((pos < 0) || (size_t(pos) >= par.size()))
1264 if (par[pos] != '{')
1266 if (size_t(pos) + 2 >= par.size())
1268 if (par[pos+2] != '}')
1270 if (par[pos+1] == '[' || par[pos+1] == ']')
1275 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1277 // Enable the use of first token again
1278 if (ignoreidx >= 0) {
1279 int value = defLang._tokenstart + defLang._tokensize;
1285 if (borders[borderidx].low < value)
1286 borders[borderidx].low = value;
1287 if (borders[borderidx].upper < value)
1288 borders[borderidx].upper = value;
1293 static void checkDepthIndex(int val)
1295 static int maxdepthidx = MAXOPENED-2;
1296 static int lastmaxdepth = 0;
1297 if (val > lastmaxdepth) {
1298 LYXERR(Debug::INFO, "Depth reached " << val);
1301 if (val > maxdepthidx) {
1303 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1308 // Not needed, because borders are now dynamically expanded
1309 static void checkIgnoreIdx(int val)
1311 static int lastmaxignore = -1;
1312 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1313 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1314 lastmaxignore = val;
1320 * Expand the region of ignored parts of the input latex string
1321 * The region is only relevant in output()
1323 void Intervall::addIntervall(int low, int upper)
1326 if (low == upper) return;
1327 for (idx = ignoreidx+1; idx > 0; --idx) {
1328 if (low > borders[idx-1].upper) {
1332 Border br(low, upper);
1333 if (idx > ignoreidx) {
1334 if (borders.size() <= size_t(idx)) {
1335 borders.push_back(br);
1341 // checkIgnoreIdx(ignoreidx);
1345 // Expand only if one of the new bound is inside the interwall
1346 // We know here that br.low > borders[idx-1].upper
1347 if (br.upper < borders[idx].low) {
1348 // We have to insert at this pos
1349 if (size_t(ignoreidx+1) >= borders.size()) {
1350 borders.push_back(borders[ignoreidx]);
1353 borders[ignoreidx+1] = borders[ignoreidx];
1355 for (int i = ignoreidx; i > idx; --i) {
1356 borders[i] = borders[i-1];
1360 // checkIgnoreIdx(ignoreidx);
1363 // Here we know, that we are overlapping
1364 if (br.low > borders[idx].low)
1365 br.low = borders[idx].low;
1366 // check what has to be concatenated
1368 for (int i = idx; i <= ignoreidx; i++) {
1369 if (br.upper >= borders[i].low) {
1371 if (br.upper < borders[i].upper)
1372 br.upper = borders[i].upper;
1378 // count should be >= 1 here
1381 for (int i = idx + count; i <= ignoreidx; i++) {
1382 borders[i-count+1] = borders[i];
1384 ignoreidx -= count - 1;
1390 typedef map<string, string> AccentsMap;
1391 static AccentsMap accents = map<string, string>();
1393 static void buildaccent(string n, string param, string values)
1397 const char delim = '|';
1398 while (getline(s, name, delim)) {
1400 for (char c : param) {
1401 string key = name + "{" + c + "}";
1402 // get the corresponding utf8-value
1403 if ((values[start] & 0xc0) != 0xc0) {
1404 // should not happen, utf8 encoding starts at least with 11xxxxxx
1405 // but value for '\dot{i}' is 'i', which is ascii
1406 if ((values[start] & 0x80) == 0) {
1408 accents[key] = values.substr(start, 1);
1409 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1414 for (int j = 1; ;j++) {
1415 if (start + j >= values.size()) {
1416 accents[key] = values.substr(start, j);
1417 start = values.size() - 1;
1420 else if ((values[start+j] & 0xc0) != 0x80) {
1421 // This is the first byte of following utf8 char
1422 accents[key] = values.substr(start, j);
1424 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1433 static string getutf8(unsigned uchar)
1436 string ret = string();
1438 if (uchar <= 0x7f) {
1439 c[maxc-1] = uchar & 0x7f;
1442 unsigned char rest = 0x40;
1443 unsigned char first = 0x80;
1445 for (int i = start; i >=0; --i) {
1447 c[i] = first + uchar;
1450 c[i] = 0x80 | (uchar & 0x3f);
1457 for (int i = 0; i < maxc; i++) {
1458 if (c[i] == 0) continue;
1464 static void buildAccentsMap()
1466 accents["imath"] = "ı";
1468 accents["jmath"] = "ȷ";
1469 accents["cdot"] = "·";
1470 accents["textasciicircum"] = "^";
1471 accents["mathcircumflex"] = "^";
1472 accents["sim"] = "~";
1473 accents["guillemotright"] = "»";
1474 accents["guillemotleft"] = "«";
1475 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1476 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1477 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1478 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1479 accents["negmedspace"] = getutf8(0xf0005);
1480 accents["thickspace"] = getutf8(0xf0006);
1481 accents["negthickspace"] = getutf8(0xf0007);
1482 accents["lyx"] = getutf8(0xf0010); // Used logos
1483 accents["LyX"] = getutf8(0xf0010);
1484 accents["tex"] = getutf8(0xf0011);
1485 accents["TeX"] = getutf8(0xf0011);
1486 accents["latex"] = getutf8(0xf0012);
1487 accents["LaTeX"] = getutf8(0xf0012);
1488 accents["latexe"] = getutf8(0xf0013);
1489 accents["LaTeXe"] = getutf8(0xf0013);
1490 accents["lyxarrow"] = getutf8(0xf0020);
1491 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1492 accents["backslash LyX"] = getutf8(0xf0010);
1493 accents["backslash tex"] = getutf8(0xf0011);
1494 accents["backslash TeX"] = getutf8(0xf0011);
1495 accents["backslash latex"] = getutf8(0xf0012);
1496 accents["backslash LaTeX"] = getutf8(0xf0012);
1497 accents["backslash latexe"] = getutf8(0xf0013);
1498 accents["backslash LaTeXe"] = getutf8(0xf0013);
1499 accents["backslash lyxarrow"] = getutf8(0xf0020);
1500 accents["ddot{\\imath}"] = "ï";
1501 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1502 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1503 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1504 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1505 accents["acute{\\imath}"] = "í";
1506 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1507 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1508 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1509 buildaccent("mathring|r", "aAuUwy",
1511 accents["check{\\imath}"] = "ǐ";
1512 accents["check{\\jmath}"] = "ǰ";
1513 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1514 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1515 accents["hat{\\imath}"] = "î";
1516 accents["hat{\\jmath}"] = "ĵ";
1517 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1518 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1519 accents["bar{\\imath}"] = "ī";
1520 buildaccent("bar|=", "aAeEiIoOuUyY",
1521 "āĀēĒīĪōŌūŪȳȲ"); // macron
1522 accents["tilde{\\imath}"] = "ĩ";
1523 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1524 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1525 accents["breve{\\imath}"] = "ĭ";
1526 buildaccent("breve|u", "aAeEgGiIoOuU",
1527 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1528 accents["grave{\\imath}"] = "ì";
1529 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1530 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1531 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1532 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1533 buildaccent("ogonek|k", "AaEeIiUuOo",
1534 "ĄąĘęĮįŲųǪǫ"); // ogonek
1535 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1536 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1537 buildaccent("subring|textsubring", "Aa",
1539 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1540 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1541 buildaccent("subtilde|textsubtilde", "EeIiUu",
1542 "ḚḛḬḭṴṵ"); // subtilde
1543 accents["dgrave{\\imath}"] = "ȉ";
1544 accents["textdoublegrave{\\i}"] = "ȉ";
1545 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1546 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1547 accents["rcap{\\imath}"] = "ȉ";
1548 accents["textroundcap{\\i}"] = "ȉ";
1549 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1550 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1551 buildaccent("slashed", "oO",
1556 * Created accents in math or regexp environment
1557 * are macros, but we need the utf8 equivalent
1559 void Intervall::removeAccents()
1561 if (accents.empty())
1563 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1564 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1565 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|guillemot(left|right)|textasciicircum|mathcircumflex|sim)(?![a-zA-Z]))");
1567 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1569 string key = sub.str(1);
1570 if (accents.find(key) != accents.end()) {
1571 string val = accents[key];
1572 size_t pos = sub.position(size_t(0));
1573 for (size_t i = 0; i < val.size(); i++) {
1574 par[pos+i] = val[i];
1576 // Remove possibly following space too
1577 if (par[pos+sub.str(0).size()] == ' ')
1578 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1580 addIntervall(pos+val.size(), pos + sub.str(0).size());
1581 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1582 // remove traces of any remaining chars
1587 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1592 void Intervall::handleOpenP(int i)
1595 depts[actualdeptindex] = i+1;
1596 closes[actualdeptindex] = -1;
1597 checkDepthIndex(actualdeptindex);
1600 void Intervall::handleCloseP(int i, bool closingAllowed)
1602 if (actualdeptindex <= 0) {
1603 if (! closingAllowed)
1604 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1605 // if we are at the very end
1606 addIntervall(i, i+1);
1609 closes[actualdeptindex] = i+1;
1614 void Intervall::resetOpenedP(int openPos)
1616 // Used as initializer for foreignlanguage entry
1617 actualdeptindex = 1;
1618 depts[1] = openPos+1;
1622 int Intervall::previousNotIgnored(int start) const
1624 int idx = 0; /* int intervalls */
1625 for (idx = ignoreidx; idx >= 0; --idx) {
1626 if (start > borders[idx].upper)
1628 if (start >= borders[idx].low)
1629 start = borders[idx].low-1;
1634 int Intervall::nextNotIgnored(int start) const
1636 int idx = 0; /* int intervalls */
1637 for (idx = 0; idx <= ignoreidx; idx++) {
1638 if (start < borders[idx].low)
1640 if (start < borders[idx].upper)
1641 start = borders[idx].upper;
1646 typedef map<string, KeyInfo> KeysMap;
1647 typedef vector< KeyInfo> Entries;
1648 static KeysMap keys = map<string, KeyInfo>();
1654 Intervall interval_;
1655 void buildKeys(bool);
1656 void buildEntries(bool);
1657 void makeKey(const string &, KeyInfo, bool isPatternString);
1658 void processRegion(int start, int region_end); /* remove {} parts */
1659 void removeHead(KeyInfo const &, int count=0);
1662 LatexInfo(string const & par, bool isPatternString)
1663 : entidx_(-1), interval_(isPatternString, par)
1665 buildKeys(isPatternString);
1666 entries_ = vector<KeyInfo>();
1667 buildEntries(isPatternString);
1671 if (entries_.empty()) {
1674 if (entries_[0].keytype == KeyInfo::isTitle) {
1675 interval_.hasTitle = true;
1676 if (! entries_[0].disabled) {
1677 interval_.titleValue = entries_[0].head;
1680 interval_.titleValue = "";
1682 removeHead(entries_[0]);
1683 if (entries_.size() > 1)
1692 if (int(entries_.size()) > entidx_) {
1699 bool setNextKey(int idx) {
1700 if ((idx == entidx_) && (entidx_ >= 0)) {
1707 int find(int start, KeyInfo::KeyType keytype) const {
1711 while (tmpIdx < int(entries_.size())) {
1712 if (entries_[tmpIdx].keytype == keytype)
1718 int process(ostringstream & os, KeyInfo const & actual);
1719 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1720 // string show(int lastpos) { return interval.show(lastpos);};
1721 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1722 KeyInfo &getKeyInfo(int keyinfo) {
1723 static KeyInfo invalidInfo = KeyInfo();
1724 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1727 return entries_[keyinfo];
1729 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1730 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1734 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1738 for (int i = start; i < end; i += 1 + skip) {
1742 if (c == '\\') skip = 1;
1746 else if (c == down) {
1749 if ((repeat <= 0) || (par[i+1] != up))
1767 vector<MathEntry> entries_;
1772 void insert(string const & wait, size_t start, size_t end) {
1773 MathEntry m = MathEntry();
1775 m.mathStart = start;
1777 m.mathSize = end - start;
1778 entries_.push_back(m);
1780 bool empty() const { return entries_.empty(); };
1781 size_t getEndPos() const {
1782 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1785 return entries_[actualIdx_].mathEnd;
1787 size_t getStartPos() const {
1788 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1789 return 100000; /* definitely enough? */
1791 return entries_[actualIdx_].mathStart;
1793 size_t getFirstPos() {
1795 return getStartPos();
1797 size_t getSize() const {
1798 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1801 return entries_[actualIdx_].mathSize;
1803 void incrEntry() { actualIdx_++; };
1806 void LatexInfo::buildEntries(bool isPatternString)
1808 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1809 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1810 static bool disableLanguageOverride = false;
1811 smatch sub, submath;
1812 bool evaluatingRegexp = false;
1814 bool evaluatingMath = false;
1815 bool evaluatingCode = false;
1817 bool evaluatingOptional = false;
1818 size_t optionalEnd = 0;
1821 bool math_end_waiting = false;
1822 size_t math_pos = 10000;
1824 static vector<string> usedText = vector<string>();
1826 interval_.removeAccents();
1828 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1830 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1831 // prefixed by odd count of '\\'
1834 if (math_end_waiting) {
1835 size_t pos = submath.position(size_t(2));
1836 if ((math_end == "$") &&
1837 (submath.str(2) == "$")) {
1838 mi.insert("$", math_pos, pos + 1);
1839 math_end_waiting = false;
1841 else if ((math_end == "\\]") &&
1842 (submath.str(2) == "\\]")) {
1843 mi.insert("\\]", math_pos, pos + 2);
1844 math_end_waiting = false;
1846 else if ((submath.str(3).compare("end") == 0) &&
1847 (submath.str(4).compare(math_end) == 0)) {
1848 mi.insert(math_end, math_pos, pos + submath.str(2).length());
1849 math_end_waiting = false;
1855 if (submath.str(3).compare("begin") == 0) {
1856 math_end_waiting = true;
1857 math_end = submath.str(4);
1858 math_pos = submath.position(size_t(2));
1860 else if (submath.str(2).compare("\\[") == 0) {
1861 math_end_waiting = true;
1863 math_pos = submath.position(size_t(2));
1865 else if (submath.str(2) == "$") {
1866 size_t pos = submath.position(size_t(2));
1867 math_end_waiting = true;
1873 // Ignore language if there is math somewhere in pattern-string
1874 if (isPatternString) {
1875 for (auto s: usedText) {
1876 // Remove entries created in previous search runs
1879 usedText = vector<string>();
1882 keys["foreignlanguage"].disabled = true;
1883 disableLanguageOverride = true;
1886 disableLanguageOverride = false;
1889 if (disableLanguageOverride) {
1890 keys["foreignlanguage"].disabled = true;
1893 math_pos = mi.getFirstPos();
1894 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1896 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1897 // prefixed by odd count of '\\'
1900 string key = sub.str(5);
1902 if (sub.str(2)[0] == '\\')
1903 key = sub.str(2)[1];
1908 if (keys.find(key) != keys.end()) {
1909 if (keys[key].keytype == KeyInfo::headRemove) {
1910 KeyInfo found1 = keys[key];
1911 found1.disabled = true;
1912 found1.head = "\\" + key + "{";
1913 found1._tokenstart = sub.position(size_t(2));
1914 found1._tokensize = found1.head.length();
1915 found1._dataStart = found1._tokenstart + found1.head.length();
1916 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1917 found1._dataEnd = endpos;
1922 if (evaluatingRegexp) {
1923 if (sub.str(3).compare("endregexp") == 0) {
1924 evaluatingRegexp = false;
1925 // found._tokenstart already set
1926 found._dataEnd = sub.position(size_t(2)) + 13;
1927 found._dataStart = found._dataEnd;
1928 found._tokensize = found._dataEnd - found._tokenstart;
1929 found.parenthesiscount = 0;
1930 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1937 if (evaluatingMath) {
1938 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1940 evaluatingMath = false;
1942 math_pos = mi.getStartPos();
1944 if (keys.find(key) == keys.end()) {
1945 found = KeyInfo(KeyInfo::isStandard, 0, true);
1946 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1947 found = KeyInfo(KeyInfo::isText, 0, false);
1948 if (isPatternString) {
1949 found.keytype = KeyInfo::isChar;
1950 found.disabled = false;
1954 usedText.push_back(key);
1958 if (key.compare("regexp") == 0) {
1959 evaluatingRegexp = true;
1960 found._tokenstart = sub.position(size_t(2));
1961 found._tokensize = 0;
1965 // Handle the other params of key
1966 if (found.keytype == KeyInfo::isIgnored)
1968 else if (found.keytype == KeyInfo::isMath) {
1969 if (size_t(sub.position(size_t(2))) == math_pos) {
1971 found._tokenstart = sub.position(size_t(2));
1972 found._tokensize = mi.getSize();
1973 found._dataEnd = found._tokenstart + found._tokensize;
1974 found._dataStart = found._dataEnd;
1975 found.parenthesiscount = 0;
1976 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1977 evaluatingMath = true;
1980 // begin|end of unknown env, discard
1981 // First handle tables
1982 // longtable|tabular
1983 bool discardComment;
1985 found.keytype = KeyInfo::doRemove;
1986 if ((sub.str(7).compare("longtable") == 0) ||
1987 (sub.str(7).compare("tabular") == 0)) {
1988 discardComment = true; /* '%' */
1991 discardComment = false;
1992 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1994 string token = sub.str(7);
1995 if (regex_match(token, sub2, removeArgs)) {
1996 found.keytype = KeyInfo::removeWithArg;
1999 // discard spaces before pos(2)
2000 int pos = sub.position(size_t(2));
2002 for (count = 0; pos - count > 0; count++) {
2003 char c = interval_.par[pos-count-1];
2004 if (discardComment) {
2005 if ((c != ' ') && (c != '%'))
2011 found._tokenstart = pos - count;
2012 if (sub.str(3).compare(0, 5, "begin") == 0) {
2013 size_t pos1 = pos + sub.str(2).length();
2014 if (sub.str(7).compare("cjk") == 0) {
2015 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2016 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2018 found.keytype = KeyInfo::isMain;
2019 found._dataStart = pos1;
2020 found._dataEnd = interval_.par.length();
2021 found.disabled = keys["foreignlanguage"].disabled;
2022 found.used = keys["foreignlanguage"].used;
2023 found._tokensize = pos1 - found._tokenstart;
2024 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2027 // Swallow possible optional params
2028 while (interval_.par[pos1] == '[') {
2029 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2031 // Swallow also the eventual parameter
2032 if (interval_.par[pos1] == '{') {
2033 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2036 found._dataEnd = pos1;
2038 found._dataStart = found._dataEnd;
2039 found._tokensize = count + found._dataEnd - pos;
2040 found.parenthesiscount = 0;
2041 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2042 found.disabled = true;
2046 // Handle "\end{...}"
2047 found._dataStart = pos + sub.str(2).length();
2048 found._dataEnd = found._dataStart;
2049 found._tokensize = count + found._dataEnd - pos;
2050 found.parenthesiscount = 0;
2051 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2052 found.disabled = true;
2056 else if (found.keytype != KeyInfo::isRegex) {
2057 found._tokenstart = sub.position(size_t(2));
2058 if (found.parenthesiscount == 0) {
2059 // Probably to be discarded
2060 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2061 char following = interval_.par[following_pos];
2062 if (following == ' ')
2063 found.head = "\\" + sub.str(5) + " ";
2064 else if (following == '=') {
2065 // like \uldepth=1000pt
2066 found.head = sub.str(2);
2069 found.head = "\\" + key;
2070 found._tokensize = found.head.length();
2071 found._dataEnd = found._tokenstart + found._tokensize;
2072 found._dataStart = found._dataEnd;
2075 int params = found._tokenstart + key.length() + 1;
2076 if (evaluatingOptional) {
2077 if (size_t(found._tokenstart) > optionalEnd) {
2078 evaluatingOptional = false;
2081 found.disabled = true;
2084 int optend = params;
2085 while (interval_.par[optend] == '[') {
2086 // discard optional parameters
2087 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2089 if (optend > params) {
2090 key += interval_.par.substr(params, optend-params);
2091 evaluatingOptional = true;
2092 optionalEnd = optend;
2093 if (found.keytype == KeyInfo::isSectioning) {
2094 // Remove optional values (but still keep in header)
2095 interval_.addIntervall(params, optend);
2098 string token = sub.str(7);
2100 if (interval_.par[optend] != '{') {
2102 found.parenthesiscount = 0;
2103 found.head = "\\" + key;
2106 closings = found.parenthesiscount;
2107 if (found.parenthesiscount == 1) {
2108 found.head = "\\" + key + "{";
2110 else if (found.parenthesiscount > 1) {
2112 found.head = sub.str(2) + "{";
2113 closings = found.parenthesiscount - 1;
2116 found.head = "\\" + key + "{";
2119 found._tokensize = found.head.length();
2120 found._dataStart = found._tokenstart + found.head.length();
2121 if (found.keytype == KeyInfo::doRemove) {
2123 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2124 if (endpar >= interval_.par.length())
2125 found._dataStart = interval_.par.length();
2127 found._dataStart = endpar;
2128 found._tokensize = found._dataStart - found._tokenstart;
2131 found._dataStart = found._tokenstart + found._tokensize;
2135 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2136 found._dataStart += 15;
2140 endpos = found._dataStart - 1;
2142 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2143 if (found.keytype == KeyInfo::isList) {
2144 // Check if it really is list env
2145 static regex const listre("^([a-z]+)$");
2147 if (!regex_match(token, sub2, listre)) {
2148 // Change the key of this entry. It is not in a list/item environment
2149 found.keytype = KeyInfo::endArguments;
2152 if (found.keytype == KeyInfo::noMain) {
2153 evaluatingCode = true;
2155 codeStart = found._dataStart;
2157 else if (evaluatingCode) {
2158 if (size_t(found._dataStart) > codeEnd)
2159 evaluatingCode = false;
2160 else if (found.keytype == KeyInfo::isMain) {
2161 // Disable this key, treate it as standard
2162 found.keytype = KeyInfo::isStandard;
2163 found.disabled = true;
2164 if ((codeEnd +1 >= interval_.par.length()) &&
2165 (found._tokenstart == codeStart)) {
2166 // trickery, because the code inset starts
2167 // with \selectlanguage ...
2169 if (entries_.size() > 1) {
2170 entries_[entries_.size()-1]._dataEnd = codeEnd;
2175 if ((endpos == interval_.par.length()) &&
2176 (found.keytype == KeyInfo::doRemove)) {
2177 // Missing closing => error in latex-input?
2178 // therefore do not delete remaining data
2179 found._dataStart -= 1;
2180 found._dataEnd = found._dataStart;
2183 found._dataEnd = endpos;
2185 if (isPatternString) {
2186 keys[key].used = true;
2189 entries_.push_back(found);
2193 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2195 stringstream s(keysstring);
2197 const char delim = '|';
2198 while (getline(s, key, delim)) {
2199 KeyInfo keyII(keyI);
2200 if (isPatternString) {
2203 else if ( !keys[key].used)
2204 keyII.disabled = true;
2209 void LatexInfo::buildKeys(bool isPatternString)
2212 static bool keysBuilt = false;
2213 if (keysBuilt && !isPatternString) return;
2215 // Keys to ignore in any case
2216 makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2217 // Known standard keys with 1 parameter.
2218 // Split is done, if not at start of region
2219 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2220 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2221 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2222 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2223 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2224 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2226 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2227 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2228 makeKey("section*|subsection*|subsubsection*|paragraph*",
2229 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2230 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2231 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2233 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2235 // Split is done, if not at start of region
2236 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2237 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2239 // Split is done always.
2240 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2244 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2245 makeKey("braceleft|braceright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2246 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2247 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2248 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2250 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2251 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2252 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2253 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2255 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2256 // Custom space/skip, remove the content (== length value)
2257 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2258 // Found in fr/UserGuide.lyx
2259 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2261 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2262 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2263 // Known macros to remove (including their parameter)
2265 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2266 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2267 // handle like standard keys with 1 parameter.
2268 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2270 // Ignore deleted text
2271 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2272 // but preserve added text
2273 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2275 // Macros to remove, but let the parameter survive
2277 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2279 // Remove language spec from content of these insets
2280 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2282 // Same effect as previous, parameter will survive (because there is no one anyway)
2284 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2285 // Remove table decorations
2286 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2287 // Discard shape-header.
2288 // For footnote or shortcut too, because of lang settings
2289 // and wrong handling if used 'KeyInfo::noMain'
2290 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2291 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2292 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2293 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2294 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2295 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2296 // like ('tiny{}' or '\tiny ' ... )
2297 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2299 // Survives, like known character
2300 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2301 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2302 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2304 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2305 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2306 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2308 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2309 // Remove RTL/LTR marker
2310 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2311 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2312 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2313 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2314 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2315 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2316 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2317 if (isPatternString) {
2318 // Allow the first searched string to rebuild the keys too
2322 // no need to rebuild again
2328 * Keep the list of actual opened parentheses actual
2329 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2331 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2334 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2338 if (c == '\\') skip = 1;
2339 else if (c == '{') {
2342 else if (c == '}') {
2343 handleCloseP(i, closingAllowed);
2349 string Intervall::show(int lastpos)
2351 int idx = 0; /* int intervalls */
2354 for (idx = 0; idx <= ignoreidx; idx++) {
2355 while (i < lastpos) {
2357 if (i <= borders[idx].low) {
2358 if (borders[idx].low > lastpos)
2359 printsize = lastpos - i;
2361 printsize = borders[idx].low - i;
2362 s += par.substr(i, printsize);
2364 if (i >= borders[idx].low)
2365 i = borders[idx].upper;
2368 i = borders[idx].upper;
2374 s += par.substr(i, lastpos-i);
2380 void Intervall::output(ostringstream &os, int lastpos)
2382 // get number of chars to output
2383 int idx = 0; /* int intervalls */
2386 string startTitle = titleValue;
2387 for (idx = 0; idx <= ignoreidx; idx++) {
2389 if (i <= borders[idx].low) {
2391 if (borders[idx].low > lastpos)
2392 printsize = lastpos - i;
2394 printsize = borders[idx].low - i;
2395 if (printsize > 0) {
2396 os << startTitle << par.substr(i, printsize);
2398 printed += printsize;
2401 handleParentheses(i, false);
2402 if (i >= borders[idx].low)
2403 i = borders[idx].upper;
2406 i = borders[idx].upper;
2413 os << startTitle << par.substr(i, lastpos-i);
2414 printed += lastpos-i;
2416 handleParentheses(lastpos, false);
2418 if (keys["foreignlanguage"].disabled)
2419 startindex = actualdeptindex-langcount;
2421 startindex = actualdeptindex;
2422 for (int i = startindex; i > 0; --i) {
2425 if (hasTitle && (printed > 0))
2427 if (! isPatternString_)
2429 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2432 void LatexInfo::processRegion(int start, int region_end)
2434 while (start < region_end) { /* Let {[} and {]} survive */
2435 int cnt = interval_.isOpeningPar(start);
2437 // Closing is allowed past the region
2438 int closing = interval_.findclosing(start+1, interval_.par.length());
2439 interval_.addIntervall(start, start+1);
2440 interval_.addIntervall(closing, closing+1);
2444 start = interval_.nextNotIgnored(start+1);
2448 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2450 if (actual.parenthesiscount == 0) {
2451 // "{\tiny{} ...}" ==> "{{} ...}"
2452 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2455 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2456 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2457 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2461 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2464 switch (actual.keytype)
2466 case KeyInfo::isTitle: {
2468 nextKeyIdx = getNextKey();
2471 case KeyInfo::cleanToStart: {
2472 actual._dataEnd = actual._dataStart;
2473 nextKeyIdx = getNextKey();
2474 // Search for end of arguments
2475 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2477 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2478 entries_[i].disabled = true;
2480 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2482 while (interval_.par[actual._dataEnd] == ' ')
2484 interval_.addIntervall(0, actual._dataEnd+1);
2485 interval_.actualdeptindex = 0;
2486 interval_.depts[0] = actual._dataEnd+1;
2487 interval_.closes[0] = -1;
2490 case KeyInfo::isText:
2491 interval_.par[actual._tokenstart] = '#';
2492 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2493 nextKeyIdx = getNextKey();
2495 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2496 if (actual.disabled)
2497 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2499 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2502 case KeyInfo::isChar: {
2503 nextKeyIdx = getNextKey();
2506 case KeyInfo::isSize: {
2507 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2508 if (actual.parenthesiscount == 0)
2509 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2511 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2513 nextKeyIdx = getNextKey();
2515 // Here _dataStart points to '{', so correct it
2516 actual._dataStart += 1;
2517 actual._tokensize += 1;
2518 actual.parenthesiscount = 1;
2519 if (interval_.par[actual._dataStart] == '}') {
2520 // Determine the end if used like '{\tiny{}...}'
2521 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2522 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2525 // Determine the end if used like '\tiny{...}'
2526 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2528 // Split on this key if not at start
2529 int start = interval_.nextNotIgnored(previousStart);
2530 if (start < actual._tokenstart) {
2531 interval_.output(os, actual._tokenstart);
2532 interval_.addIntervall(start, actual._tokenstart);
2534 // discard entry if at end of actual
2535 nextKeyIdx = process(os, actual);
2539 case KeyInfo::endArguments: {
2540 // Remove trailing '{}' too
2541 actual._dataStart += 1;
2542 actual._dataEnd += 1;
2543 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2544 nextKeyIdx = getNextKey();
2547 case KeyInfo::noMain:
2549 case KeyInfo::isStandard: {
2550 if (actual.disabled) {
2552 processRegion(actual._dataStart, actual._dataStart+1);
2553 nextKeyIdx = getNextKey();
2555 // Split on this key if not at datastart of calling entry
2556 int start = interval_.nextNotIgnored(previousStart);
2557 if (start < actual._tokenstart) {
2558 interval_.output(os, actual._tokenstart);
2559 interval_.addIntervall(start, actual._tokenstart);
2561 // discard entry if at end of actual
2562 nextKeyIdx = process(os, actual);
2566 case KeyInfo::removeWithArg: {
2567 nextKeyIdx = getNextKey();
2568 // Search for end of arguments
2569 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2571 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2572 entries_[i].disabled = true;
2574 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2576 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2579 case KeyInfo::doRemove: {
2580 // Remove the key with all parameters and following spaces
2583 if (interval_.par[actual._dataEnd-1] == ' ')
2584 start = actual._dataEnd;
2586 start = actual._dataEnd+1;
2587 for (pos = start; pos < interval_.par.length(); pos++) {
2588 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2591 // Remove also enclosing parentheses [] and {}
2594 while (actual._tokenstart > numpars) {
2595 if (pos+numpars >= interval_.par.size())
2597 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2599 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2605 if (interval_.par[pos+numpars] == ' ')
2609 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2610 nextKeyIdx = getNextKey();
2613 case KeyInfo::isList: {
2614 // Discard space before _tokenstart
2616 for (count = 0; count < actual._tokenstart; count++) {
2617 if (interval_.par[actual._tokenstart-count-1] != ' ')
2620 nextKeyIdx = getNextKey();
2621 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2623 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2625 // How else can we catch this one?
2626 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2627 entries_[i].disabled = true;
2629 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2631 else if (nextKeyIdx > 0) {
2632 // Ignore any lang entries inside data region
2633 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2634 if (entries_[i].keytype == KeyInfo::isMain)
2635 entries_[i].disabled = true;
2638 if (actual.disabled) {
2639 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2642 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2644 if (interval_.par[actual._dataEnd+1] == '[') {
2645 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2646 if ((interval_.par[actual._dataEnd+2] == '{') &&
2647 (interval_.par[posdown-1] == '}')) {
2648 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2649 interval_.addIntervall(posdown-1, posdown+1);
2652 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2653 interval_.addIntervall(posdown, posdown+1);
2655 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2656 if (blk > posdown) {
2657 // Discard at most 1 space after empty item
2659 for (count = 0; count < 1; count++) {
2660 if (interval_.par[blk+count] != ' ')
2664 interval_.addIntervall(blk, blk+count);
2669 case KeyInfo::isSectioning: {
2670 // Discard spaces before _tokenstart
2672 int val = actual._tokenstart;
2673 for (count = 0; count < actual._tokenstart;) {
2674 val = interval_.previousNotIgnored(val-1);
2675 if (val < 0 || interval_.par[val] != ' ')
2678 count = actual._tokenstart - val;
2681 if (actual.disabled) {
2682 removeHead(actual, count);
2683 nextKeyIdx = getNextKey();
2685 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2686 nextKeyIdx = process(os, actual);
2690 case KeyInfo::isMath: {
2691 // Same as regex, use the content unchanged
2692 nextKeyIdx = getNextKey();
2695 case KeyInfo::isRegex: {
2696 // DO NOT SPLIT ON REGEX
2698 nextKeyIdx = getNextKey();
2701 case KeyInfo::isIgnored: {
2702 // Treat like a character for now
2703 nextKeyIdx = getNextKey();
2706 case KeyInfo::isMain: {
2707 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2708 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2709 if (actual._tokenstart > 0) {
2710 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2711 if ((prev >= 0) && interval_.par[prev] == '%')
2712 interval_.addIntervall(prev, prev+1);
2714 if (actual.disabled) {
2716 interval_.langcount++;
2717 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2718 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2719 // Discard also the space before math-equation
2720 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2722 nextKeyIdx = getNextKey();
2723 // interval.resetOpenedP(actual._dataStart-1);
2726 if (actual._tokenstart < 26) {
2727 // for the first (and maybe dummy) language
2728 interval_.setForDefaultLang(actual);
2730 interval_.resetOpenedP(actual._dataStart-1);
2734 case KeyInfo::invalid:
2735 case KeyInfo::headRemove:
2736 // These two cases cannot happen, already handled
2739 // LYXERR(Debug::INFO, "Unhandled keytype");
2740 nextKeyIdx = getNextKey();
2747 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2749 int end = interval_.nextNotIgnored(actual._dataEnd);
2750 int oldStart = actual._dataStart;
2751 int nextKeyIdx = getNextKey();
2753 if ((nextKeyIdx < 0) ||
2754 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2755 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2756 if (oldStart <= end) {
2757 processRegion(oldStart, end);
2762 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2764 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2765 (void) dispatch(os, actual._dataStart, nextKey);
2766 end = nextKey._tokenstart;
2769 processRegion(oldStart, nextKey._tokenstart);
2770 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2772 oldStart = nextKey._dataEnd+1;
2774 // now nextKey is either invalid or is outside of actual._dataEnd
2775 // output the remaining and discard myself
2776 if (oldStart <= end) {
2777 processRegion(oldStart, end);
2779 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2781 // This is the normal case.
2782 // But if using the firstlanguage, the closing may be missing
2784 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2786 if (actual._dataEnd < end)
2787 output_end = interval_.nextNotIgnored(actual._dataEnd);
2788 else if (interval_.par.size() > (size_t) end)
2789 output_end = interval_.nextNotIgnored(end);
2791 output_end = interval_.par.size();
2792 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2793 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2795 // Remove possible empty data
2796 int dstart = interval_.nextNotIgnored(actual._dataStart);
2797 while (interval_.isOpeningPar(dstart) == 1) {
2798 interval_.addIntervall(dstart, dstart+1);
2799 int dend = interval_.findclosing(dstart+1, output_end);
2800 interval_.addIntervall(dend, dend+1);
2801 dstart = interval_.nextNotIgnored(dstart+1);
2803 if (dstart < output_end)
2804 interval_.output(os, output_end);
2805 interval_.addIntervall(actual._tokenstart, end);
2809 string splitOnKnownMacros(string par, bool isPatternString)
2812 LatexInfo li(par, isPatternString);
2813 // LYXERR(Debug::INFO, "Berfore split: " << par);
2814 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2816 DummyKey._tokensize = 0;
2817 DummyKey._dataStart = 0;
2818 DummyKey._dataEnd = par.length();
2819 DummyKey.disabled = true;
2820 int firstkeyIdx = li.getFirstKey();
2822 if (firstkeyIdx >= 0) {
2823 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2824 DummyKey._tokenstart = firstKey._tokenstart;
2826 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2827 // Use dummy firstKey
2828 firstKey = DummyKey;
2829 (void) li.setNextKey(firstkeyIdx);
2832 if (par.substr(firstKey._dataStart, 2) == "% ")
2833 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2835 nextkeyIdx = li.process(os, firstKey);
2836 while (nextkeyIdx >= 0) {
2837 // Check for a possible gap between the last
2838 // entry and this one
2839 int datastart = li.nextNotIgnored(firstKey._dataStart);
2840 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2841 if ((nextKey._tokenstart > datastart)) {
2843 firstKey._dataStart = datastart;
2844 firstKey._dataEnd = par.length();
2845 (void) li.setNextKey(nextkeyIdx);
2846 // Fake the last opened parenthesis
2847 li.setForDefaultLang(firstKey);
2848 nextkeyIdx = li.process(os, firstKey);
2851 if (nextKey.keytype != KeyInfo::isMain) {
2852 firstKey._dataStart = datastart;
2853 firstKey._dataEnd = nextKey._dataEnd+1;
2854 (void) li.setNextKey(nextkeyIdx);
2855 li.setForDefaultLang(firstKey);
2856 nextkeyIdx = li.process(os, firstKey);
2859 nextkeyIdx = li.process(os, nextKey);
2863 // Handle the remaining
2864 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2865 firstKey._dataEnd = par.length();
2867 if ((firstKey._dataStart < firstKey._dataEnd) &&
2868 (par[firstKey._dataStart] != '}')) {
2869 li.setForDefaultLang(firstKey);
2870 (void) li.process(os, firstKey);
2874 // return string definitelly impossible to match
2875 s = "\\foreignlanguage{ignore}{ }";
2879 s = par; /* no known macros found */
2880 // LYXERR(Debug::INFO, "After split: " << s);
2885 * Try to unify the language specs in the latexified text.
2886 * Resulting modified string is set to "", if
2887 * the searched tex does not contain all the features in the search pattern
2889 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2891 static Features regex_f;
2892 static int missed = 0;
2893 static bool regex_with_format = false;
2895 int parlen = par.length();
2897 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2900 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2901 // Happens to be there in case of description or labeling environment
2906 // Split the latex input into pieces which
2907 // can be digested by our search engine
2908 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2909 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2910 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2913 result = par.substr(0, parlen);
2914 if (isPatternString) {
2917 regex_f = identifyFeatures(result);
2918 string features = "";
2919 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2920 string a = it->first;
2921 regex_with_format = true;
2922 features += " " + a;
2923 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2925 LYXERR(Debug::FIND, "Identified Features" << features);
2928 } else if (regex_with_format) {
2929 Features info = identifyFeatures(result);
2930 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2931 string a = it->first;
2932 bool b = it->second;
2933 if (b && ! info[a]) {
2935 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2942 // LYXERR(Debug::INFO, "No regex formats");
2948 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2949 static int identifyClosing(string & t)
2951 int open_braces = 0;
2953 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2954 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2956 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2958 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2960 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2969 static int num_replaced = 0;
2970 static bool previous_single_replace = true;
2972 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2975 // Handle \w properly
2976 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2977 if (! opt.casesensitive) {
2978 popts |= QRegularExpression::CaseInsensitiveOption;
2980 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2981 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2983 if (regexp.isValid() && regexp2.isValid()) {
2984 regexIsValid = true;
2985 // Check '{', '}' pairs inside the regex
2988 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2989 char c = par_as_string[i];
2996 else if (c == '}') {
3003 if (balanced != 0) {
3004 regexIsValid = false;
3005 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3009 regexIsValid = false;
3010 if (!regexp.isValid())
3011 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3013 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3016 if (opt.casesensitive) {
3017 regexp = regex(regexp_str);
3018 regexp2 = regex(regexp2_str);
3021 regexp = regex(regexp_str, std::regex_constants::icase);
3022 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3027 static void modifyRegexForMatchWord(string &t)
3030 regex wordre("(\\\\)*((\\.|\\\\b))");
3033 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3035 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3038 else if (sub.str(2) == "\\\\b")
3040 if (lastpos < (size_t) sub.position(2))
3041 s += t.substr(lastpos, sub.position(2) - lastpos);
3043 lastpos = sub.position(2) + sub.length(2);
3046 s = "\\b" + t + "\\b";
3050 else if (lastpos < t.length())
3051 s += t.substr(lastpos, t.length() - lastpos);
3052 t = "\\b" + s + "\\b";
3055 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3056 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3058 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3059 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3060 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3061 if (opt.replace_all && previous_single_replace) {
3062 previous_single_replace = false;
3065 else if (!opt.replace_all) {
3066 num_replaced = 0; // count number of replaced strings
3067 previous_single_replace = true;
3069 // When using regexp, braces are hacked already by escape_for_regex()
3070 par_as_string = normalize(ds);
3072 close_wildcards = 0;
3074 size_t lead_size = 0;
3075 // correct the language settings
3076 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
3077 opt.matchstart = false;
3079 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3080 if (opt.ignoreformat) {
3084 lead_size = identifyLeading(par_as_string);
3086 lead_as_string = par_as_string.substr(0, lead_size);
3087 string lead_as_regex_string = string2regex(lead_as_string);
3088 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3089 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3090 /* Handle whole words too in this case
3092 if (opt.matchword) {
3093 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3094 opt.matchword = false;
3096 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3097 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3098 CreateRegexp(opt, regexp_str, regexp2_str);
3100 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3101 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3105 if (!opt.ignoreformat) {
3106 lead_size = identifyLeading(par_as_string);
3107 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3108 lead_as_string = par_as_string.substr(0, lead_size);
3109 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3112 // Here we are using regexp
3113 LASSERT(use_regexp, /**/);
3115 string lead_as_regexp;
3116 if (lead_size > 0) {
3117 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3118 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3119 par_as_string = par_as_string_nolead;
3120 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3121 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3123 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3124 par_as_string = escape_for_regex(par_as_string);
3125 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3126 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3127 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3129 size_t lng = par_as_string.size();
3130 if (!opt.ignoreformat) {
3131 // Remove extra '\}' at end if not part of \{\.\}
3133 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3135 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3144 if (lng < par_as_string.size())
3145 par_as_string = par_as_string.substr(0,lng);
3147 if ((lng > 0) && (par_as_string[0] == '^')) {
3148 par_as_string = par_as_string.substr(1);
3150 opt.matchstart = true;
3152 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3153 LYXERR(Debug::FIND, "Open braces: " << open_braces);
3154 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3156 // If entered regexp must match at begin of searched string buffer
3157 // Kornel: Added parentheses to use $1 for size of the leading string
3161 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3162 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3163 // so the convert has no effect in that case
3164 for (int i = 7; i > 0; --i) {
3165 string orig = "\\\\" + std::to_string(i);
3166 string dest = "\\" + std::to_string(i+2);
3167 while (regex_replace(par_as_string, par_as_string, orig, dest));
3169 if (opt.matchword) {
3170 modifyRegexForMatchWord(par_as_string);
3171 opt.matchword = false;
3173 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3174 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3176 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3177 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3178 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3183 // Count number of characters in string
3187 // \\[a-zA-Z]+ ==> 1
3189 static int computeSize(QStringRef s, int len)
3190 #define isLyxAlpha(arg) arg.isLetter()
3192 static int computeSize(string s, int len)
3193 #define isLyxAlpha(arg) isalpha(arg)
3200 for (int i = 0; i < len; i += skip, count++) {
3201 if (s.at(i) == '\\') {
3203 if (i + 1 < len && isLyxAlpha(s.at(i+1))) {
3204 for (int j = 2; i+j < len; j++) {
3205 if (! isLyxAlpha(s.at(i+j))) {
3206 if (s.at(i+j) == ' ')
3208 else if (s.at(i+j) == '{') {
3209 if (i+j+1 < len && s.at(i+j+1) == '}')
3211 else if (i + j + 1 >= len)
3220 else if (s.at(i) == '{') {
3221 if (i + 1 < len && s.at(i+1) == '}')
3226 else if (s.at(i) == '-') {
3227 if (i+1 < len && s.at(i+1) == '-') {
3228 if (i + 2 < len && s.at(i+2) == '-')
3244 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3248 mres.searched_size = len;
3250 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3253 docstring docstr = stringifyFromForSearch(opt, cur, len);
3255 if (use_regexp || opt.casesensitive)
3256 str = normalize(docstr);
3258 str = normalize(lowercase(docstr));
3259 if (!opt.ignoreformat) {
3260 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3263 mres.match_len = -1;
3266 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
3267 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3270 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3272 QString qstr = QString::fromStdString(str);
3273 QRegularExpression const *p_regexp;
3274 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3278 p_regexp = ®exp2;
3280 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3281 if (!match.hasMatch())
3284 regex const *p_regexp;
3285 regex_constants::match_flag_type flags;
3287 flags = regex_constants::match_continuous;
3290 flags = regex_constants::match_default;
3291 p_regexp = ®exp2;
3293 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3294 if (re_it == sregex_iterator())
3296 match_results<string::const_iterator> const & m = *re_it;
3298 // Whole found string, including the leading
3299 // std: m[0].second - m[0].first
3300 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3302 // Size of the leading string
3303 // std: m[1].second - m[1].first
3304 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3305 int leadingsize = 0;
3307 if (match.lastCapturedIndex() > 0) {
3308 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3313 leadingsize = m[1].second - m[1].first;
3317 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3318 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3319 // because of different number of closing at end of string
3320 // we have to 'unify' the length of the post-match.
3321 // Done by ignoring closing parenthesis and linefeeds at string end
3322 int matchend = match.capturedEnd(0);
3323 while (mres.match_len > 0) {
3324 QChar c = qstr.at(matchend - 1);
3332 size_t strsize = qstr.size();
3333 while (strsize > (size_t) match.capturedEnd(0)) {
3334 QChar c = qstr.at(strsize-1);
3335 if ((c == '\n') || (c == '}')) {
3341 // LYXERR0(qstr.toStdString());
3342 mres.match2end = strsize - matchend;
3343 mres.pos = match.capturedStart(2);
3345 mres.match_prefix = m[2].second - m[2].first;
3346 mres.match_len = m[0].second - m[2].second;
3347 // ignore closing parenthesis and linefeeds at string end
3348 size_t strend = m[0].second - m[0].first;
3349 int matchend = strend;
3350 while (mres.match_len > 0) {
3351 char c = str.at(matchend - 1);
3352 if ((c == '\n') || (c == '}') || (c == '{')) {
3359 size_t strsize = str.size();
3360 while (strsize > strend) {
3361 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3368 mres.match2end = strsize - matchend;
3369 mres.pos = m[2].first - m[0].first;;
3371 if (mres.match2end < 0)
3373 mres.leadsize = leadingsize;
3375 if (mres.match_len > 0) {
3376 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3377 mres.result.push_back(a0);
3378 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3379 mres.result.push_back(match.captured(i).toStdString());
3383 if (mres.match_len > 0) {
3384 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3385 mres.result.push_back(a0);
3386 for (size_t i = 3; i < m.size(); i++) {
3387 mres.result.push_back(m[i]);
3394 // else !use_regexp: but all code paths above return
3395 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3396 << par_as_string << "', str='" << str << "'");
3397 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3398 << lead_as_string << "', par_as_string_nolead='"
3399 << par_as_string_nolead << "'");
3402 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3403 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3404 if (str.substr(0, par_as_string.size()) == par_as_string) {
3405 mres.match_len = par_as_string.size();
3406 mres.match2end = str.size();
3411 // Start the search _after_ the leading part
3412 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3413 if (pos != string::npos) {
3414 mres.match_len = par_as_string.size();
3415 mres.match2end = str.size() - pos;
3424 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3426 MatchResult mres = findAux(cur, len, at_begin);
3427 int res = mres.match_len;
3429 "res=" << res << ", at_begin=" << at_begin
3430 << ", matchstart=" << opt.matchstart
3431 << ", inTexted=" << cur.inTexted());
3432 if (opt.matchstart) {
3435 else if (mres.match_prefix > 0)
3444 static bool simple_replace(string &t, string from, string to)
3446 regex repl("(\\\\)*(" + from + ")");
3450 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3452 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3454 if (lastpos < (size_t) sub.position(2))
3455 s += t.substr(lastpos, sub.position(2) - lastpos);
3457 lastpos = sub.position(2) + sub.length(2);
3461 else if (lastpos < t.length())
3462 s += t.substr(lastpos, t.length() - lastpos);
3468 string MatchStringAdv::normalize(docstring const & s) const
3471 t = lyx::to_utf8(s);
3472 // Remove \n at begin
3473 while (!t.empty() && t[0] == '\n')
3476 while (!t.empty() && t[t.size() - 1] == '\n')
3477 t = t.substr(0, t.size() - 1);
3479 // Handle all other '\n'
3480 while ((pos = t.find("\n")) != string::npos) {
3481 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3483 if (isAlnumASCII(t[pos+1])) {
3484 t.replace(pos-2, 3, " ");
3487 t.replace(pos-2, 3, "");
3490 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3491 // '\n' adjacent to non-alpha-numerics, discard
3492 t.replace(pos, 1, "");
3495 // Replace all other \n with spaces
3496 t.replace(pos, 1, " ");
3499 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3500 // Kornel: Added textsl, textsf, textit, texttt and noun
3501 // + allow to seach for colored text too
3502 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3503 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3504 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3505 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3506 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3507 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3513 docstring stringifyFromCursor(DocIterator const & cur, int len)
3515 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3516 if (cur.inTexted()) {
3517 Paragraph const & par = cur.paragraph();
3518 // TODO what about searching beyond/across paragraph breaks ?
3519 // TODO Try adding a AS_STR_INSERTS as last arg
3520 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3521 int(par.size()) : cur.pos() + len;
3522 // OutputParams runparams(&cur.buffer()->params().encoding());
3523 OutputParams runparams(encodings.fromLyXName("utf8"));
3524 runparams.nice = true;
3525 runparams.flavor = Flavor::XeTeX;
3526 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3527 // No side effect of file copying and image conversion
3528 runparams.dryrun = true;
3529 runparams.for_search = true;
3530 LYXERR(Debug::FIND, "Stringifying with cur: "
3531 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3532 return par.asString(cur.pos(), end,
3533 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3535 } else if (cur.inMathed()) {
3536 CursorSlice cs = cur.top();
3537 MathData md = cs.cell();
3538 MathData::const_iterator it_end =
3539 (( len == -1 || cs.pos() + len > int(md.size()))
3541 : md.begin() + cs.pos() + len );
3543 for (MathData::const_iterator it = md.begin() + cs.pos();
3546 docstring s = asString(md2);
3547 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3550 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3555 /** Computes the LaTeX export of buf starting from cur and ending len positions
3556 * after cur, if len is positive, or at the paragraph or innermost inset end
3559 docstring latexifyFromCursor(DocIterator const & cur, int len)
3561 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3562 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3563 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3564 Buffer const & buf = *cur.buffer();
3566 odocstringstream ods;
3568 //OutputParams runparams(&buf.params().encoding());
3569 OutputParams runparams(encodings.fromLyXName("utf8"));
3570 runparams.nice = false;
3571 runparams.flavor = Flavor::XeTeX;
3572 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3573 // No side effect of file copying and image conversion
3574 runparams.dryrun = true;
3575 runparams.for_search = true;
3577 if (cur.inTexted()) {
3578 // @TODO what about searching beyond/across paragraph breaks ?
3579 pos_type endpos = cur.paragraph().size();
3580 if (len != -1 && endpos > cur.pos() + len)
3581 endpos = cur.pos() + len;
3582 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3583 string(), cur.pos(), endpos);
3584 string s = lyx::to_utf8(ods.str());
3585 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3586 return(lyx::from_utf8(s));
3587 } else if (cur.inMathed()) {
3588 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3589 for (int s = cur.depth() - 1; s >= 0; --s) {
3590 CursorSlice const & cs = cur[s];
3591 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3592 TeXMathStream ws(os);
3593 cs.asInsetMath()->asHullInset()->header_write(ws);
3598 CursorSlice const & cs = cur.top();
3599 MathData md = cs.cell();
3600 MathData::const_iterator it_end =
3601 ((len == -1 || cs.pos() + len > int(md.size()))
3603 : md.begin() + cs.pos() + len);
3605 for (MathData::const_iterator it = md.begin() + cs.pos();
3609 ods << asString(md2);
3610 // Retrieve the math environment type, and add '$' or '$]'
3611 // or others (\end{equation}) accordingly
3612 for (int s = cur.depth() - 1; s >= 0; --s) {
3613 CursorSlice const & cs2 = cur[s];
3614 InsetMath * inset = cs2.asInsetMath();
3615 if (inset && inset->asHullInset()) {
3616 TeXMathStream ws(os);
3617 inset->asHullInset()->footer_write(ws);
3621 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3623 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3628 #if defined(ResultsDebug)
3630 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3632 LYXERR0( "from:\t\t\t" << from);
3634 if (mres.pos_len > 0) {
3636 status = "FINALSEARCH";
3639 if (mres.match_len > 0) {
3640 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3641 status = "Good Match";
3643 status = "Matched in";
3646 status = "MissedSearch";
3649 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3650 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3651 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3652 if ((mres.pos > 0) || (mres.match_prefix > 0))
3653 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3654 for (size_t i = 0; i < mres.result.size(); i++)
3655 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3657 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3659 #define displayMres(s, txt, cur)
3662 /** Finalize an advanced find operation, advancing the cursor to the innermost
3663 ** position that matches, plus computing the length of the matching text to
3665 ** Return the cur.pos() difference between start and end of found match
3667 MatchResult &findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3669 // Search the foremost position that matches (avoids find of entire math
3670 // inset when match at start of it)
3671 DocIterator old_cur(cur.buffer());
3673 static MatchResult fail = MatchResult();
3674 static MatchResult max_match;
3675 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3676 // Happens with e.g. hyperlinks
3677 // either one sees "http://www.bla.bla" or nothing
3678 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3679 // and although we search for only 3 chars, we find the whole hyperlink inset
3680 bool at_begin = (expected.match_prefix == 0);
3681 LASSERT(at_begin, /**/);
3682 if (expected.match_len > 0 && at_begin) {
3683 // Search for deepest match
3685 max_match = expected;
3687 size_t d = cur.depth();
3691 if (cur.depth() < d)
3693 if (cur.depth() == d)
3696 while (cur && cur.depth() > lastd) {
3697 lastd = cur.depth();
3698 mres = match(cur, -1, at_begin);
3699 displayMres(mres, "Checking innermost", cur);
3700 if (mres.match_len > 0)
3705 if (mres.match_len < expected.match_len)
3713 // (expected.match_len <= 0)
3714 mres = match(cur); /* match valid only if not searching whole words */
3715 displayMres(mres, "Start with negative match", cur);
3718 if (max_match.match_len <= 0) return fail;
3719 LYXERR(Debug::FIND, "Ok");
3721 // Compute the match length
3723 if (cur.pos() + len > cur.lastpos())
3725 // regexp should use \w+, \S+, or \b(some string)\b
3726 // to search for whole words
3727 if (match.opt.matchword && !match.use_regexp) {
3728 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3729 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3731 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3733 // Length of matched text (different from len param)
3734 static MatchResult old_match = match(cur, len, at_begin);
3735 if (old_match.match_len < 0)
3737 MatchResult new_match;
3738 // Greedy behaviour while matching regexps
3739 while ((new_match = match(cur, len + 1, at_begin)).match_len > old_match.match_len) {
3741 old_match = new_match;
3742 LYXERR(Debug::FIND, "verifying match with len = " << len);
3744 displayMres(old_match, "SEARCH RESULT", cur)
3749 int maxl = cur.lastpos() - cur.pos();
3750 // Greedy behaviour while matching regexps
3751 while (maxl > minl) {
3753 mres2 = match(cur, len, at_begin);
3754 displayMres(mres2, "Finalize loop", cur);
3755 int actual_match_len = mres2.match_len;
3756 if (actual_match_len >= max_match.match_len) {
3757 // actual_match_len > max_match _can_ happen,
3758 // if the search area splits
3759 // some following word so that the regex
3760 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3762 // This means, the len value is too big
3763 actual_match_len = max_match.match_len;
3765 max_match.match_len = actual_match_len;
3767 if (maxl - minl < 4)
3768 len = (int)((maxl + minl)/2);
3770 len = (int)(minl + (maxl - minl + 3)/4);
3773 // (actual_match_len < max_match.match_len)
3775 len = (int)((maxl + minl)/2);
3780 // Search for real start of matched characters
3782 MatchResult actual_match;
3785 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3786 if (cur.depth() < old_cur.depth()) {
3788 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3791 if (cur.pos() != old_cur.pos()) {
3792 // OK, forwarded 1 pos in actual inset
3793 actual_match = match(cur, len-1, at_begin);
3794 if (actual_match.match_len == max_match.match_len) {
3795 // Ha, got it! The shorter selection has the same match length
3798 max_match = actual_match;
3801 // OK, the shorter selection matches less chars, revert to previous value
3807 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3808 actual_match = match(cur, len, at_begin);
3809 if (actual_match.match_len == max_match.match_len) {
3811 max_match = actual_match;
3818 max_match.pos_len = len;
3819 displayMres(max_match, "SEARCH RESULT", cur)
3826 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3830 bool repeat = false;
3831 while (!theApp()->longOperationCancelled() && cur) {
3832 //(void) findAdvForwardInnermost(cur);
3833 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3834 MatchResult mres = match(cur, -1, false);
3835 string msg = "Starting";
3838 displayMres(mres, msg + " findForwardAdv", cur)
3839 int match_len = mres.match_len;
3840 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3841 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3844 if (match_len <= 0) {
3845 // This should exit nested insets, if any, or otherwise undefine the currsor.
3846 cur.pos() = cur.lastpos();
3847 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3850 else { // match_len > 0
3851 // Try to find the begin of searched string
3853 int firstInvalid = 100000;
3855 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3856 int incrcur = (cur.lastpos() - cur.pos() + 1 )*3/4;
3857 if (incrcur < incrmatch)
3858 increment = incrcur;
3860 increment = incrmatch;
3864 LYXERR(Debug::FIND, "Set increment to " << increment);
3865 while (increment > 0) {
3866 DocIterator old_cur = cur;
3867 size_t skipping = cur.depth();
3868 for (int i = 0; i < increment && cur; i++) {
3870 while (cur && cur.depth() > skipping) {
3871 cur.pos() = cur.lastpos();
3875 if (! cur || (cur.pit() > old_cur.pit())) {
3876 // Are we outside of the paragraph?
3877 // This can happen if moving past some UTF8-encoded chars
3882 MatchResult mres2 = match(cur, -1, false);
3883 displayMres(mres2, "findForwardAdv loop", cur)
3884 switch (interpretMatch(mres, mres2)) {
3885 case MatchResult::newIsTooFar:
3886 // behind the expected match
3887 firstInvalid = increment;
3891 case MatchResult::newIsBetter:
3892 // not reached yet, but cur.pos()+increment is bettert
3894 firstInvalid -= increment;
3895 if (increment > firstInvalid*3/4)
3896 increment = firstInvalid*3/4;
3897 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3898 if (increment >= mres2.match_prefix)
3899 increment = (mres2.match_prefix+1)*3/4;
3904 // Handle not like MatchResult::newIsTooFar
3905 LYXERR0( "Something is wrong: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3907 increment = increment*3/4;
3913 if (mres.match_len > 0 && mres.match_prefix + mres.pos - mres.leadsize > 0) {
3918 // LYXERR0("Leaving first loop");
3919 LYXERR(Debug::FIND, "Finalizing 1");
3920 MatchResult found_match = findAdvFinalize(cur, match, mres);
3921 if (found_match.match_len > 0) {
3922 LASSERT(found_match.pos_len > 0, /**/);
3923 match.FillResults(found_match);
3924 return found_match.pos_len;
3927 // try next possible match
3938 /// Find the most backward consecutive match within same paragraph while searching backwards.
3939 MatchResult &findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3941 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3942 DocIterator tmp_cur = cur;
3943 static MatchResult mr = findAdvFinalize(tmp_cur, match, MatchResult(-1));
3944 Inset & inset = cur.inset();
3945 for (; cur != cur_begin; cur.backwardPos()) {
3946 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3947 DocIterator new_cur = cur;
3948 new_cur.backwardPos();
3949 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3951 MatchResult new_mr = findAdvFinalize(new_cur, match, MatchResult(-1));
3952 if (new_mr.match_len == mr.match_len)
3956 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3962 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3966 // Backup of original position
3967 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3968 if (cur == cur_begin)
3971 DocIterator cur_orig(cur);
3972 bool pit_changed = false;
3975 bool found_match = (match(cur, -1, false).match_len > 0);
3979 cur.pos() = cur.lastpos();
3981 cur.pos() = cur_orig.pos();
3982 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3983 DocIterator cur_prev_iter;
3985 found_match = (match(cur).match_len > 0);
3986 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3987 << found_match << ", cur: " << cur);
3989 MatchResult found_mr = findMostBackwards(cur, match);
3990 match.FillResults(found_mr);
3991 LASSERT(found_mr.pos_len > 0, /**/);
3992 return found_mr.pos_len;
3995 // Stop if begin of document reached
3996 if (cur == cur_begin)
3998 cur_prev_iter = cur;
4002 if (cur == cur_begin)
4009 } while (!theApp()->longOperationCancelled());
4017 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4018 DocIterator const & cur, int len)
4020 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4022 if (!opt.ignoreformat)
4023 return latexifyFromCursor(cur, len);
4025 return stringifyFromCursor(cur, len);
4029 FindAndReplaceOptions::FindAndReplaceOptions(
4030 docstring const & _find_buf_name, bool _casesensitive,
4031 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4032 docstring const & _repl_buf_name, bool _keep_case,
4033 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4034 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4035 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4036 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4044 /** Check if 'len' letters following cursor are all non-lowercase */
4045 static bool allNonLowercase(Cursor const & cur, int len)
4047 pos_type beg_pos = cur.selectionBegin().pos();
4048 pos_type end_pos = cur.selectionBegin().pos() + len;
4049 if (len > cur.lastpos() + 1 - beg_pos) {
4050 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4051 len = cur.lastpos() + 1 - beg_pos;
4052 end_pos = beg_pos + len;
4054 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4055 if (isLowerCase(cur.paragraph().getChar(pos)))
4061 /** Check if first letter is upper case and second one is lower case */
4062 static bool firstUppercase(Cursor const & cur)
4065 pos_type pos = cur.selectionBegin().pos();
4066 if (pos >= cur.lastpos() - 1) {
4067 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4070 ch1 = cur.paragraph().getChar(pos);
4071 ch2 = cur.paragraph().getChar(pos + 1);
4072 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4073 LYXERR(Debug::FIND, "firstUppercase(): "
4074 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4075 << ch2 << "(" << char(ch2) << ")"
4076 << ", result=" << result << ", cur=" << cur);
4081 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4083 ** \fixme What to do with possible further paragraphs in replace buffer ?
4085 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4087 ParagraphList::iterator pit = buffer.paragraphs().begin();
4088 LASSERT(!pit->empty(), /**/);
4089 pos_type right = pos_type(1);
4090 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4091 right = pit->size();
4092 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4097 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4099 // Should replace the string "$" + std::to_string(matchnum) with replacement
4100 // if the char '$' is not prefixed with odd number of char '\\'
4101 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4105 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4107 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4109 int num = stoi(sub.str(3), nullptr, 10);
4110 if (num >= maxmatchnum)
4112 if (lastpos < (size_t) sub.position(2))
4113 s += t.substr(lastpos, sub.position(2) - lastpos);
4114 s += replacements[num];
4115 lastpos = sub.position(2) + sub.length(2);
4119 else if (lastpos < t.length())
4120 s += t.substr(lastpos, t.length() - lastpos);
4127 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4129 Cursor & cur = bv->cursor();
4130 if (opt.repl_buf_name.empty()
4131 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4132 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4135 DocIterator sel_beg = cur.selectionBegin();
4136 DocIterator sel_end = cur.selectionEnd();
4137 if (&sel_beg.inset() != &sel_end.inset()
4138 || sel_beg.pit() != sel_end.pit()
4139 || sel_beg.idx() != sel_end.idx())
4141 int sel_len = sel_end.pos() - sel_beg.pos();
4142 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4143 << ", sel_len: " << sel_len << endl);
4146 LASSERT(sel_len > 0, return 0);
4148 if (!matchAdv(sel_beg, sel_len).match_len)
4151 // Build a copy of the replace buffer, adapted to the KeepCase option
4152 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4154 repl_buffer_orig.write(oss);
4155 string lyx = oss.str();
4156 if (matchAdv.valid_matches > 0) {
4157 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4159 Buffer repl_buffer("", false);
4160 repl_buffer.setUnnamed(true);
4161 LASSERT(repl_buffer.readString(lyx), return 0);
4162 if (opt.keep_case && sel_len >= 2) {
4163 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4164 if (cur.inTexted()) {
4165 if (firstUppercase(cur))
4166 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4167 else if (allNonLowercase(cur, sel_len))
4168 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4171 cap::cutSelection(cur, false);
4172 if (cur.inTexted()) {
4173 repl_buffer.changeLanguage(
4174 repl_buffer.language(),
4175 cur.getFont().language());
4176 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4177 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4178 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4179 repl_buffer.params().documentClassPtr(),
4180 bv->buffer().errorList("Paste"));
4181 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4182 sel_len = repl_buffer.paragraphs().begin()->size();
4183 } else if (cur.inMathed()) {
4184 odocstringstream ods;
4186 // OutputParams runparams(&repl_buffer.params().encoding());
4187 OutputParams runparams(encodings.fromLyXName("utf8"));
4188 runparams.nice = false;
4189 runparams.flavor = Flavor::XeTeX;
4190 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4191 runparams.dryrun = true;
4192 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4193 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4194 docstring repl_latex = ods.str();
4195 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4197 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4198 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4199 repl_latex = from_utf8(s);
4200 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4201 MathData ar(cur.buffer());
4202 asArray(repl_latex, ar, Parse::NORMAL);
4204 sel_len = ar.size();
4205 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4207 if (cur.pos() >= sel_len)
4208 cur.pos() -= sel_len;
4211 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4212 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4213 bv->processUpdateFlags(Update::Force);
4218 /// Perform a FindAdv operation.
4219 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4224 // e.g., when invoking word-findadv from mini-buffer wither with
4225 // wrong options syntax or before ever opening advanced F&R pane
4226 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4230 MatchStringAdv matchAdv(bv->buffer(), opt);
4232 if (!matchAdv.regexIsValid) {
4233 bv->message(lyx::from_utf8(matchAdv.regexError));
4237 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4239 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4240 num_replaced += findAdvReplace(bv, opt, matchAdv);
4243 pos_len = findForwardAdv(cur, matchAdv);
4245 pos_len = findBackwardsAdv(cur, matchAdv);
4246 } catch (exception & ex) {
4247 bv->message(from_utf8(ex.what()));
4252 if (num_replaced > 0) {
4253 switch (num_replaced)
4256 bv->message(_("One match has been replaced."));
4259 bv->message(_("Two matches have been replaced."));
4262 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4268 bv->message(_("Match not found."));
4273 if (num_replaced > 0)
4274 bv->message(_("Match has been replaced."));
4276 bv->message(_("Match found."));
4278 if (cur.pos() + pos_len > cur.lastpos()) {
4279 // Prevent crash in bv->putSelectionAt()
4280 // Should never happen, maybe LASSERT() here?
4281 pos_len = cur.lastpos() - cur.pos();
4283 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4284 bv->putSelectionAt(cur, pos_len, !opt.forward);
4290 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4292 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4293 << opt.casesensitive << ' '
4294 << opt.matchword << ' '
4295 << opt.forward << ' '
4296 << opt.expandmacros << ' '
4297 << opt.ignoreformat << ' '
4298 << opt.replace_all << ' '
4299 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4300 << opt.keep_case << ' '
4301 << int(opt.scope) << ' '
4304 LYXERR(Debug::FIND, "built: " << os.str());
4310 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4312 LYXERR(Debug::FIND, "parsing");
4316 while (line != "EOSS") {
4320 if (is.eof()) // Tolerate malformed request
4324 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4325 opt.find_buf_name = from_utf8(s);
4326 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4327 is.get(); // Waste space before replace string
4330 while (line != "EOSS") {
4334 if (is.eof()) // Tolerate malformed request
4338 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4339 opt.repl_buf_name = from_utf8(s);
4340 is >> opt.keep_case;
4343 opt.scope = FindAndReplaceOptions::SearchScope(i);
4345 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4347 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4348 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4349 << opt.scope << ' ' << opt.restr);