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"
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathData.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/FileName.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
53 #include <unordered_map>
56 //#define ResultsDebug
57 #define USE_QT_FOR_SEARCH
58 #if defined(USE_QT_FOR_SEARCH)
59 #include <QtCore> // sets QT_VERSION
60 #if (QT_VERSION >= 0x050000)
61 #include <QRegularExpression>
71 using namespace lyx::support;
75 typedef unordered_map<string, string> AccentsMap;
76 typedef unordered_map<string,string>::const_iterator AccentsIterator;
77 static AccentsMap accents = unordered_map<string, string>();
79 // Helper class for deciding what should be ignored
83 IgnoreFormats() = default;
85 bool getFamily() const { return ignoreFamily_; }
87 bool getSeries() const { return ignoreSeries_; }
89 bool getShape() const { return ignoreShape_; }
91 bool getUnderline() const { return ignoreUnderline_; }
93 bool getMarkUp() const { return ignoreMarkUp_; }
95 bool getStrikeOut() const { return ignoreStrikeOut_; }
97 bool getSectioning() const { return ignoreSectioning_; }
99 bool getFrontMatter() const { return ignoreFrontMatter_; }
101 bool getColor() const { return ignoreColor_; }
103 bool getLanguage() const { return ignoreLanguage_; }
105 bool getDeleted() const { return ignoreDeleted_; }
107 void setIgnoreDeleted(bool value);
109 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreUnderline_ = false;
121 bool ignoreMarkUp_ = false;
123 bool ignoreStrikeOut_ = false;
125 bool ignoreSectioning_ = false;
127 bool ignoreFrontMatter_ = false;
129 bool ignoreColor_ = false;
131 bool ignoreLanguage_ = false;
132 bool userSelectedIgnoreLanguage_ = false;
134 bool ignoreDeleted_ = true;
137 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
139 if (type == "color") {
140 ignoreColor_ = value;
142 else if (type == "language") {
144 userSelectedIgnoreLanguage_ = value;
145 ignoreLanguage_ = value;
148 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
150 else if (type == "sectioning") {
151 ignoreSectioning_ = value;
152 ignoreFrontMatter_ = value;
154 else if (type == "font") {
155 ignoreSeries_ = value;
156 ignoreShape_ = value;
157 ignoreFamily_ = value;
159 else if (type == "series") {
160 ignoreSeries_ = value;
162 else if (type == "shape") {
163 ignoreShape_ = value;
165 else if (type == "family") {
166 ignoreFamily_ = value;
168 else if (type == "markup") {
169 ignoreMarkUp_ = value;
171 else if (type == "underline") {
172 ignoreUnderline_ = value;
174 else if (type == "strike") {
175 ignoreStrikeOut_ = value;
177 else if (type == "deleted") {
178 ignoreDeleted_ = value;
182 // The global variable that can be changed from outside
183 IgnoreFormats ignoreFormats;
186 void setIgnoreFormat(string const & type, bool value, bool fromUser)
188 ignoreFormats.setIgnoreFormat(type, value, fromUser);
194 bool parse_bool(docstring & howto, bool const defvalue = false)
199 howto = split(howto, var, ' ');
207 MatchString(docstring const & s, bool cs, bool mw)
208 : str(s), case_sens(cs), whole_words(mw)
211 // returns true if the specified string is at the specified position
212 // del specifies whether deleted strings in ct mode will be considered
213 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
215 return par.find(str, case_sens, whole_words, pos, del);
223 // match whole words only
228 int findForward(DocIterator & cur, MatchString const & match,
229 bool find_del = true)
231 for (; cur; cur.forwardChar())
232 if (cur.inTexted()) {
233 int len = match(cur.paragraph(), cur.pos(), find_del);
241 int findBackwards(DocIterator & cur, MatchString const & match,
242 bool find_del = true)
246 if (cur.inTexted()) {
247 int len = match(cur.paragraph(), cur.pos(), find_del);
256 bool searchAllowed(docstring const & str)
259 frontend::Alert::error(_("Search error"), _("Search string is empty"));
268 bool findOne(BufferView * bv, docstring const & searchstr,
269 bool case_sens, bool whole, bool forward,
270 bool find_del, bool check_wrap, bool auto_wrap,
273 if (!searchAllowed(searchstr))
276 DocIterator cur = forward
277 ? (instant ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
278 : (instant ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
280 MatchString const match(searchstr, case_sens, whole);
282 int match_len = forward
283 ? findForward(cur, match, find_del)
284 : findBackwards(cur, match, find_del);
287 bv->putSelectionAt(cur, match_len, !forward);
288 else if (check_wrap) {
289 DocIterator cur_orig(bv->cursor());
293 q = _("End of file reached while searching forward.\n"
294 "Continue searching from the beginning?");
296 q = _("Beginning of file reached while searching backward.\n"
297 "Continue searching from the end?");
298 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
299 q, 0, 1, _("&Yes"), _("&No"));
300 auto_wrap = wrap_answer == 0;
304 bv->cursor().clear();
305 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
307 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
308 bv->cursor().backwardPos();
310 bv->clearSelection();
311 if (findOne(bv, searchstr, case_sens, whole, forward,
312 find_del, false, false, false))
315 bv->cursor().setCursor(cur_orig);
319 return match_len > 0;
325 int replaceAll(BufferView * bv,
326 docstring const & searchstr, docstring const & replacestr,
327 bool case_sens, bool whole)
329 Buffer & buf = bv->buffer();
331 if (!searchAllowed(searchstr) || buf.isReadonly())
334 DocIterator cur_orig(bv->cursor());
336 MatchString const match(searchstr, case_sens, whole);
339 int const rsize = replacestr.size();
340 int const ssize = searchstr.size();
343 cur.setCursor(doc_iterator_begin(&buf));
344 int match_len = findForward(cur, match, false);
345 while (match_len > 0) {
346 // Backup current cursor position and font.
347 pos_type const pos = cur.pos();
348 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
350 int striked = ssize -
351 cur.paragraph().eraseChars(pos, pos + match_len,
352 buf.params().track_changes);
353 cur.paragraph().insert(pos, replacestr, font,
354 Change(buf.params().track_changes
356 : Change::UNCHANGED));
357 for (int i = 0; i < rsize + striked; ++i)
360 match_len = findForward(cur, match, false);
363 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
365 cur_orig.fixIfBroken();
366 bv->setCursor(cur_orig);
372 // the idea here is that we are going to replace the string that
373 // is selected IF it is the search string.
374 // if there is a selection, but it is not the search string, then
375 // we basically ignore it. (FIXME We ought to replace only within
377 // if there is no selection, then:
378 // (i) if some search string has been provided, then we find it.
379 // (think of how the dialog works when you hit "replace" the
381 // (ii) if no search string has been provided, then we treat the
382 // word the cursor is in as the search string. (why? i have no
383 // idea.) but this only works in text?
385 // returns the number of replacements made (one, if any) and
386 // whether anything at all was done.
387 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
388 docstring const & replacestr, bool case_sens,
389 bool whole, bool forward, bool findnext, bool wrap)
391 Cursor & cur = bv->cursor();
392 if (!cur.selection()) {
393 // no selection, non-empty search string: find it
394 if (!searchstr.empty()) {
395 bool const found = findOne(bv, searchstr, case_sens, whole,
396 forward, true, findnext, wrap, false);
397 return make_pair(found, 0);
399 // empty search string
402 return make_pair(false, 0);
403 // select current word and treat it as the search string.
404 // This causes a minor bug as undo will restore this selection,
405 // which the user did not create (#8986).
406 cur.innerText()->selectWord(cur, WHOLE_WORD);
407 searchstr = cur.selectionAsString(false, true);
410 // if we still don't have a search string, report the error
412 if (!searchAllowed(searchstr))
413 return make_pair(false, 0);
415 bool have_selection = cur.selection();
416 docstring const selected = cur.selectionAsString(false, true);
419 ? searchstr == selected
420 : compare_no_case(searchstr, selected) == 0;
422 // no selection or current selection is not search word:
423 // just find the search word
424 if (!have_selection || !match) {
425 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
426 true, findnext, wrap, false);
427 return make_pair(found, 0);
430 // we're now actually ready to replace. if the buffer is
431 // read-only, we can't, though.
432 if (bv->buffer().isReadonly())
433 return make_pair(false, 0);
435 cap::replaceSelectionWithString(cur, replacestr);
437 cur.pos() += replacestr.length();
438 LASSERT(cur.pos() <= cur.lastpos(),
439 cur.pos() = cur.lastpos());
442 findOne(bv, searchstr, case_sens, whole,
443 forward, false, findnext, wrap, false);
445 return make_pair(true, 1);
451 docstring const find2string(docstring const & search,
452 bool casesensitive, bool matchword,
453 bool forward, bool wrap, bool instant)
457 << int(casesensitive) << ' '
458 << int(matchword) << ' '
459 << int(forward) << ' '
466 docstring const replace2string(docstring const & replace,
467 docstring const & search,
468 bool casesensitive, bool matchword,
469 bool all, bool forward, bool findnext, bool wrap)
472 ss << replace << '\n'
474 << int(casesensitive) << ' '
475 << int(matchword) << ' '
477 << int(forward) << ' '
478 << int(findnext) << ' '
484 docstring const string2find(docstring const & argument,
491 // data is of the form
493 // <casesensitive> <matchword> <forward> <wrap>"
495 docstring howto = split(argument, search, '\n');
497 casesensitive = parse_bool(howto);
498 matchword = parse_bool(howto);
499 forward = parse_bool(howto, true);
500 wrap = parse_bool(howto);
501 instant = parse_bool(howto);
507 bool lyxfind(BufferView * bv, FuncRequest const & ev)
509 if (!bv || ev.action() != LFUN_WORD_FIND)
512 //lyxerr << "find called, cmd: " << ev << endl;
519 docstring search = string2find(ev.argument(), casesensitive,
520 matchword, forward, wrap, instant);
522 return findOne(bv, search, casesensitive, matchword, forward,
523 false, true, wrap, instant);
527 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
529 if (!bv || ev.action() != LFUN_WORD_REPLACE)
532 // data is of the form
535 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap>"
538 docstring howto = split(ev.argument(), rplc, '\n');
539 howto = split(howto, search, '\n');
541 bool casesensitive = parse_bool(howto);
542 bool matchword = parse_bool(howto);
543 bool all = parse_bool(howto);
544 bool forward = parse_bool(howto, true);
545 bool findnext = parse_bool(howto, true);
546 bool wrap = parse_bool(howto);
550 int replace_count = 0;
552 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
553 update = replace_count > 0;
556 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext, wrap);
558 replace_count = rv.second;
561 Buffer const & buf = bv->buffer();
563 // emit message signal.
564 buf.message(_("String not found."));
566 if (replace_count == 0) {
567 buf.message(_("String found."));
568 } else if (replace_count == 1) {
569 buf.message(_("String has been replaced."));
571 docstring const str =
572 bformat(_("%1$d strings have been replaced."), replace_count);
580 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
582 for (; cur; cur.forwardPos())
583 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
587 DocIterator cur_orig(bv->cursor());
588 docstring q = _("End of file reached while searching forward.\n"
589 "Continue searching from the beginning?");
590 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
591 q, 0, 1, _("&Yes"), _("&No"));
592 if (wrap_answer == 0) {
593 bv->cursor().clear();
594 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
595 bv->clearSelection();
596 cur.setCursor(bv->cursor().selectionBegin());
597 if (findNextChange(bv, cur, false))
600 bv->cursor().setCursor(cur_orig);
607 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
609 for (cur.backwardPos(); cur; cur.backwardPos()) {
610 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
615 DocIterator cur_orig(bv->cursor());
616 docstring q = _("Beginning of file reached while searching backward.\n"
617 "Continue searching from the end?");
618 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
619 q, 0, 1, _("&Yes"), _("&No"));
620 if (wrap_answer == 0) {
621 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
622 bv->cursor().backwardPos();
623 bv->clearSelection();
624 cur.setCursor(bv->cursor().selectionBegin());
625 if (findPreviousChange(bv, cur, false))
628 bv->cursor().setCursor(cur_orig);
635 bool selectChange(Cursor & cur, bool forward)
637 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
639 Change ch = cur.paragraph().lookupChange(cur.pos());
641 CursorSlice tip1 = cur.top();
642 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
643 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
644 if (!ch2.isSimilarTo(ch))
647 CursorSlice tip2 = cur.top();
648 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
650 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
651 if (!ch2.isSimilarTo(ch)) {
652 // take a step forward to correctly set the selection
660 cur.bv().mouseSetCursor(cur, false);
662 cur.bv().mouseSetCursor(cur, true);
670 bool findChange(BufferView * bv, bool forward)
673 cur.setCursor(forward ? bv->cursor().selectionEnd()
674 : bv->cursor().selectionBegin());
675 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
676 return selectChange(cur, forward);
681 bool findNextChange(BufferView * bv)
683 return findChange(bv, true);
687 bool findPreviousChange(BufferView * bv)
689 return findChange(bv, false);
696 typedef vector<pair<string, string> > Escapes;
698 string string2regex(string in)
700 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
701 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
706 while (fl_pos < temp.size()) {
707 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
708 if (fl_pos == string::npos)
711 temp2 += temp.substr(lastpos, fl_pos - lastpos);
717 if (lastpos < temp.size()) {
718 temp2 += temp.substr(lastpos, temp.size() - lastpos);
723 string correctRegex(string t, bool withformat)
725 /* Convert \backslash => \
726 * and \{, \}, \[, \] => {, }, [, ]
729 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
732 bool backslashed = false;
733 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
736 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
740 if (sub.str(4) == "backslash") {
743 // transforms '\backslash \{' into '\{'
745 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
746 if ((next == "\\{") || (next == "\\}")) {
752 else if (sub.str(4) == "mathcircumflex")
754 else if (backslashed) {
756 if (withformat && (sub.str(3) == "{"))
757 replace = accents["braceleft"];
758 else if (withformat && (sub.str(3) == "}"))
759 replace = accents["braceright"];
761 // else part should not exist
766 replace = sub.str(3);
768 if (lastpos < (size_t) sub.position(2))
769 s += t.substr(lastpos, sub.position(2) - lastpos);
771 lastpos = sub.position(2) + sub.length(2);
775 else if (lastpos < t.length())
776 s += t.substr(lastpos, t.length() - lastpos);
780 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
781 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
782 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
783 string escape_for_regex(string s, bool withformat)
787 while (lastpos < s.size()) {
788 size_t regex_pos = s.find("\\regexp{", lastpos);
789 if (regex_pos == string::npos) {
790 regex_pos = s.size();
792 if (regex_pos > lastpos) {
793 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
795 if (lastpos == s.size())
798 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
799 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
800 lastpos = end_pos + 13;
806 /// Wrapper for lyx::regex_replace with simpler interface
807 bool regex_replace(string const & s, string & t, string const & searchstr,
808 string const & replacestr)
810 regex e(searchstr, regex_constants::ECMAScript);
812 ostream_iterator<char, char> it(oss);
813 regex_replace(it, s.begin(), s.end(), e, replacestr);
814 // tolerate t and s be references to the same variable
815 bool rv = (s != oss.str());
834 vector <string> result = vector <string>();
835 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
838 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
840 if (newres.match2end < oldres.match2end)
841 return MatchResult::newIsTooFar;
842 if (newres.match_len < oldres.match_len)
843 return MatchResult::newIsTooFar;
845 if (newres.match_len == oldres.match_len) {
846 if (newres.match2end == oldres.match2end)
847 return MatchResult::newIsBetter;
849 return MatchResult::newIsInvalid;
852 /** The class performing a match between a position in the document and the FindAdvOptions.
855 class MatchStringAdv {
857 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
859 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
860 ** constructor as opt.search, under the opt.* options settings.
863 ** If set, then match is searched only against beginning of text starting at cur.
864 ** If unset, then match is searched anywhere in text starting at cur.
867 ** The length of the matching text, or zero if no match was found.
869 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
878 /// first buffer on which search was started
879 lyx::Buffer * const p_first_buf;
881 FindAndReplaceOptions const & opt;
884 /// Auxiliary find method (does not account for opt.matchword)
885 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
886 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
888 /** Normalize a stringified or latexified LyX paragraph.
892 ** <li>if search is not casesensitive, then lowercase the string;
893 ** <li>remove any newline at begin or end of the string;
894 ** <li>replace any newline in the middle of the string with a simple space;
895 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
898 ** @todo Normalization should also expand macros, if the corresponding
899 ** search option was checked.
901 string normalize(docstring const & s) const;
902 // normalized string to search
903 string par_as_string;
904 // regular expression to use for searching
905 // regexp2 is same as regexp, but prefixed with a ".*?"
907 QRegularExpression regexp;
908 QRegularExpression regexp2;
913 // leading format material as string
914 string lead_as_string;
915 // par_as_string after removal of lead_as_string
916 string par_as_string_nolead;
917 // unmatched open braces in the search string/regexp
919 // number of (.*?) subexpressions added at end of search regexp for closing
920 // environments, math mode, styles, etc...
923 // Are we searching with regular expressions ?
925 static int valid_matches;
926 static vector <string> matches;
927 void FillResults(MatchResult &found_mr);
930 int MatchStringAdv::valid_matches = 0;
931 vector <string> MatchStringAdv::matches = vector <string>(10);
933 void MatchStringAdv::FillResults(MatchResult &found_mr)
935 if (found_mr.match_len > 0) {
936 valid_matches = found_mr.result.size();
937 for (size_t i = 0; i < found_mr.result.size(); i++)
938 matches[i] = found_mr.result[i];
944 static docstring buffer_to_latex(Buffer & buffer)
946 //OutputParams runparams(&buffer.params().encoding());
947 OutputParams runparams(encodings.fromLyXName("utf8"));
948 odocstringstream ods;
950 runparams.nice = true;
951 runparams.flavor = Flavor::XeTeX;
952 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
953 // No side effect of file copying and image conversion
954 runparams.dryrun = true;
955 if (ignoreFormats.getDeleted())
956 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
958 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
959 pit_type const endpit = buffer.paragraphs().size();
960 for (pit_type pit = 0; pit != endpit; ++pit) {
961 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
962 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
968 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
971 if (!opt.ignoreformat) {
972 str = buffer_to_latex(buffer);
974 // OutputParams runparams(&buffer.params().encoding());
975 OutputParams runparams(encodings.fromLyXName("utf8"));
976 runparams.nice = true;
977 runparams.flavor = Flavor::XeTeX;
978 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
979 runparams.dryrun = true;
980 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
981 if (ignoreFormats.getDeleted()) {
982 option |= AS_STR_SKIPDELETE;
983 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
986 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
988 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
989 Paragraph const & par = buffer.paragraphs().at(pit);
990 LYXERR(Debug::FIND, "Adding to search string: '"
991 << par.asString(pos_type(0), par.size(),
995 str += par.asString(pos_type(0), par.size(),
999 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1000 string t = to_utf8(str);
1001 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1008 /// Return separation pos between the leading material and the rest
1009 static size_t identifyLeading(string const & s)
1012 // @TODO Support \item[text]
1013 // Kornel: Added textsl, textsf, textit, texttt and noun
1014 // + allow to search for colored text too
1015 while (regex_replace(t, t, "^\\\\(("
1016 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1017 "lyxaddress|lyxrightaddress|"
1018 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1019 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1020 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1021 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1022 || regex_replace(t, t, "^\\$", "")
1023 || regex_replace(t, t, "^\\\\\\[", "")
1024 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1025 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1027 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1032 * Given a latexified string, retrieve some handled features
1033 * The features of the regex will later be compared with the features
1034 * of the searched text. If the regex features are not a
1035 * subset of the analized, then, in not format ignoring search
1036 * we can early stop the search in the relevant inset.
1038 typedef map<string, bool> Features;
1040 static Features identifyFeatures(string const & s)
1042 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1043 static regex const valid("^("
1045 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1046 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1047 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1048 "(u|uu)line|(s|x)out|uwave|"
1049 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1050 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1055 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1058 if (sub.str(1).compare("regexp") == 0) {
1062 string token = sub.str(1);
1064 if (regex_match(token, sub2, valid)) {
1072 if (sub.str(1).compare("endregexp") == 0) {
1082 * defines values features of a key "\\[a-z]+{"
1087 /* Char type with content discarded
1088 * like \hspace{1cm} */
1090 /* Char, like \backslash */
1092 /* replace starting backslash with '#' */
1094 /* \part, \section*, ... */
1096 /* title, author etc */
1098 /* \foreignlanguage{ngerman}, ... */
1101 * to discard language in content */
1104 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1106 /* fonts, colors, markups, ... */
1108 /* footnotesize, ... large, ...
1109 * Ignore all of them */
1112 /* inputencoding, ...
1113 * Discard also content, because they do not help in search */
1116 * like remove, but also all arguments */
1118 /* item, listitem */
1120 /* tex, latex, ... like isChar */
1122 /* like \lettrine[lines=5]{}{} */
1124 // like isStandard, but always remove head
1126 /* End of arguments marker for lettrine,
1127 * so that they can be ignored */
1130 KeyInfo() = default;
1131 KeyInfo(KeyType type, int parcount, bool disable)
1133 parenthesiscount(parcount),
1134 disabled(disable) {}
1135 KeyType keytype = invalid;
1137 int _tokensize = -1;
1138 int _tokenstart = -1;
1139 int _dataStart = -1;
1141 int parenthesiscount = 1;
1142 bool disabled = false;
1143 bool used = false; /* by pattern */
1148 Border(int l=0, int u=0) : low(l), upper(u) {};
1153 #define MAXOPENED 30
1155 bool isPatternString_;
1157 explicit Intervall(bool isPattern, string const & p) :
1158 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1159 hasTitle(false), langcount(0)
1167 static vector<Border> borders;
1168 int depts[MAXOPENED];
1169 int closes[MAXOPENED];
1170 int actualdeptindex;
1171 int previousNotIgnored(int) const;
1172 int nextNotIgnored(int) const;
1173 void handleOpenP(int i);
1174 void handleCloseP(int i, bool closingAllowed);
1175 void resetOpenedP(int openPos);
1176 void addIntervall(int upper);
1177 void addIntervall(int low, int upper); /* if explicit */
1178 void removeAccents();
1179 void setForDefaultLang(KeyInfo const & defLang) const;
1180 int findclosing(int start, int end, char up, char down, int repeat);
1181 void handleParentheses(int lastpos, bool closingAllowed);
1183 int langcount; // Number of disabled language specs up to current position in actual interval
1184 int isOpeningPar(int pos) const;
1186 void output(ostringstream &os, int lastpos);
1187 // string show(int lastpos);
1190 vector<Border> Intervall::borders = vector<Border>(30);
1192 int Intervall::isOpeningPar(int pos) const
1194 if ((pos < 0) || (size_t(pos) >= par.size()))
1196 if (par[pos] != '{')
1198 if (size_t(pos) + 2 >= par.size())
1200 if (par[pos+2] != '}')
1202 if (par[pos+1] == '[' || par[pos+1] == ']')
1207 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1209 // Enable the use of first token again
1210 if (ignoreidx >= 0) {
1211 int value = defLang._tokenstart + defLang._tokensize;
1217 if (borders[borderidx].low < value)
1218 borders[borderidx].low = value;
1219 if (borders[borderidx].upper < value)
1220 borders[borderidx].upper = value;
1225 static void checkDepthIndex(int val)
1227 static int maxdepthidx = MAXOPENED-2;
1228 static int lastmaxdepth = 0;
1229 if (val > lastmaxdepth) {
1230 LYXERR(Debug::INFO, "Depth reached " << val);
1233 if (val > maxdepthidx) {
1235 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1240 // Not needed, because borders are now dynamically expanded
1241 static void checkIgnoreIdx(int val)
1243 static int lastmaxignore = -1;
1244 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1245 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1246 lastmaxignore = val;
1252 * Expand the region of ignored parts of the input latex string
1253 * The region is only relevant in output()
1255 void Intervall::addIntervall(int low, int upper)
1258 if (low == upper) return;
1259 for (idx = ignoreidx+1; idx > 0; --idx) {
1260 if (low > borders[idx-1].upper) {
1264 Border br(low, upper);
1265 if (idx > ignoreidx) {
1266 if (borders.size() <= size_t(idx)) {
1267 borders.push_back(br);
1273 // checkIgnoreIdx(ignoreidx);
1277 // Expand only if one of the new bound is inside the interwall
1278 // We know here that br.low > borders[idx-1].upper
1279 if (br.upper < borders[idx].low) {
1280 // We have to insert at this pos
1281 if (size_t(ignoreidx+1) >= borders.size()) {
1282 borders.push_back(borders[ignoreidx]);
1285 borders[ignoreidx+1] = borders[ignoreidx];
1287 for (int i = ignoreidx; i > idx; --i) {
1288 borders[i] = borders[i-1];
1292 // checkIgnoreIdx(ignoreidx);
1295 // Here we know, that we are overlapping
1296 if (br.low > borders[idx].low)
1297 br.low = borders[idx].low;
1298 // check what has to be concatenated
1300 for (int i = idx; i <= ignoreidx; i++) {
1301 if (br.upper >= borders[i].low) {
1303 if (br.upper < borders[i].upper)
1304 br.upper = borders[i].upper;
1310 // count should be >= 1 here
1313 for (int i = idx + count; i <= ignoreidx; i++) {
1314 borders[i-count+1] = borders[i];
1316 ignoreidx -= count - 1;
1322 static void buildaccent(string n, string param, string values)
1326 const char delim = '|';
1327 while (getline(s, name, delim)) {
1329 for (char c : param) {
1330 string key = name + "{" + c + "}";
1331 // get the corresponding utf8-value
1332 if ((values[start] & 0xc0) != 0xc0) {
1333 // should not happen, utf8 encoding starts at least with 11xxxxxx
1334 // but value for '\dot{i}' is 'i', which is ascii
1335 if ((values[start] & 0x80) == 0) {
1337 accents[key] = values.substr(start, 1);
1338 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1343 for (int j = 1; ;j++) {
1344 if (start + j >= values.size()) {
1345 accents[key] = values.substr(start, j);
1346 start = values.size() - 1;
1349 else if ((values[start+j] & 0xc0) != 0x80) {
1350 // This is the first byte of following utf8 char
1351 accents[key] = values.substr(start, j);
1353 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1362 static string getutf8(unsigned uchar)
1365 string ret = string();
1367 if (uchar <= 0x7f) {
1368 c[maxc-1] = uchar & 0x7f;
1371 unsigned char rest = 0x40;
1372 unsigned char first = 0x80;
1374 for (int i = start; i >=0; --i) {
1376 c[i] = first + uchar;
1379 c[i] = 0x80 | (uchar & 0x3f);
1386 for (int i = 0; i < maxc; i++) {
1387 if (c[i] == 0) continue;
1393 static void buildAccentsMap()
1395 accents["imath"] = "ı";
1397 accents["jmath"] = "ȷ";
1398 accents["cdot"] = "·";
1399 accents["textasciicircum"] = "^";
1400 accents["mathcircumflex"] = "^";
1401 accents["sim"] = "~";
1402 accents["guillemotright"] = "»";
1403 accents["guillemotleft"] = "«";
1404 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1405 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1406 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1407 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1408 accents["negmedspace"] = getutf8(0xf0005);
1409 accents["thickspace"] = getutf8(0xf0006);
1410 accents["negthickspace"] = getutf8(0xf0007);
1411 accents["lyx"] = getutf8(0xf0010); // Used logos
1412 accents["LyX"] = getutf8(0xf0010);
1413 accents["tex"] = getutf8(0xf0011);
1414 accents["TeX"] = getutf8(0xf0011);
1415 accents["latex"] = getutf8(0xf0012);
1416 accents["LaTeX"] = getutf8(0xf0012);
1417 accents["latexe"] = getutf8(0xf0013);
1418 accents["LaTeXe"] = getutf8(0xf0013);
1419 accents["lyxarrow"] = getutf8(0xf0020);
1420 accents["braceleft"] = getutf8(0xf0030);
1421 accents["braceright"] = getutf8(0xf0031);
1422 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1423 accents["backslash LyX"] = getutf8(0xf0010);
1424 accents["backslash tex"] = getutf8(0xf0011);
1425 accents["backslash TeX"] = getutf8(0xf0011);
1426 accents["backslash latex"] = getutf8(0xf0012);
1427 accents["backslash LaTeX"] = getutf8(0xf0012);
1428 accents["backslash latexe"] = getutf8(0xf0013);
1429 accents["backslash LaTeXe"] = getutf8(0xf0013);
1430 accents["backslash lyxarrow"] = getutf8(0xf0020);
1431 accents["ddot{\\imath}"] = "ï";
1432 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1433 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1434 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1435 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1436 accents["acute{\\imath}"] = "í";
1437 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1438 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1439 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1440 buildaccent("mathring|r", "aAuUwy",
1442 accents["check{\\imath}"] = "ǐ";
1443 accents["check{\\jmath}"] = "ǰ";
1444 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1445 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1446 accents["hat{\\imath}"] = "î";
1447 accents["hat{\\jmath}"] = "ĵ";
1448 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1449 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1450 accents["bar{\\imath}"] = "ī";
1451 buildaccent("bar|=", "aAeEiIoOuUyY",
1452 "āĀēĒīĪōŌūŪȳȲ"); // macron
1453 accents["tilde{\\imath}"] = "ĩ";
1454 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1455 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1456 accents["breve{\\imath}"] = "ĭ";
1457 buildaccent("breve|u", "aAeEgGiIoOuU",
1458 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1459 accents["grave{\\imath}"] = "ì";
1460 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1461 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1462 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1463 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1464 buildaccent("ogonek|k", "AaEeIiUuOo",
1465 "ĄąĘęĮįŲųǪǫ"); // ogonek
1466 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1467 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1468 buildaccent("subring|textsubring", "Aa",
1470 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1471 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1472 buildaccent("subtilde|textsubtilde", "EeIiUu",
1473 "ḚḛḬḭṴṵ"); // subtilde
1474 accents["dgrave{\\imath}"] = "ȉ";
1475 accents["textdoublegrave{\\i}"] = "ȉ";
1476 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1477 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1478 accents["rcap{\\imath}"] = "ȉ";
1479 accents["textroundcap{\\i}"] = "ȉ";
1480 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1481 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1482 buildaccent("slashed", "oO",
1487 * Created accents in math or regexp environment
1488 * are macros, but we need the utf8 equivalent
1490 void Intervall::removeAccents()
1492 if (accents.empty())
1494 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1495 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1496 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|(brace|guillemot)(left|right)|textasciicircum|mathcircumflex|sim)(?![a-zA-Z]))");
1498 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1500 string key = sub.str(1);
1501 AccentsIterator it_ac = accents.find(key);
1502 if (it_ac != accents.end()) {
1503 string val = it_ac->second;
1504 size_t pos = sub.position(size_t(0));
1505 for (size_t i = 0; i < val.size(); i++) {
1506 par[pos+i] = val[i];
1508 // Remove possibly following space too
1509 if (par[pos+sub.str(0).size()] == ' ')
1510 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1512 addIntervall(pos+val.size(), pos + sub.str(0).size());
1513 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1514 // remove traces of any remaining chars
1519 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1524 void Intervall::handleOpenP(int i)
1527 depts[actualdeptindex] = i+1;
1528 closes[actualdeptindex] = -1;
1529 checkDepthIndex(actualdeptindex);
1532 void Intervall::handleCloseP(int i, bool closingAllowed)
1534 if (actualdeptindex <= 0) {
1535 if (! closingAllowed)
1536 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1537 // if we are at the very end
1538 addIntervall(i, i+1);
1541 closes[actualdeptindex] = i+1;
1546 void Intervall::resetOpenedP(int openPos)
1548 // Used as initializer for foreignlanguage entry
1549 actualdeptindex = 1;
1550 depts[1] = openPos+1;
1554 int Intervall::previousNotIgnored(int start) const
1556 int idx = 0; /* int intervalls */
1557 for (idx = ignoreidx; idx >= 0; --idx) {
1558 if (start > borders[idx].upper)
1560 if (start >= borders[idx].low)
1561 start = borders[idx].low-1;
1566 int Intervall::nextNotIgnored(int start) const
1568 int idx = 0; /* int intervalls */
1569 for (idx = 0; idx <= ignoreidx; idx++) {
1570 if (start < borders[idx].low)
1572 if (start < borders[idx].upper)
1573 start = borders[idx].upper;
1578 typedef unordered_map<string, KeyInfo> KeysMap;
1579 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1580 typedef vector< KeyInfo> Entries;
1581 static KeysMap keys = unordered_map<string, KeyInfo>();
1587 Intervall interval_;
1588 void buildKeys(bool);
1589 void buildEntries(bool);
1590 void makeKey(const string &, KeyInfo, bool isPatternString);
1591 void processRegion(int start, int region_end); /* remove {} parts */
1592 void removeHead(KeyInfo const &, int count=0);
1595 LatexInfo(string const & par, bool isPatternString)
1596 : entidx_(-1), interval_(isPatternString, par)
1598 buildKeys(isPatternString);
1599 entries_ = vector<KeyInfo>();
1600 buildEntries(isPatternString);
1604 if (entries_.empty()) {
1607 if (entries_[0].keytype == KeyInfo::isTitle) {
1608 interval_.hasTitle = true;
1609 if (! entries_[0].disabled) {
1610 interval_.titleValue = entries_[0].head;
1613 interval_.titleValue = "";
1615 removeHead(entries_[0]);
1616 if (entries_.size() > 1)
1625 if (int(entries_.size()) > entidx_) {
1632 bool setNextKey(int idx) {
1633 if ((idx == entidx_) && (entidx_ >= 0)) {
1640 int find(int start, KeyInfo::KeyType keytype) const {
1644 while (tmpIdx < int(entries_.size())) {
1645 if (entries_[tmpIdx].keytype == keytype)
1651 int process(ostringstream & os, KeyInfo const & actual);
1652 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1653 // string show(int lastpos) { return interval.show(lastpos);};
1654 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1655 KeyInfo &getKeyInfo(int keyinfo) {
1656 static KeyInfo invalidInfo = KeyInfo();
1657 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1660 return entries_[keyinfo];
1662 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1663 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1667 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1671 for (int i = start; i < end; i += 1 + skip) {
1675 if (c == '\\') skip = 1;
1679 else if (c == down) {
1682 if ((repeat <= 0) || (par[i+1] != up))
1696 size_t mathpostfixsize;
1698 size_t mathprefixsize;
1702 vector<MathEntry> entries_;
1707 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1708 MathEntry m = MathEntry();
1710 m.mathStart = start;
1711 m.mathprefixsize = prefixsize;
1712 m.mathEnd = end + postfixsize;
1713 m.mathpostfixsize = postfixsize;
1714 m.mathSize = m.mathEnd - m.mathStart;
1715 entries_.push_back(m);
1717 bool empty() const { return entries_.empty(); };
1718 size_t getEndPos() const {
1719 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1722 return entries_[actualIdx_].mathEnd;
1724 size_t getStartPos() const {
1725 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1726 return 100000; /* definitely enough? */
1728 return entries_[actualIdx_].mathStart;
1730 size_t getPrefixSize() const {
1731 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1734 return entries_[actualIdx_].mathprefixsize;
1736 size_t getPostfixSize() const {
1737 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1740 return entries_[actualIdx_].mathpostfixsize;
1742 size_t getFirstPos() {
1744 return getStartPos();
1746 size_t getSize() const {
1747 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1750 return entries_[actualIdx_].mathSize;
1752 void incrEntry() { actualIdx_++; };
1755 void LatexInfo::buildEntries(bool isPatternString)
1757 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1758 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1759 static bool disableLanguageOverride = false;
1760 smatch sub, submath;
1761 bool evaluatingRegexp = false;
1763 bool evaluatingMath = false;
1764 bool evaluatingCode = false;
1766 bool evaluatingOptional = false;
1767 size_t optionalEnd = 0;
1770 bool math_end_waiting = false;
1771 size_t math_pos = 10000;
1772 size_t math_prefix_size = 1;
1774 static vector<string> usedText = vector<string>();
1775 static bool removeMathHull = false;
1777 interval_.removeAccents();
1779 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1781 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1782 // prefixed by odd count of '\\'
1785 if (math_end_waiting) {
1786 size_t pos = submath.position(size_t(2));
1787 if ((math_end == "$") &&
1788 (submath.str(2) == "$")) {
1789 mi.insert("$", math_pos, 1, pos, 1);
1790 math_end_waiting = false;
1792 else if ((math_end == "\\]") &&
1793 (submath.str(2) == "\\]")) {
1794 mi.insert("\\]", math_pos, 2, pos, 2);
1795 math_end_waiting = false;
1797 else if ((submath.str(3).compare("end") == 0) &&
1798 (submath.str(4).compare(math_end) == 0)) {
1799 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
1800 math_end_waiting = false;
1806 if (submath.str(3).compare("begin") == 0) {
1807 math_end_waiting = true;
1808 math_end = submath.str(4);
1809 math_pos = submath.position(size_t(2));
1810 math_prefix_size = submath.str(2).length();
1812 else if (submath.str(2).compare("\\[") == 0) {
1813 math_end_waiting = true;
1815 math_pos = submath.position(size_t(2));
1817 else if (submath.str(2) == "$") {
1818 size_t pos = submath.position(size_t(2));
1819 math_end_waiting = true;
1825 // Ignore language if there is math somewhere in pattern-string
1826 if (isPatternString) {
1827 for (auto s: usedText) {
1828 // Remove entries created in previous search runs
1831 usedText = vector<string>();
1834 keys["foreignlanguage"].disabled = true;
1835 disableLanguageOverride = true;
1836 removeMathHull = false;
1839 removeMathHull = true; // used later if not isPatternString
1840 disableLanguageOverride = false;
1844 if (disableLanguageOverride) {
1845 keys["foreignlanguage"].disabled = true;
1848 math_pos = mi.getFirstPos();
1849 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1851 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1852 // prefixed by odd count of '\\'
1855 string key = sub.str(5);
1857 if (sub.str(2)[0] == '\\')
1858 key = sub.str(2)[1];
1863 KeysIterator it_key = keys.find(key);
1864 if (it_key != keys.end()) {
1865 if (it_key->second.keytype == KeyInfo::headRemove) {
1866 KeyInfo found1 = it_key->second;
1867 found1.disabled = true;
1868 found1.head = "\\" + key + "{";
1869 found1._tokenstart = sub.position(size_t(2));
1870 found1._tokensize = found1.head.length();
1871 found1._dataStart = found1._tokenstart + found1.head.length();
1872 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1873 found1._dataEnd = endpos;
1878 if (evaluatingRegexp) {
1879 if (sub.str(3).compare("endregexp") == 0) {
1880 evaluatingRegexp = false;
1881 // found._tokenstart already set
1882 found._dataEnd = sub.position(size_t(2)) + 13;
1883 found._dataStart = found._dataEnd;
1884 found._tokensize = found._dataEnd - found._tokenstart;
1885 found.parenthesiscount = 0;
1886 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1893 if (evaluatingMath) {
1894 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1896 evaluatingMath = false;
1898 math_pos = mi.getStartPos();
1900 if (it_key == keys.end()) {
1901 found = KeyInfo(KeyInfo::isStandard, 0, true);
1902 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1903 found = KeyInfo(KeyInfo::isText, 0, false);
1904 if (isPatternString) {
1905 found.keytype = KeyInfo::isChar;
1906 found.disabled = false;
1910 usedText.push_back(key);
1914 if (key.compare("regexp") == 0) {
1915 evaluatingRegexp = true;
1916 found._tokenstart = sub.position(size_t(2));
1917 found._tokensize = 0;
1921 // Handle the other params of key
1922 if (found.keytype == KeyInfo::isIgnored)
1924 else if (found.keytype == KeyInfo::isMath) {
1925 if (size_t(sub.position(size_t(2))) == math_pos) {
1927 found._tokenstart = sub.position(size_t(2));
1928 found._tokensize = mi.getSize();
1929 found._dataEnd = found._tokenstart + found._tokensize;
1930 found._dataStart = found._dataEnd;
1931 found.parenthesiscount = 0;
1932 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1933 if (removeMathHull) {
1934 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1935 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1937 evaluatingMath = true;
1940 // begin|end of unknown env, discard
1941 // First handle tables
1942 // longtable|tabular
1943 bool discardComment;
1945 found.keytype = KeyInfo::doRemove;
1946 if ((sub.str(7).compare("longtable") == 0) ||
1947 (sub.str(7).compare("tabular") == 0)) {
1948 discardComment = true; /* '%' */
1951 discardComment = false;
1952 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1954 string token = sub.str(7);
1955 if (regex_match(token, sub2, removeArgs)) {
1956 found.keytype = KeyInfo::removeWithArg;
1959 // discard spaces before pos(2)
1960 int pos = sub.position(size_t(2));
1962 for (count = 0; pos - count > 0; count++) {
1963 char c = interval_.par[pos-count-1];
1964 if (discardComment) {
1965 if ((c != ' ') && (c != '%'))
1971 found._tokenstart = pos - count;
1972 if (sub.str(3).compare(0, 5, "begin") == 0) {
1973 size_t pos1 = pos + sub.str(2).length();
1974 if (sub.str(7).compare("cjk") == 0) {
1975 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1976 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1978 found.keytype = KeyInfo::isMain;
1979 found._dataStart = pos1;
1980 found._dataEnd = interval_.par.length();
1981 found.disabled = keys["foreignlanguage"].disabled;
1982 found.used = keys["foreignlanguage"].used;
1983 found._tokensize = pos1 - found._tokenstart;
1984 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1987 // Swallow possible optional params
1988 while (interval_.par[pos1] == '[') {
1989 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1991 // Swallow also the eventual parameter
1992 if (interval_.par[pos1] == '{') {
1993 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1996 found._dataEnd = pos1;
1998 found._dataStart = found._dataEnd;
1999 found._tokensize = count + found._dataEnd - pos;
2000 found.parenthesiscount = 0;
2001 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2002 found.disabled = true;
2006 // Handle "\end{...}"
2007 found._dataStart = pos + sub.str(2).length();
2008 found._dataEnd = found._dataStart;
2009 found._tokensize = count + found._dataEnd - pos;
2010 found.parenthesiscount = 0;
2011 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2012 found.disabled = true;
2016 else if (found.keytype != KeyInfo::isRegex) {
2017 found._tokenstart = sub.position(size_t(2));
2018 if (found.parenthesiscount == 0) {
2019 // Probably to be discarded
2020 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2021 char following = interval_.par[following_pos];
2022 if (following == ' ')
2023 found.head = "\\" + sub.str(5) + " ";
2024 else if (following == '=') {
2025 // like \uldepth=1000pt
2026 found.head = sub.str(2);
2029 found.head = "\\" + key;
2030 found._tokensize = found.head.length();
2031 found._dataEnd = found._tokenstart + found._tokensize;
2032 found._dataStart = found._dataEnd;
2035 int params = found._tokenstart + key.length() + 1;
2036 if (evaluatingOptional) {
2037 if (size_t(found._tokenstart) > optionalEnd) {
2038 evaluatingOptional = false;
2041 found.disabled = true;
2044 int optend = params;
2045 while (interval_.par[optend] == '[') {
2046 // discard optional parameters
2047 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2049 if (optend > params) {
2050 key += interval_.par.substr(params, optend-params);
2051 evaluatingOptional = true;
2052 optionalEnd = optend;
2053 if (found.keytype == KeyInfo::isSectioning) {
2054 // Remove optional values (but still keep in header)
2055 interval_.addIntervall(params, optend);
2058 string token = sub.str(7);
2060 if (interval_.par[optend] != '{') {
2062 found.parenthesiscount = 0;
2063 found.head = "\\" + key;
2066 closings = found.parenthesiscount;
2067 if (found.parenthesiscount == 1) {
2068 found.head = "\\" + key + "{";
2070 else if (found.parenthesiscount > 1) {
2072 found.head = sub.str(2) + "{";
2073 closings = found.parenthesiscount - 1;
2076 found.head = "\\" + key + "{";
2079 found._tokensize = found.head.length();
2080 found._dataStart = found._tokenstart + found.head.length();
2081 if (found.keytype == KeyInfo::doRemove) {
2083 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2084 if (endpar >= interval_.par.length())
2085 found._dataStart = interval_.par.length();
2087 found._dataStart = endpar;
2088 found._tokensize = found._dataStart - found._tokenstart;
2091 found._dataStart = found._tokenstart + found._tokensize;
2095 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2096 found._dataStart += 15;
2100 endpos = found._dataStart - 1;
2102 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2103 if (found.keytype == KeyInfo::isList) {
2104 // Check if it really is list env
2105 static regex const listre("^([a-z]+)$");
2107 if (!regex_match(token, sub2, listre)) {
2108 // Change the key of this entry. It is not in a list/item environment
2109 found.keytype = KeyInfo::endArguments;
2112 if (found.keytype == KeyInfo::noMain) {
2113 evaluatingCode = true;
2115 codeStart = found._dataStart;
2117 else if (evaluatingCode) {
2118 if (size_t(found._dataStart) > codeEnd)
2119 evaluatingCode = false;
2120 else if (found.keytype == KeyInfo::isMain) {
2121 // Disable this key, treate it as standard
2122 found.keytype = KeyInfo::isStandard;
2123 found.disabled = true;
2124 if ((codeEnd +1 >= interval_.par.length()) &&
2125 (found._tokenstart == codeStart)) {
2126 // trickery, because the code inset starts
2127 // with \selectlanguage ...
2129 if (entries_.size() > 1) {
2130 entries_[entries_.size()-1]._dataEnd = codeEnd;
2135 if ((endpos == interval_.par.length()) &&
2136 (found.keytype == KeyInfo::doRemove)) {
2137 // Missing closing => error in latex-input?
2138 // therefore do not delete remaining data
2139 found._dataStart -= 1;
2140 found._dataEnd = found._dataStart;
2143 found._dataEnd = endpos;
2145 if (isPatternString) {
2146 keys[key].used = true;
2149 entries_.push_back(found);
2153 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2155 stringstream s(keysstring);
2157 const char delim = '|';
2158 while (getline(s, key, delim)) {
2159 KeyInfo keyII(keyI);
2160 if (isPatternString) {
2163 else if ( !keys[key].used)
2164 keyII.disabled = true;
2169 void LatexInfo::buildKeys(bool isPatternString)
2172 static bool keysBuilt = false;
2173 if (keysBuilt && !isPatternString) return;
2175 // Keys to ignore in any case
2176 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2177 // Known standard keys with 1 parameter.
2178 // Split is done, if not at start of region
2179 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2180 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2181 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2182 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2183 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2184 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2186 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2187 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2188 makeKey("section*|subsection*|subsubsection*|paragraph*",
2189 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2190 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2191 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2193 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2195 // Split is done, if not at start of region
2196 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2197 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2199 // Split is done always.
2200 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2204 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2205 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2206 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2207 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2209 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2210 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2211 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2212 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2214 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2215 // Custom space/skip, remove the content (== length value)
2216 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2217 // Found in fr/UserGuide.lyx
2218 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2220 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2221 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2222 // Known macros to remove (including their parameter)
2224 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2225 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2226 // handle like standard keys with 1 parameter.
2227 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2229 // Ignore deleted text
2230 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2231 // but preserve added text
2232 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2234 // Macros to remove, but let the parameter survive
2236 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2238 // Remove language spec from content of these insets
2239 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2241 // Same effect as previous, parameter will survive (because there is no one anyway)
2243 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2244 // Remove table decorations
2245 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2246 // Discard shape-header.
2247 // For footnote or shortcut too, because of lang settings
2248 // and wrong handling if used 'KeyInfo::noMain'
2249 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2250 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2251 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2252 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2253 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2254 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2255 // like ('tiny{}' or '\tiny ' ... )
2256 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2258 // Survives, like known character
2259 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2260 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2261 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2263 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2264 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2265 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2267 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2268 // Remove RTL/LTR marker
2269 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2270 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2271 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2272 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2273 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2274 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2275 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2276 if (isPatternString) {
2277 // Allow the first searched string to rebuild the keys too
2281 // no need to rebuild again
2287 * Keep the list of actual opened parentheses actual
2288 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2290 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2293 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2297 if (c == '\\') skip = 1;
2298 else if (c == '{') {
2301 else if (c == '}') {
2302 handleCloseP(i, closingAllowed);
2308 string Intervall::show(int lastpos)
2310 int idx = 0; /* int intervalls */
2313 for (idx = 0; idx <= ignoreidx; idx++) {
2314 while (i < lastpos) {
2316 if (i <= borders[idx].low) {
2317 if (borders[idx].low > lastpos)
2318 printsize = lastpos - i;
2320 printsize = borders[idx].low - i;
2321 s += par.substr(i, printsize);
2323 if (i >= borders[idx].low)
2324 i = borders[idx].upper;
2327 i = borders[idx].upper;
2333 s += par.substr(i, lastpos-i);
2339 void Intervall::output(ostringstream &os, int lastpos)
2341 // get number of chars to output
2342 int idx = 0; /* int intervalls */
2345 string startTitle = titleValue;
2346 for (idx = 0; idx <= ignoreidx; idx++) {
2348 if (i <= borders[idx].low) {
2350 if (borders[idx].low > lastpos)
2351 printsize = lastpos - i;
2353 printsize = borders[idx].low - i;
2354 if (printsize > 0) {
2355 os << startTitle << par.substr(i, printsize);
2357 printed += printsize;
2360 handleParentheses(i, false);
2361 if (i >= borders[idx].low)
2362 i = borders[idx].upper;
2365 i = borders[idx].upper;
2372 os << startTitle << par.substr(i, lastpos-i);
2373 printed += lastpos-i;
2375 handleParentheses(lastpos, false);
2377 if (keys["foreignlanguage"].disabled)
2378 startindex = actualdeptindex-langcount;
2380 startindex = actualdeptindex;
2381 for (int i = startindex; i > 0; --i) {
2384 if (hasTitle && (printed > 0))
2386 if (! isPatternString_)
2388 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2391 void LatexInfo::processRegion(int start, int region_end)
2393 while (start < region_end) { /* Let {[} and {]} survive */
2394 int cnt = interval_.isOpeningPar(start);
2396 // Closing is allowed past the region
2397 int closing = interval_.findclosing(start+1, interval_.par.length());
2398 interval_.addIntervall(start, start+1);
2399 interval_.addIntervall(closing, closing+1);
2403 start = interval_.nextNotIgnored(start+1);
2407 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2409 if (actual.parenthesiscount == 0) {
2410 // "{\tiny{} ...}" ==> "{{} ...}"
2411 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2414 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2415 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2416 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2420 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2423 switch (actual.keytype)
2425 case KeyInfo::isTitle: {
2427 nextKeyIdx = getNextKey();
2430 case KeyInfo::cleanToStart: {
2431 actual._dataEnd = actual._dataStart;
2432 nextKeyIdx = getNextKey();
2433 // Search for end of arguments
2434 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2436 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2437 entries_[i].disabled = true;
2439 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2441 while (interval_.par[actual._dataEnd] == ' ')
2443 interval_.addIntervall(0, actual._dataEnd+1);
2444 interval_.actualdeptindex = 0;
2445 interval_.depts[0] = actual._dataEnd+1;
2446 interval_.closes[0] = -1;
2449 case KeyInfo::isText:
2450 interval_.par[actual._tokenstart] = '#';
2451 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2452 nextKeyIdx = getNextKey();
2454 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2455 if (actual.disabled)
2456 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2458 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2461 case KeyInfo::isChar: {
2462 nextKeyIdx = getNextKey();
2465 case KeyInfo::isSize: {
2466 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2467 if (actual.parenthesiscount == 0)
2468 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2470 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2472 nextKeyIdx = getNextKey();
2474 // Here _dataStart points to '{', so correct it
2475 actual._dataStart += 1;
2476 actual._tokensize += 1;
2477 actual.parenthesiscount = 1;
2478 if (interval_.par[actual._dataStart] == '}') {
2479 // Determine the end if used like '{\tiny{}...}'
2480 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2481 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2484 // Determine the end if used like '\tiny{...}'
2485 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2487 // Split on this key if not at start
2488 int start = interval_.nextNotIgnored(previousStart);
2489 if (start < actual._tokenstart) {
2490 interval_.output(os, actual._tokenstart);
2491 interval_.addIntervall(start, actual._tokenstart);
2493 // discard entry if at end of actual
2494 nextKeyIdx = process(os, actual);
2498 case KeyInfo::endArguments: {
2499 // Remove trailing '{}' too
2500 actual._dataStart += 1;
2501 actual._dataEnd += 1;
2502 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2503 nextKeyIdx = getNextKey();
2506 case KeyInfo::noMain:
2508 case KeyInfo::isStandard: {
2509 if (actual.disabled) {
2511 processRegion(actual._dataStart, actual._dataStart+1);
2512 nextKeyIdx = getNextKey();
2514 // Split on this key if not at datastart of calling entry
2515 int start = interval_.nextNotIgnored(previousStart);
2516 if (start < actual._tokenstart) {
2517 interval_.output(os, actual._tokenstart);
2518 interval_.addIntervall(start, actual._tokenstart);
2520 // discard entry if at end of actual
2521 nextKeyIdx = process(os, actual);
2525 case KeyInfo::removeWithArg: {
2526 nextKeyIdx = getNextKey();
2527 // Search for end of arguments
2528 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2530 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2531 entries_[i].disabled = true;
2533 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2535 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2538 case KeyInfo::doRemove: {
2539 // Remove the key with all parameters and following spaces
2542 if (interval_.par[actual._dataEnd-1] == ' ')
2543 start = actual._dataEnd;
2545 start = actual._dataEnd+1;
2546 for (pos = start; pos < interval_.par.length(); pos++) {
2547 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2550 // Remove also enclosing parentheses [] and {}
2553 while (actual._tokenstart > numpars) {
2554 if (pos+numpars >= interval_.par.size())
2556 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2558 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2564 if (interval_.par[pos+numpars] == ' ')
2568 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2569 nextKeyIdx = getNextKey();
2572 case KeyInfo::isList: {
2573 // Discard space before _tokenstart
2575 for (count = 0; count < actual._tokenstart; count++) {
2576 if (interval_.par[actual._tokenstart-count-1] != ' ')
2579 nextKeyIdx = getNextKey();
2580 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2582 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2584 // How else can we catch this one?
2585 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2586 entries_[i].disabled = true;
2588 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2590 else if (nextKeyIdx > 0) {
2591 // Ignore any lang entries inside data region
2592 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2593 if (entries_[i].keytype == KeyInfo::isMain)
2594 entries_[i].disabled = true;
2597 if (actual.disabled) {
2598 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2601 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2603 if (interval_.par[actual._dataEnd+1] == '[') {
2604 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2605 if ((interval_.par[actual._dataEnd+2] == '{') &&
2606 (interval_.par[posdown-1] == '}')) {
2607 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2608 interval_.addIntervall(posdown-1, posdown+1);
2611 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2612 interval_.addIntervall(posdown, posdown+1);
2614 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2615 if (blk > posdown) {
2616 // Discard at most 1 space after empty item
2618 for (count = 0; count < 1; count++) {
2619 if (interval_.par[blk+count] != ' ')
2623 interval_.addIntervall(blk, blk+count);
2628 case KeyInfo::isSectioning: {
2629 // Discard spaces before _tokenstart
2631 int val = actual._tokenstart;
2632 for (count = 0; count < actual._tokenstart;) {
2633 val = interval_.previousNotIgnored(val-1);
2634 if (val < 0 || interval_.par[val] != ' ')
2637 count = actual._tokenstart - val;
2640 if (actual.disabled) {
2641 removeHead(actual, count);
2642 nextKeyIdx = getNextKey();
2644 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2645 nextKeyIdx = process(os, actual);
2649 case KeyInfo::isMath: {
2650 // Same as regex, use the content unchanged
2651 nextKeyIdx = getNextKey();
2654 case KeyInfo::isRegex: {
2655 // DO NOT SPLIT ON REGEX
2657 nextKeyIdx = getNextKey();
2660 case KeyInfo::isIgnored: {
2661 // Treat like a character for now
2662 nextKeyIdx = getNextKey();
2665 case KeyInfo::isMain: {
2666 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2667 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2668 if (actual._tokenstart > 0) {
2669 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2670 if ((prev >= 0) && interval_.par[prev] == '%')
2671 interval_.addIntervall(prev, prev+1);
2673 if (actual.disabled) {
2675 interval_.langcount++;
2676 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2677 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2678 // Discard also the space before math-equation
2679 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2681 nextKeyIdx = getNextKey();
2682 // interval.resetOpenedP(actual._dataStart-1);
2685 if (actual._tokenstart < 26) {
2686 // for the first (and maybe dummy) language
2687 interval_.setForDefaultLang(actual);
2689 interval_.resetOpenedP(actual._dataStart-1);
2693 case KeyInfo::invalid:
2694 case KeyInfo::headRemove:
2695 // These two cases cannot happen, already handled
2698 // LYXERR(Debug::INFO, "Unhandled keytype");
2699 nextKeyIdx = getNextKey();
2706 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2708 int end = interval_.nextNotIgnored(actual._dataEnd);
2709 int oldStart = actual._dataStart;
2710 int nextKeyIdx = getNextKey();
2712 if ((nextKeyIdx < 0) ||
2713 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2714 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2715 if (oldStart <= end) {
2716 processRegion(oldStart, end);
2721 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2723 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2724 (void) dispatch(os, actual._dataStart, nextKey);
2725 end = nextKey._tokenstart;
2728 processRegion(oldStart, nextKey._tokenstart);
2729 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2731 oldStart = nextKey._dataEnd+1;
2733 // now nextKey is either invalid or is outside of actual._dataEnd
2734 // output the remaining and discard myself
2735 if (oldStart <= end) {
2736 processRegion(oldStart, end);
2738 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2740 // This is the normal case.
2741 // But if using the firstlanguage, the closing may be missing
2743 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2745 if (actual._dataEnd < end)
2746 output_end = interval_.nextNotIgnored(actual._dataEnd);
2747 else if (interval_.par.size() > (size_t) end)
2748 output_end = interval_.nextNotIgnored(end);
2750 output_end = interval_.par.size();
2751 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2752 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2754 // Remove possible empty data
2755 int dstart = interval_.nextNotIgnored(actual._dataStart);
2756 while (interval_.isOpeningPar(dstart) == 1) {
2757 interval_.addIntervall(dstart, dstart+1);
2758 int dend = interval_.findclosing(dstart+1, output_end);
2759 interval_.addIntervall(dend, dend+1);
2760 dstart = interval_.nextNotIgnored(dstart+1);
2762 if (dstart < output_end)
2763 interval_.output(os, output_end);
2765 interval_.addIntervall(0, end);
2767 interval_.addIntervall(actual._tokenstart, end);
2771 string splitOnKnownMacros(string par, bool isPatternString)
2774 LatexInfo li(par, isPatternString);
2775 // LYXERR(Debug::INFO, "Berfore split: " << par);
2776 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2778 DummyKey._tokensize = 0;
2779 DummyKey._dataStart = 0;
2780 DummyKey._dataEnd = par.length();
2781 DummyKey.disabled = true;
2782 int firstkeyIdx = li.getFirstKey();
2784 if (firstkeyIdx >= 0) {
2785 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2786 DummyKey._tokenstart = firstKey._tokenstart;
2788 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2789 // Use dummy firstKey
2790 firstKey = DummyKey;
2791 (void) li.setNextKey(firstkeyIdx);
2794 if (par.substr(firstKey._dataStart, 2) == "% ")
2795 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2797 nextkeyIdx = li.process(os, firstKey);
2798 while (nextkeyIdx >= 0) {
2799 // Check for a possible gap between the last
2800 // entry and this one
2801 int datastart = li.nextNotIgnored(firstKey._dataStart);
2802 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2803 if ((nextKey._tokenstart > datastart)) {
2805 firstKey._dataStart = datastart;
2806 firstKey._dataEnd = par.length();
2807 (void) li.setNextKey(nextkeyIdx);
2808 // Fake the last opened parenthesis
2809 li.setForDefaultLang(firstKey);
2810 nextkeyIdx = li.process(os, firstKey);
2813 if (nextKey.keytype != KeyInfo::isMain) {
2814 firstKey._dataStart = datastart;
2815 firstKey._dataEnd = nextKey._dataEnd+1;
2816 (void) li.setNextKey(nextkeyIdx);
2817 li.setForDefaultLang(firstKey);
2818 nextkeyIdx = li.process(os, firstKey);
2821 nextkeyIdx = li.process(os, nextKey);
2825 // Handle the remaining
2826 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2827 firstKey._dataEnd = par.length();
2829 if ((firstKey._dataStart < firstKey._dataEnd) &&
2830 (par[firstKey._dataStart] != '}')) {
2831 li.setForDefaultLang(firstKey);
2832 (void) li.process(os, firstKey);
2836 // return string definitelly impossible to match
2837 s = "\\foreignlanguage{ignore}{ }";
2841 s = par; /* no known macros found */
2842 // LYXERR(Debug::INFO, "After split: " << s);
2847 * Try to unify the language specs in the latexified text.
2848 * Resulting modified string is set to "", if
2849 * the searched tex does not contain all the features in the search pattern
2851 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2853 static Features regex_f;
2854 static int missed = 0;
2855 static bool regex_with_format = false;
2857 int parlen = par.length();
2859 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2862 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2863 // Happens to be there in case of description or labeling environment
2868 // Split the latex input into pieces which
2869 // can be digested by our search engine
2870 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2871 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2872 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2873 string doclang = pbuf->params().language->polyglossia();
2874 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2876 bool toIgnoreLang = true;
2877 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2879 if (sub.str(2) != doclang) {
2880 toIgnoreLang = false;
2884 setIgnoreFormat("language", toIgnoreLang, false);
2887 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2888 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2891 result = par.substr(0, parlen);
2892 if (isPatternString) {
2895 regex_f = identifyFeatures(result);
2896 string features = "";
2897 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2898 string a = it->first;
2899 regex_with_format = true;
2900 features += " " + a;
2901 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2903 LYXERR(Debug::FIND, "Identified Features" << features);
2906 } else if (regex_with_format) {
2907 Features info = identifyFeatures(result);
2908 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2909 string a = it->first;
2910 bool b = it->second;
2911 if (b && ! info[a]) {
2913 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2920 // LYXERR(Debug::INFO, "No regex formats");
2926 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2927 static int identifyClosing(string & t)
2929 int open_braces = 0;
2931 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2932 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2934 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2936 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2938 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2947 static int num_replaced = 0;
2948 static bool previous_single_replace = true;
2950 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2953 // Handle \w properly
2954 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2955 if (! opt.casesensitive) {
2956 popts |= QRegularExpression::CaseInsensitiveOption;
2958 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2959 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2961 if (regexp.isValid() && regexp2.isValid()) {
2962 regexIsValid = true;
2963 // Check '{', '}' pairs inside the regex
2966 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2967 char c = par_as_string[i];
2974 else if (c == '}') {
2981 if (balanced != 0) {
2982 regexIsValid = false;
2983 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2987 regexIsValid = false;
2988 if (!regexp.isValid())
2989 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2991 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2994 if (opt.casesensitive) {
2995 regexp = regex(regexp_str);
2996 regexp2 = regex(regexp2_str);
2999 regexp = regex(regexp_str, std::regex_constants::icase);
3000 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3005 static void modifyRegexForMatchWord(string &t)
3008 regex wordre("(\\\\)*((\\.|\\\\b))");
3011 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3013 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3016 else if (sub.str(2) == "\\\\b")
3018 if (lastpos < (size_t) sub.position(2))
3019 s += t.substr(lastpos, sub.position(2) - lastpos);
3021 lastpos = sub.position(2) + sub.length(2);
3024 s = "\\b" + t + "\\b";
3028 else if (lastpos < t.length())
3029 s += t.substr(lastpos, t.length() - lastpos);
3030 t = "\\b" + s + "\\b";
3033 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3034 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3036 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3037 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3038 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3039 if (opt.replace_all && previous_single_replace) {
3040 previous_single_replace = false;
3043 else if (!opt.replace_all) {
3044 num_replaced = 0; // count number of replaced strings
3045 previous_single_replace = true;
3047 // When using regexp, braces are hacked already by escape_for_regex()
3048 par_as_string = normalize(ds);
3050 close_wildcards = 0;
3052 size_t lead_size = 0;
3053 // correct the language settings
3054 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3055 opt.matchAtStart = false;
3057 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3058 if (opt.ignoreformat) {
3062 lead_size = identifyLeading(par_as_string);
3064 lead_as_string = par_as_string.substr(0, lead_size);
3065 string lead_as_regex_string = string2regex(lead_as_string);
3066 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3067 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3068 /* Handle whole words too in this case
3070 if (opt.matchword) {
3071 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3072 opt.matchword = false;
3074 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3075 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3076 CreateRegexp(opt, regexp_str, regexp2_str);
3078 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3079 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3083 if (!opt.ignoreformat) {
3084 lead_size = identifyLeading(par_as_string);
3085 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3086 lead_as_string = par_as_string.substr(0, lead_size);
3087 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3090 // Here we are using regexp
3091 LASSERT(use_regexp, /**/);
3093 string lead_as_regexp;
3094 if (lead_size > 0) {
3095 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3096 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3097 par_as_string = par_as_string_nolead;
3098 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3099 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3101 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3102 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3103 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3104 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3106 size_t lng = par_as_string.size();
3107 if (!opt.ignoreformat) {
3108 // Remove extra '\}' at end if not part of \{\.\}
3110 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3112 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3121 if (lng < par_as_string.size())
3122 par_as_string = par_as_string.substr(0,lng);
3124 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3125 if ((lng > 0) && (par_as_string[0] == '^')) {
3126 par_as_string = par_as_string.substr(1);
3128 opt.matchAtStart = true;
3130 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3131 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3132 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3134 // If entered regexp must match at begin of searched string buffer
3135 // Kornel: Added parentheses to use $1 for size of the leading string
3139 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3140 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3141 // so the convert has no effect in that case
3142 for (int i = 7; i > 0; --i) {
3143 string orig = "\\\\" + std::to_string(i);
3144 string dest = "\\" + std::to_string(i+2);
3145 while (regex_replace(par_as_string, par_as_string, orig, dest));
3147 if (opt.matchword) {
3148 modifyRegexForMatchWord(par_as_string);
3149 opt.matchword = false;
3151 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3152 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3154 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3155 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3156 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3160 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3164 mres.searched_size = len;
3166 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3169 docstring docstr = stringifyFromForSearch(opt, cur, len);
3171 str = normalize(docstr);
3172 if (!opt.ignoreformat) {
3173 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3174 // remove closing '}' and '\n' to allow for use of '$' in regex
3175 size_t lng = str.size();
3176 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3178 if (lng != str.size()) {
3179 str = str.substr(0, lng);
3183 mres.match_len = -1;
3186 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3188 LASSERT(use_regexp, /**/);
3190 // use_regexp always true
3191 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3193 QString qstr = QString::fromStdString(str);
3194 QRegularExpression const *p_regexp;
3195 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3199 p_regexp = ®exp2;
3201 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3202 if (!match.hasMatch())
3205 regex const *p_regexp;
3206 regex_constants::match_flag_type flags;
3208 flags = regex_constants::match_continuous;
3211 flags = regex_constants::match_default;
3212 p_regexp = ®exp2;
3214 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3215 if (re_it == sregex_iterator())
3217 match_results<string::const_iterator> const & m = *re_it;
3219 // Whole found string, including the leading
3220 // std: m[0].second - m[0].first
3221 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3223 // Size of the leading string
3224 // std: m[1].second - m[1].first
3225 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3226 int leadingsize = 0;
3228 if (match.lastCapturedIndex() > 0) {
3229 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3234 leadingsize = m[1].second - m[1].first;
3238 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3239 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3240 // because of different number of closing at end of string
3241 // we have to 'unify' the length of the post-match.
3242 // Done by ignoring closing parenthesis and linefeeds at string end
3243 int matchend = match.capturedEnd(0);
3244 size_t strsize = qstr.size();
3245 if (!opt.ignoreformat) {
3246 while (mres.match_len > 0) {
3247 QChar c = qstr.at(matchend - 1);
3248 if ((c == '\n') || (c == '}') || (c == '{')) {
3255 while (strsize > (size_t) match.capturedEnd(0)) {
3256 QChar c = qstr.at(strsize-1);
3257 if ((c == '\n') || (c == '}')) {
3264 // LYXERR0(qstr.toStdString());
3265 mres.match2end = strsize - matchend;
3266 mres.pos = match.capturedStart(2);
3268 mres.match_prefix = m[2].second - m[2].first;
3269 mres.match_len = m[0].second - m[2].second;
3270 // ignore closing parenthesis and linefeeds at string end
3271 size_t strend = m[0].second - m[0].first;
3272 int matchend = strend;
3273 size_t strsize = str.size();
3274 if (!opt.ignoreformat) {
3275 while (mres.match_len > 0) {
3276 char c = str.at(matchend - 1);
3277 if ((c == '\n') || (c == '}') || (c == '{')) {
3284 while (strsize > strend) {
3285 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3293 mres.match2end = strsize - matchend;
3294 mres.pos = m[2].first - m[0].first;;
3296 if (mres.match2end < 0)
3298 mres.leadsize = leadingsize;
3300 if (mres.match_len > 0) {
3301 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3302 mres.result.push_back(a0);
3303 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3304 mres.result.push_back(match.captured(i).toStdString());
3308 if (mres.match_len > 0) {
3309 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3310 mres.result.push_back(a0);
3311 for (size_t i = 3; i < m.size(); i++) {
3312 mres.result.push_back(m[i]);
3321 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3323 MatchResult mres = findAux(cur, len, at_begin);
3324 int res = mres.match_len;
3326 "res=" << res << ", at_begin=" << at_begin
3327 << ", matchAtStart=" << opt.matchAtStart
3328 << ", inTexted=" << cur.inTexted());
3329 if (opt.matchAtStart) {
3332 else if (mres.match_prefix > 0)
3341 static bool simple_replace(string &t, string from, string to)
3343 regex repl("(\\\\)*(" + from + ")");
3347 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3349 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3351 if (lastpos < (size_t) sub.position(2))
3352 s += t.substr(lastpos, sub.position(2) - lastpos);
3354 lastpos = sub.position(2) + sub.length(2);
3358 else if (lastpos < t.length())
3359 s += t.substr(lastpos, t.length() - lastpos);
3365 string MatchStringAdv::normalize(docstring const & s) const
3368 t = lyx::to_utf8(s);
3369 // Remove \n at begin
3370 while (!t.empty() && t[0] == '\n')
3373 while (!t.empty() && t[t.size() - 1] == '\n')
3374 t = t.substr(0, t.size() - 1);
3376 // Handle all other '\n'
3377 while ((pos = t.find("\n")) != string::npos) {
3378 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3380 if (isAlnumASCII(t[pos+1])) {
3381 t.replace(pos-2, 3, " ");
3384 t.replace(pos-2, 3, "");
3387 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3388 // '\n' adjacent to non-alpha-numerics, discard
3389 t.replace(pos, 1, "");
3392 // Replace all other \n with spaces
3393 t.replace(pos, 1, " ");
3396 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3397 // Kornel: Added textsl, textsf, textit, texttt and noun
3398 // + allow to seach for colored text too
3399 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3400 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3401 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3402 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3403 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3404 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3410 docstring stringifyFromCursor(DocIterator const & cur, int len)
3412 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3413 if (cur.inTexted()) {
3414 Paragraph const & par = cur.paragraph();
3415 // TODO what about searching beyond/across paragraph breaks ?
3416 // TODO Try adding a AS_STR_INSERTS as last arg
3417 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3418 int(par.size()) : cur.pos() + len;
3419 // OutputParams runparams(&cur.buffer()->params().encoding());
3420 OutputParams runparams(encodings.fromLyXName("utf8"));
3421 runparams.nice = true;
3422 runparams.flavor = Flavor::XeTeX;
3423 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3424 // No side effect of file copying and image conversion
3425 runparams.dryrun = true;
3426 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3427 if (ignoreFormats.getDeleted()) {
3428 option |= AS_STR_SKIPDELETE;
3429 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3432 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3434 LYXERR(Debug::FIND, "Stringifying with cur: "
3435 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3436 return par.asString(cur.pos(), end,
3439 } else if (cur.inMathed()) {
3440 CursorSlice cs = cur.top();
3441 MathData md = cs.cell();
3442 MathData::const_iterator it_end =
3443 (( len == -1 || cs.pos() + len > int(md.size()))
3445 : md.begin() + cs.pos() + len );
3447 for (MathData::const_iterator it = md.begin() + cs.pos();
3450 docstring s = asString(md2);
3451 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3454 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3459 /** Computes the LaTeX export of buf starting from cur and ending len positions
3460 * after cur, if len is positive, or at the paragraph or innermost inset end
3463 docstring latexifyFromCursor(DocIterator const & cur, int len)
3466 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3467 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3468 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3470 Buffer const & buf = *cur.buffer();
3472 odocstringstream ods;
3474 //OutputParams runparams(&buf.params().encoding());
3475 OutputParams runparams(encodings.fromLyXName("utf8"));
3476 runparams.nice = false;
3477 runparams.flavor = Flavor::XeTeX;
3478 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3479 // No side effect of file copying and image conversion
3480 runparams.dryrun = true;
3481 if (ignoreFormats.getDeleted()) {
3482 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3485 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3488 if (cur.inTexted()) {
3489 // @TODO what about searching beyond/across paragraph breaks ?
3490 pos_type endpos = cur.paragraph().size();
3491 if (len != -1 && endpos > cur.pos() + len)
3492 endpos = cur.pos() + len;
3493 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3494 string(), cur.pos(), endpos);
3495 string s = lyx::to_utf8(ods.str());
3496 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3497 return(lyx::from_utf8(s));
3498 } else if (cur.inMathed()) {
3499 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3500 for (int s = cur.depth() - 1; s >= 0; --s) {
3501 CursorSlice const & cs = cur[s];
3502 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3503 TeXMathStream ws(os);
3504 cs.asInsetMath()->asHullInset()->header_write(ws);
3509 CursorSlice const & cs = cur.top();
3510 MathData md = cs.cell();
3511 MathData::const_iterator it_end =
3512 ((len == -1 || cs.pos() + len > int(md.size()))
3514 : md.begin() + cs.pos() + len);
3516 for (MathData::const_iterator it = md.begin() + cs.pos();
3520 ods << asString(md2);
3521 // Retrieve the math environment type, and add '$' or '$]'
3522 // or others (\end{equation}) accordingly
3523 for (int s = cur.depth() - 1; s >= 0; --s) {
3524 CursorSlice const & cs2 = cur[s];
3525 InsetMath * inset = cs2.asInsetMath();
3526 if (inset && inset->asHullInset()) {
3527 TeXMathStream ws(os);
3528 inset->asHullInset()->footer_write(ws);
3532 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3534 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3539 #if defined(ResultsDebug)
3541 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3543 LYXERR0( "from:\t\t\t" << from);
3545 if (mres.pos_len > 0) {
3547 status = "FINALSEARCH";
3550 if (mres.match_len > 0) {
3551 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3552 status = "Good Match";
3554 status = "Matched in";
3557 status = "MissedSearch";
3560 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3561 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3562 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3563 if ((mres.pos > 0) || (mres.match_prefix > 0))
3564 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3565 for (size_t i = 0; i < mres.result.size(); i++)
3566 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3568 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3570 #define displayMres(s, txt, cur)
3573 /** Finalize an advanced find operation, advancing the cursor to the innermost
3574 ** position that matches, plus computing the length of the matching text to
3576 ** Return the cur.pos() difference between start and end of found match
3578 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3580 // Search the foremost position that matches (avoids find of entire math
3581 // inset when match at start of it)
3582 DocIterator old_cur(cur.buffer());
3584 static MatchResult fail = MatchResult();
3585 MatchResult max_match;
3586 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3587 // Happens with e.g. hyperlinks
3588 // either one sees "http://www.bla.bla" or nothing
3589 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3590 // and although we search for only 3 chars, we find the whole hyperlink inset
3591 bool at_begin = (expected.match_prefix == 0);
3592 if (!match.opt.forward && match.opt.ignoreformat) {
3593 if (expected.pos > 0)
3596 LASSERT(at_begin, /**/);
3597 if (expected.match_len > 0 && at_begin) {
3598 // Search for deepest match
3600 max_match = expected;
3602 size_t d = cur.depth();
3606 if (cur.depth() < d)
3608 if (cur.depth() == d)
3611 while (cur && cur.depth() > lastd) {
3612 lastd = cur.depth();
3613 mres = match(cur, -1, at_begin);
3614 displayMres(mres, "Checking innermost", cur);
3615 if (mres.match_len > 0)
3620 if (mres.match_len < expected.match_len)
3628 // (expected.match_len <= 0)
3629 mres = match(cur); /* match valid only if not searching whole words */
3630 displayMres(mres, "Start with negative match", cur);
3633 if (max_match.match_len <= 0) return fail;
3634 LYXERR(Debug::FIND, "Ok");
3636 // Compute the match length
3638 if (cur.pos() + len > cur.lastpos())
3641 LASSERT(match.use_regexp, /**/);
3644 int maxl = cur.lastpos() - cur.pos();
3645 // Greedy behaviour while matching regexps
3646 while (maxl > minl) {
3648 mres2 = match(cur, len, at_begin);
3649 displayMres(mres2, "Finalize loop", cur);
3650 int actual_match_len = mres2.match_len;
3651 if (actual_match_len >= max_match.match_len) {
3652 // actual_match_len > max_match _can_ happen,
3653 // if the search area splits
3654 // some following word so that the regex
3655 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3657 // This means, the len value is too big
3658 actual_match_len = max_match.match_len;
3660 max_match.match_len = actual_match_len;
3662 if (maxl - minl < 4)
3663 len = (int)((maxl + minl)/2);
3665 len = (int)(minl + (maxl - minl + 3)/4);
3668 // (actual_match_len < max_match.match_len)
3670 len = (int)((maxl + minl)/2);
3675 // Search for real start of matched characters
3677 MatchResult actual_match;
3680 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3681 if (cur.depth() < old_cur.depth()) {
3683 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3686 if (cur.pos() != old_cur.pos()) {
3687 // OK, forwarded 1 pos in actual inset
3688 actual_match = match(cur, len-1, at_begin);
3689 if (actual_match.match_len == max_match.match_len) {
3690 // Ha, got it! The shorter selection has the same match length
3693 max_match = actual_match;
3696 // OK, the shorter selection matches less chars, revert to previous value
3702 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3703 actual_match = match(cur, len, at_begin);
3704 if (actual_match.match_len == max_match.match_len) {
3706 max_match = actual_match;
3713 max_match.pos_len = len;
3714 displayMres(max_match, "SEARCH RESULT", cur)
3721 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3725 bool repeat = false;
3726 DocIterator orig_cur; // to be used if repeat not successful
3727 MatchResult orig_mres;
3728 while (!theApp()->longOperationCancelled() && cur) {
3729 //(void) findAdvForwardInnermost(cur);
3730 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3731 MatchResult mres = match(cur, -1, false);
3732 string msg = "Starting";
3735 displayMres(mres, msg + " findForwardAdv", cur)
3736 int match_len = mres.match_len;
3737 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3738 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3741 if (match_len <= 0) {
3742 // This should exit nested insets, if any, or otherwise undefine the currsor.
3743 cur.pos() = cur.lastpos();
3744 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3747 else { // match_len > 0
3748 // Try to find the begin of searched string
3750 int firstInvalid = cur.lastpos() - cur.pos();
3752 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3753 int incrcur = (firstInvalid + 1 )*3/4;
3754 if (incrcur < incrmatch)
3755 increment = incrcur;
3757 increment = incrmatch;
3761 LYXERR(Debug::FIND, "Set increment to " << increment);
3762 while (increment > 0) {
3763 DocIterator old_cur = cur;
3764 if (cur.pos() + increment >= cur.lastpos()) {
3768 cur.pos() = cur.pos() + increment;
3769 MatchResult mres2 = match(cur, -1, false);
3770 displayMres(mres2, "findForwardAdv loop", cur)
3771 switch (interpretMatch(mres, mres2)) {
3772 case MatchResult::newIsTooFar:
3773 // behind the expected match
3774 firstInvalid = increment;
3778 case MatchResult::newIsBetter:
3779 // not reached yet, but cur.pos()+increment is bettert
3781 firstInvalid -= increment;
3782 if (increment > firstInvalid*3/4)
3783 increment = firstInvalid*3/4;
3784 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3785 if (increment >= mres2.match_prefix)
3786 increment = (mres2.match_prefix+1)*3/4;
3791 // Handle not like MatchResult::newIsTooFar
3792 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3794 increment = increment*3/4;
3799 if (mres.match_len > 0) {
3800 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3801 // The match seems to indicate some deeper level
3810 // should never be reached.
3814 // LYXERR0("Leaving first loop");
3815 LYXERR(Debug::FIND, "Finalizing 1");
3816 MatchResult found_match = findAdvFinalize(cur, match, mres);
3817 if (found_match.match_len > 0) {
3818 LASSERT(found_match.pos_len > 0, /**/);
3819 match.FillResults(found_match);
3820 return found_match.pos_len;
3823 // try next possible match
3834 /// Find the most backward consecutive match within same paragraph while searching backwards.
3835 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3837 DocIterator cur_begin = cur;
3838 cur_begin.pos() = 0;
3839 DocIterator tmp_cur = cur;
3840 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3841 Inset & inset = cur.inset();
3842 for (; cur != cur_begin; cur.backwardPos()) {
3843 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3844 DocIterator new_cur = cur;
3845 new_cur.backwardPos();
3846 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3848 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3849 if (new_mr.match_len == mr.match_len)
3853 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3859 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3863 // Backup of original position
3864 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3865 if (cur == cur_begin)
3868 DocIterator cur_orig(cur);
3869 bool pit_changed = false;
3872 MatchResult found_match = match(cur, -1, false);
3874 if (found_match.match_len > 0) {
3876 cur.pos() = cur.lastpos();
3878 cur.pos() = cur_orig.pos();
3879 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3880 DocIterator cur_prev_iter;
3882 found_match = match(cur);
3883 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3884 << (found_match.match_len > 0) << ", cur: " << cur);
3885 if (found_match.match_len > 0) {
3886 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3887 if (found_mr.pos_len > 0) {
3888 match.FillResults(found_mr);
3889 return found_mr.pos_len;
3893 // Stop if begin of document reached
3894 if (cur == cur_begin)
3896 cur_prev_iter = cur;
3900 if (cur == cur_begin)
3907 } while (!theApp()->longOperationCancelled());
3915 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3916 DocIterator const & cur, int len)
3918 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3920 if (!opt.ignoreformat)
3921 return latexifyFromCursor(cur, len);
3923 return stringifyFromCursor(cur, len);
3927 FindAndReplaceOptions::FindAndReplaceOptions(
3928 docstring const & _find_buf_name, bool _casesensitive,
3929 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3930 docstring const & _repl_buf_name, bool _keep_case,
3931 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3932 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3933 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3934 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3942 /** Check if 'len' letters following cursor are all non-lowercase */
3943 static bool allNonLowercase(Cursor const & cur, int len)
3945 pos_type beg_pos = cur.selectionBegin().pos();
3946 pos_type end_pos = cur.selectionBegin().pos() + len;
3947 if (len > cur.lastpos() + 1 - beg_pos) {
3948 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3949 len = cur.lastpos() + 1 - beg_pos;
3950 end_pos = beg_pos + len;
3952 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3953 if (isLowerCase(cur.paragraph().getChar(pos)))
3959 /** Check if first letter is upper case and second one is lower case */
3960 static bool firstUppercase(Cursor const & cur)
3963 pos_type pos = cur.selectionBegin().pos();
3964 if (pos >= cur.lastpos() - 1) {
3965 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3968 ch1 = cur.paragraph().getChar(pos);
3969 ch2 = cur.paragraph().getChar(pos + 1);
3970 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3971 LYXERR(Debug::FIND, "firstUppercase(): "
3972 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3973 << ch2 << "(" << char(ch2) << ")"
3974 << ", result=" << result << ", cur=" << cur);
3979 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3981 ** \fixme What to do with possible further paragraphs in replace buffer ?
3983 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3985 ParagraphList::iterator pit = buffer.paragraphs().begin();
3986 LASSERT(!pit->empty(), /**/);
3987 pos_type right = pos_type(1);
3988 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3989 right = pit->size();
3990 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3994 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3996 // Should replace the string "$" + std::to_string(matchnum) with replacement
3997 // if the char '$' is not prefixed with odd number of char '\\'
3998 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4002 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4004 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4006 int num = stoi(sub.str(3), nullptr, 10);
4007 if (num >= maxmatchnum)
4009 if (lastpos < (size_t) sub.position(2))
4010 s += t.substr(lastpos, sub.position(2) - lastpos);
4011 s += replacements[num];
4012 lastpos = sub.position(2) + sub.length(2);
4016 else if (lastpos < t.length())
4017 s += t.substr(lastpos, t.length() - lastpos);
4023 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4025 Cursor & cur = bv->cursor();
4026 if (opt.repl_buf_name.empty()
4027 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4028 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4031 DocIterator sel_beg = cur.selectionBegin();
4032 DocIterator sel_end = cur.selectionEnd();
4033 if (&sel_beg.inset() != &sel_end.inset()
4034 || sel_beg.pit() != sel_end.pit()
4035 || sel_beg.idx() != sel_end.idx())
4037 int sel_len = sel_end.pos() - sel_beg.pos();
4038 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4039 << ", sel_len: " << sel_len << endl);
4042 LASSERT(sel_len > 0, return 0);
4044 if (!matchAdv(sel_beg, sel_len).match_len)
4047 // Build a copy of the replace buffer, adapted to the KeepCase option
4048 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4050 repl_buffer_orig.write(oss);
4051 string lyx = oss.str();
4052 if (matchAdv.valid_matches > 0) {
4053 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4055 Buffer repl_buffer("", false);
4056 repl_buffer.setUnnamed(true);
4057 LASSERT(repl_buffer.readString(lyx), return 0);
4058 if (opt.keep_case && sel_len >= 2) {
4059 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4060 if (cur.inTexted()) {
4061 if (firstUppercase(cur))
4062 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4063 else if (allNonLowercase(cur, sel_len))
4064 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4067 cap::cutSelection(cur, false);
4068 if (cur.inTexted()) {
4069 repl_buffer.changeLanguage(
4070 repl_buffer.language(),
4071 cur.getFont().language());
4072 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4073 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4074 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4075 repl_buffer.params().documentClassPtr(),
4076 repl_buffer.params().authors(),
4077 bv->buffer().errorList("Paste"));
4078 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4079 sel_len = repl_buffer.paragraphs().begin()->size();
4080 } else if (cur.inMathed()) {
4081 odocstringstream ods;
4083 // OutputParams runparams(&repl_buffer.params().encoding());
4084 OutputParams runparams(encodings.fromLyXName("utf8"));
4085 runparams.nice = false;
4086 runparams.flavor = Flavor::XeTeX;
4087 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4088 runparams.dryrun = true;
4089 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4090 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4091 docstring repl_latex = ods.str();
4092 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4094 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4095 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4096 repl_latex = from_utf8(s);
4097 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4098 MathData ar(cur.buffer());
4099 asArray(repl_latex, ar, Parse::NORMAL);
4101 sel_len = ar.size();
4102 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4104 if (cur.pos() >= sel_len)
4105 cur.pos() -= sel_len;
4108 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4109 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4110 bv->processUpdateFlags(Update::Force);
4115 /// Perform a FindAdv operation.
4116 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4121 // e.g., when invoking word-findadv from mini-buffer wither with
4122 // wrong options syntax or before ever opening advanced F&R pane
4123 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4127 MatchStringAdv matchAdv(bv->buffer(), opt);
4129 if (!matchAdv.regexIsValid) {
4130 bv->message(lyx::from_utf8(matchAdv.regexError));
4134 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4136 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4137 num_replaced += findAdvReplace(bv, opt, matchAdv);
4140 pos_len = findForwardAdv(cur, matchAdv);
4142 pos_len = findBackwardsAdv(cur, matchAdv);
4143 } catch (exception & ex) {
4144 bv->message(from_utf8(ex.what()));
4149 if (num_replaced > 0) {
4150 switch (num_replaced)
4153 bv->message(_("One match has been replaced."));
4156 bv->message(_("Two matches have been replaced."));
4159 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4165 bv->message(_("Match not found."));
4170 if (num_replaced > 0)
4171 bv->message(_("Match has been replaced."));
4173 bv->message(_("Match found."));
4175 if (cur.pos() + pos_len > cur.lastpos()) {
4176 // Prevent crash in bv->putSelectionAt()
4177 // Should never happen, maybe LASSERT() here?
4178 pos_len = cur.lastpos() - cur.pos();
4180 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4181 bv->putSelectionAt(cur, pos_len, !opt.forward);
4187 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4189 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4190 << opt.casesensitive << ' '
4191 << opt.matchword << ' '
4192 << opt.forward << ' '
4193 << opt.expandmacros << ' '
4194 << opt.ignoreformat << ' '
4195 << opt.replace_all << ' '
4196 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4197 << opt.keep_case << ' '
4198 << int(opt.scope) << ' '
4201 LYXERR(Debug::FIND, "built: " << os.str());
4207 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4209 // LYXERR(Debug::FIND, "parsing");
4213 while (line != "EOSS") {
4217 if (is.eof()) // Tolerate malformed request
4221 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4222 opt.find_buf_name = from_utf8(s);
4223 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4224 is.get(); // Waste space before replace string
4227 while (line != "EOSS") {
4231 if (is.eof()) // Tolerate malformed request
4235 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4236 opt.repl_buf_name = from_utf8(s);
4237 is >> opt.keep_case;
4240 opt.scope = FindAndReplaceOptions::SearchScope(i);
4242 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4245 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4246 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4247 << opt.scope << ' ' << opt.restr);