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)
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"));
266 bool findOne(BufferView * bv, docstring const & searchstr,
267 bool case_sens, bool whole, bool forward,
268 bool find_del = true, bool check_wrap = false)
270 if (!searchAllowed(searchstr))
273 DocIterator cur = forward
274 ? bv->cursor().selectionEnd()
275 : bv->cursor().selectionBegin();
277 MatchString const match(searchstr, case_sens, whole);
279 int match_len = forward
280 ? findForward(cur, match, find_del)
281 : findBackwards(cur, match, find_del);
284 bv->putSelectionAt(cur, match_len, !forward);
285 else if (check_wrap) {
286 DocIterator cur_orig(bv->cursor());
289 q = _("End of file reached while searching forward.\n"
290 "Continue searching from the beginning?");
292 q = _("Beginning of file reached while searching backward.\n"
293 "Continue searching from the end?");
294 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
295 q, 0, 1, _("&Yes"), _("&No"));
296 if (wrap_answer == 0) {
298 bv->cursor().clear();
299 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
301 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
302 bv->cursor().backwardPos();
304 bv->clearSelection();
305 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
308 bv->cursor().setCursor(cur_orig);
312 return match_len > 0;
316 int replaceAll(BufferView * bv,
317 docstring const & searchstr, docstring const & replacestr,
318 bool case_sens, bool whole)
320 Buffer & buf = bv->buffer();
322 if (!searchAllowed(searchstr) || buf.isReadonly())
325 DocIterator cur_orig(bv->cursor());
327 MatchString const match(searchstr, case_sens, whole);
330 int const rsize = replacestr.size();
331 int const ssize = searchstr.size();
334 cur.setCursor(doc_iterator_begin(&buf));
335 int match_len = findForward(cur, match, false);
336 while (match_len > 0) {
337 // Backup current cursor position and font.
338 pos_type const pos = cur.pos();
339 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
341 int striked = ssize -
342 cur.paragraph().eraseChars(pos, pos + match_len,
343 buf.params().track_changes);
344 cur.paragraph().insert(pos, replacestr, font,
345 Change(buf.params().track_changes
347 : Change::UNCHANGED));
348 for (int i = 0; i < rsize + striked; ++i)
351 match_len = findForward(cur, match, false);
354 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
356 cur_orig.fixIfBroken();
357 bv->setCursor(cur_orig);
363 // the idea here is that we are going to replace the string that
364 // is selected IF it is the search string.
365 // if there is a selection, but it is not the search string, then
366 // we basically ignore it. (FIXME We ought to replace only within
368 // if there is no selection, then:
369 // (i) if some search string has been provided, then we find it.
370 // (think of how the dialog works when you hit "replace" the
372 // (ii) if no search string has been provided, then we treat the
373 // word the cursor is in as the search string. (why? i have no
374 // idea.) but this only works in text?
376 // returns the number of replacements made (one, if any) and
377 // whether anything at all was done.
378 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
379 docstring const & replacestr, bool case_sens,
380 bool whole, bool forward, bool findnext)
382 Cursor & cur = bv->cursor();
383 if (!cur.selection()) {
384 // no selection, non-empty search string: find it
385 if (!searchstr.empty()) {
386 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
387 return make_pair(found, 0);
389 // empty search string
392 return make_pair(false, 0);
393 // select current word and treat it as the search string.
394 // This causes a minor bug as undo will restore this selection,
395 // which the user did not create (#8986).
396 cur.innerText()->selectWord(cur, WHOLE_WORD);
397 searchstr = cur.selectionAsString(false, true);
400 // if we still don't have a search string, report the error
402 if (!searchAllowed(searchstr))
403 return make_pair(false, 0);
405 bool have_selection = cur.selection();
406 docstring const selected = cur.selectionAsString(false, true);
409 ? searchstr == selected
410 : compare_no_case(searchstr, selected) == 0;
412 // no selection or current selection is not search word:
413 // just find the search word
414 if (!have_selection || !match) {
415 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
416 return make_pair(found, 0);
419 // we're now actually ready to replace. if the buffer is
420 // read-only, we can't, though.
421 if (bv->buffer().isReadonly())
422 return make_pair(false, 0);
424 cap::replaceSelectionWithString(cur, replacestr);
426 cur.pos() += replacestr.length();
427 LASSERT(cur.pos() <= cur.lastpos(),
428 cur.pos() = cur.lastpos());
431 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
433 return make_pair(true, 1);
439 docstring const find2string(docstring const & search,
440 bool casesensitive, bool matchword, bool forward)
444 << int(casesensitive) << ' '
445 << int(matchword) << ' '
451 docstring const replace2string(docstring const & replace,
452 docstring const & search,
453 bool casesensitive, bool matchword,
454 bool all, bool forward, bool findnext)
457 ss << replace << '\n'
459 << int(casesensitive) << ' '
460 << int(matchword) << ' '
462 << int(forward) << ' '
468 docstring const string2find(docstring const & argument,
473 // data is of the form
475 // <casesensitive> <matchword> <forward>"
477 docstring howto = split(argument, search, '\n');
479 casesensitive = parse_bool(howto);
480 matchword = parse_bool(howto);
481 forward = parse_bool(howto);
487 bool lyxfind(BufferView * bv, FuncRequest const & ev)
489 if (!bv || ev.action() != LFUN_WORD_FIND)
492 //lyxerr << "find called, cmd: " << ev << endl;
496 docstring search = string2find(ev.argument(), casesensitive, matchword, forward);
498 return findOne(bv, search, casesensitive, matchword, forward, false, true);
502 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
504 if (!bv || ev.action() != LFUN_WORD_REPLACE)
507 // data is of the form
510 // <casesensitive> <matchword> <all> <forward> <findnext>"
513 docstring howto = split(ev.argument(), rplc, '\n');
514 howto = split(howto, search, '\n');
516 bool casesensitive = parse_bool(howto);
517 bool matchword = parse_bool(howto);
518 bool all = parse_bool(howto);
519 bool forward = parse_bool(howto);
520 bool findnext = howto.empty() ? true : parse_bool(howto);
524 int replace_count = 0;
526 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
527 update = replace_count > 0;
530 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
532 replace_count = rv.second;
535 Buffer const & buf = bv->buffer();
537 // emit message signal.
538 buf.message(_("String not found."));
540 if (replace_count == 0) {
541 buf.message(_("String found."));
542 } else if (replace_count == 1) {
543 buf.message(_("String has been replaced."));
545 docstring const str =
546 bformat(_("%1$d strings have been replaced."), replace_count);
554 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
556 for (; cur; cur.forwardPos())
557 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
561 DocIterator cur_orig(bv->cursor());
562 docstring q = _("End of file reached while searching forward.\n"
563 "Continue searching from the beginning?");
564 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
565 q, 0, 1, _("&Yes"), _("&No"));
566 if (wrap_answer == 0) {
567 bv->cursor().clear();
568 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
569 bv->clearSelection();
570 cur.setCursor(bv->cursor().selectionBegin());
571 if (findNextChange(bv, cur, false))
574 bv->cursor().setCursor(cur_orig);
581 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
583 for (cur.backwardPos(); cur; cur.backwardPos()) {
584 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
589 DocIterator cur_orig(bv->cursor());
590 docstring q = _("Beginning of file reached while searching backward.\n"
591 "Continue searching from the end?");
592 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
593 q, 0, 1, _("&Yes"), _("&No"));
594 if (wrap_answer == 0) {
595 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
596 bv->cursor().backwardPos();
597 bv->clearSelection();
598 cur.setCursor(bv->cursor().selectionBegin());
599 if (findPreviousChange(bv, cur, false))
602 bv->cursor().setCursor(cur_orig);
609 bool selectChange(Cursor & cur, bool forward)
611 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
613 Change ch = cur.paragraph().lookupChange(cur.pos());
615 CursorSlice tip1 = cur.top();
616 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
617 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
618 if (!ch2.isSimilarTo(ch))
621 CursorSlice tip2 = cur.top();
622 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
624 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
625 if (!ch2.isSimilarTo(ch)) {
626 // take a step forward to correctly set the selection
634 cur.bv().mouseSetCursor(cur, false);
636 cur.bv().mouseSetCursor(cur, true);
644 bool findChange(BufferView * bv, bool forward)
647 cur.setCursor(forward ? bv->cursor().selectionEnd()
648 : bv->cursor().selectionBegin());
649 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
650 return selectChange(cur, forward);
655 bool findNextChange(BufferView * bv)
657 return findChange(bv, true);
661 bool findPreviousChange(BufferView * bv)
663 return findChange(bv, false);
670 typedef vector<pair<string, string> > Escapes;
672 string string2regex(string in)
674 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
675 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
680 while (fl_pos < temp.size()) {
681 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
682 if (fl_pos == string::npos)
685 temp2 += temp.substr(lastpos, fl_pos - lastpos);
691 if (lastpos < temp.size()) {
692 temp2 += temp.substr(lastpos, temp.size() - lastpos);
697 string correctRegex(string t, bool withformat)
699 /* Convert \backslash => \
700 * and \{, \}, \[, \] => {, }, [, ]
703 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
706 bool backslashed = false;
707 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
710 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
714 if (sub.str(4) == "backslash") {
717 // transforms '\backslash \{' into '\{'
719 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
720 if ((next == "\\{") || (next == "\\}")) {
726 else if (sub.str(4) == "mathcircumflex")
728 else if (backslashed) {
730 if (withformat && (sub.str(3) == "{"))
731 replace = accents["braceleft"];
732 else if (withformat && (sub.str(3) == "}"))
733 replace = accents["braceright"];
735 // else part should not exist
740 replace = sub.str(3);
742 if (lastpos < (size_t) sub.position(2))
743 s += t.substr(lastpos, sub.position(2) - lastpos);
745 lastpos = sub.position(2) + sub.length(2);
749 else if (lastpos < t.length())
750 s += t.substr(lastpos, t.length() - lastpos);
754 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
755 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
756 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
757 string escape_for_regex(string s, bool withformat)
761 while (lastpos < s.size()) {
762 size_t regex_pos = s.find("\\regexp{", lastpos);
763 if (regex_pos == string::npos) {
764 regex_pos = s.size();
766 if (regex_pos > lastpos) {
767 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
769 if (lastpos == s.size())
772 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
773 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
774 lastpos = end_pos + 13;
780 /// Wrapper for lyx::regex_replace with simpler interface
781 bool regex_replace(string const & s, string & t, string const & searchstr,
782 string const & replacestr)
784 regex e(searchstr, regex_constants::ECMAScript);
786 ostream_iterator<char, char> it(oss);
787 regex_replace(it, s.begin(), s.end(), e, replacestr);
788 // tolerate t and s be references to the same variable
789 bool rv = (s != oss.str());
808 vector <string> result = vector <string>();
809 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
812 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
814 if (newres.match2end < oldres.match2end)
815 return MatchResult::newIsTooFar;
816 if (newres.match_len < oldres.match_len)
817 return MatchResult::newIsTooFar;
819 if (newres.match_len == oldres.match_len) {
820 if (newres.match2end == oldres.match2end)
821 return MatchResult::newIsBetter;
823 return MatchResult::newIsInvalid;
826 /** The class performing a match between a position in the document and the FindAdvOptions.
829 class MatchStringAdv {
831 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
833 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
834 ** constructor as opt.search, under the opt.* options settings.
837 ** If set, then match is searched only against beginning of text starting at cur.
838 ** If unset, then match is searched anywhere in text starting at cur.
841 ** The length of the matching text, or zero if no match was found.
843 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
852 /// first buffer on which search was started
853 lyx::Buffer * const p_first_buf;
855 FindAndReplaceOptions const & opt;
858 /// Auxiliary find method (does not account for opt.matchword)
859 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
860 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
862 /** Normalize a stringified or latexified LyX paragraph.
866 ** <li>if search is not casesensitive, then lowercase the string;
867 ** <li>remove any newline at begin or end of the string;
868 ** <li>replace any newline in the middle of the string with a simple space;
869 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
872 ** @todo Normalization should also expand macros, if the corresponding
873 ** search option was checked.
875 string normalize(docstring const & s) const;
876 // normalized string to search
877 string par_as_string;
878 // regular expression to use for searching
879 // regexp2 is same as regexp, but prefixed with a ".*?"
881 QRegularExpression regexp;
882 QRegularExpression regexp2;
887 // leading format material as string
888 string lead_as_string;
889 // par_as_string after removal of lead_as_string
890 string par_as_string_nolead;
891 // unmatched open braces in the search string/regexp
893 // number of (.*?) subexpressions added at end of search regexp for closing
894 // environments, math mode, styles, etc...
897 // Are we searching with regular expressions ?
899 static int valid_matches;
900 static vector <string> matches;
901 void FillResults(MatchResult &found_mr);
904 int MatchStringAdv::valid_matches = 0;
905 vector <string> MatchStringAdv::matches = vector <string>(10);
907 void MatchStringAdv::FillResults(MatchResult &found_mr)
909 if (found_mr.match_len > 0) {
910 valid_matches = found_mr.result.size();
911 for (size_t i = 0; i < found_mr.result.size(); i++)
912 matches[i] = found_mr.result[i];
918 static docstring buffer_to_latex(Buffer & buffer)
920 //OutputParams runparams(&buffer.params().encoding());
921 OutputParams runparams(encodings.fromLyXName("utf8"));
922 odocstringstream ods;
924 runparams.nice = true;
925 runparams.flavor = Flavor::XeTeX;
926 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
927 // No side effect of file copying and image conversion
928 runparams.dryrun = true;
929 if (ignoreFormats.getDeleted())
930 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
932 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
933 pit_type const endpit = buffer.paragraphs().size();
934 for (pit_type pit = 0; pit != endpit; ++pit) {
935 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
936 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
942 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
945 if (!opt.ignoreformat) {
946 str = buffer_to_latex(buffer);
948 // OutputParams runparams(&buffer.params().encoding());
949 OutputParams runparams(encodings.fromLyXName("utf8"));
950 runparams.nice = true;
951 runparams.flavor = Flavor::XeTeX;
952 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
953 runparams.dryrun = true;
954 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
955 if (ignoreFormats.getDeleted()) {
956 option |= AS_STR_SKIPDELETE;
957 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
960 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
962 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
963 Paragraph const & par = buffer.paragraphs().at(pit);
964 LYXERR(Debug::FIND, "Adding to search string: '"
965 << par.asString(pos_type(0), par.size(),
969 str += par.asString(pos_type(0), par.size(),
973 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
974 string t = to_utf8(str);
975 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
982 /// Return separation pos between the leading material and the rest
983 static size_t identifyLeading(string const & s)
986 // @TODO Support \item[text]
987 // Kornel: Added textsl, textsf, textit, texttt and noun
988 // + allow to search for colored text too
989 while (regex_replace(t, t, "^\\\\(("
990 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
991 "lyxaddress|lyxrightaddress|"
992 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
993 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
994 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
995 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
996 || regex_replace(t, t, "^\\$", "")
997 || regex_replace(t, t, "^\\\\\\[", "")
998 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
999 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1001 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1006 * Given a latexified string, retrieve some handled features
1007 * The features of the regex will later be compared with the features
1008 * of the searched text. If the regex features are not a
1009 * subset of the analized, then, in not format ignoring search
1010 * we can early stop the search in the relevant inset.
1012 typedef map<string, bool> Features;
1014 static Features identifyFeatures(string const & s)
1016 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1017 static regex const valid("^("
1019 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1020 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1021 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1022 "(u|uu)line|(s|x)out|uwave|"
1023 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1024 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1029 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1032 if (sub.str(1).compare("regexp") == 0) {
1036 string token = sub.str(1);
1038 if (regex_match(token, sub2, valid)) {
1046 if (sub.str(1).compare("endregexp") == 0) {
1056 * defines values features of a key "\\[a-z]+{"
1061 /* Char type with content discarded
1062 * like \hspace{1cm} */
1064 /* Char, like \backslash */
1066 /* replace starting backslash with '#' */
1068 /* \part, \section*, ... */
1070 /* title, author etc */
1072 /* \foreignlanguage{ngerman}, ... */
1075 * to discard language in content */
1078 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1080 /* fonts, colors, markups, ... */
1082 /* footnotesize, ... large, ...
1083 * Ignore all of them */
1086 /* inputencoding, ...
1087 * Discard also content, because they do not help in search */
1090 * like remove, but also all arguments */
1092 /* item, listitem */
1094 /* tex, latex, ... like isChar */
1096 /* like \lettrine[lines=5]{}{} */
1098 // like isStandard, but always remove head
1100 /* End of arguments marker for lettrine,
1101 * so that they can be ignored */
1104 KeyInfo() = default;
1105 KeyInfo(KeyType type, int parcount, bool disable)
1107 parenthesiscount(parcount),
1108 disabled(disable) {}
1109 KeyType keytype = invalid;
1111 int _tokensize = -1;
1112 int _tokenstart = -1;
1113 int _dataStart = -1;
1115 int parenthesiscount = 1;
1116 bool disabled = false;
1117 bool used = false; /* by pattern */
1122 Border(int l=0, int u=0) : low(l), upper(u) {};
1127 #define MAXOPENED 30
1129 bool isPatternString_;
1131 explicit Intervall(bool isPattern, string const & p) :
1132 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1133 hasTitle(false), langcount(0)
1141 static vector<Border> borders;
1142 int depts[MAXOPENED];
1143 int closes[MAXOPENED];
1144 int actualdeptindex;
1145 int previousNotIgnored(int) const;
1146 int nextNotIgnored(int) const;
1147 void handleOpenP(int i);
1148 void handleCloseP(int i, bool closingAllowed);
1149 void resetOpenedP(int openPos);
1150 void addIntervall(int upper);
1151 void addIntervall(int low, int upper); /* if explicit */
1152 void removeAccents();
1153 void setForDefaultLang(KeyInfo const & defLang) const;
1154 int findclosing(int start, int end, char up, char down, int repeat);
1155 void handleParentheses(int lastpos, bool closingAllowed);
1157 int langcount; // Number of disabled language specs up to current position in actual interval
1158 int isOpeningPar(int pos) const;
1160 void output(ostringstream &os, int lastpos);
1161 // string show(int lastpos);
1164 vector<Border> Intervall::borders = vector<Border>(30);
1166 int Intervall::isOpeningPar(int pos) const
1168 if ((pos < 0) || (size_t(pos) >= par.size()))
1170 if (par[pos] != '{')
1172 if (size_t(pos) + 2 >= par.size())
1174 if (par[pos+2] != '}')
1176 if (par[pos+1] == '[' || par[pos+1] == ']')
1181 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1183 // Enable the use of first token again
1184 if (ignoreidx >= 0) {
1185 int value = defLang._tokenstart + defLang._tokensize;
1191 if (borders[borderidx].low < value)
1192 borders[borderidx].low = value;
1193 if (borders[borderidx].upper < value)
1194 borders[borderidx].upper = value;
1199 static void checkDepthIndex(int val)
1201 static int maxdepthidx = MAXOPENED-2;
1202 static int lastmaxdepth = 0;
1203 if (val > lastmaxdepth) {
1204 LYXERR(Debug::INFO, "Depth reached " << val);
1207 if (val > maxdepthidx) {
1209 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1214 // Not needed, because borders are now dynamically expanded
1215 static void checkIgnoreIdx(int val)
1217 static int lastmaxignore = -1;
1218 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1219 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1220 lastmaxignore = val;
1226 * Expand the region of ignored parts of the input latex string
1227 * The region is only relevant in output()
1229 void Intervall::addIntervall(int low, int upper)
1232 if (low == upper) return;
1233 for (idx = ignoreidx+1; idx > 0; --idx) {
1234 if (low > borders[idx-1].upper) {
1238 Border br(low, upper);
1239 if (idx > ignoreidx) {
1240 if (borders.size() <= size_t(idx)) {
1241 borders.push_back(br);
1247 // checkIgnoreIdx(ignoreidx);
1251 // Expand only if one of the new bound is inside the interwall
1252 // We know here that br.low > borders[idx-1].upper
1253 if (br.upper < borders[idx].low) {
1254 // We have to insert at this pos
1255 if (size_t(ignoreidx+1) >= borders.size()) {
1256 borders.push_back(borders[ignoreidx]);
1259 borders[ignoreidx+1] = borders[ignoreidx];
1261 for (int i = ignoreidx; i > idx; --i) {
1262 borders[i] = borders[i-1];
1266 // checkIgnoreIdx(ignoreidx);
1269 // Here we know, that we are overlapping
1270 if (br.low > borders[idx].low)
1271 br.low = borders[idx].low;
1272 // check what has to be concatenated
1274 for (int i = idx; i <= ignoreidx; i++) {
1275 if (br.upper >= borders[i].low) {
1277 if (br.upper < borders[i].upper)
1278 br.upper = borders[i].upper;
1284 // count should be >= 1 here
1287 for (int i = idx + count; i <= ignoreidx; i++) {
1288 borders[i-count+1] = borders[i];
1290 ignoreidx -= count - 1;
1296 static void buildaccent(string n, string param, string values)
1300 const char delim = '|';
1301 while (getline(s, name, delim)) {
1303 for (char c : param) {
1304 string key = name + "{" + c + "}";
1305 // get the corresponding utf8-value
1306 if ((values[start] & 0xc0) != 0xc0) {
1307 // should not happen, utf8 encoding starts at least with 11xxxxxx
1308 // but value for '\dot{i}' is 'i', which is ascii
1309 if ((values[start] & 0x80) == 0) {
1311 accents[key] = values.substr(start, 1);
1312 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1317 for (int j = 1; ;j++) {
1318 if (start + j >= values.size()) {
1319 accents[key] = values.substr(start, j);
1320 start = values.size() - 1;
1323 else if ((values[start+j] & 0xc0) != 0x80) {
1324 // This is the first byte of following utf8 char
1325 accents[key] = values.substr(start, j);
1327 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1336 static string getutf8(unsigned uchar)
1339 string ret = string();
1341 if (uchar <= 0x7f) {
1342 c[maxc-1] = uchar & 0x7f;
1345 unsigned char rest = 0x40;
1346 unsigned char first = 0x80;
1348 for (int i = start; i >=0; --i) {
1350 c[i] = first + uchar;
1353 c[i] = 0x80 | (uchar & 0x3f);
1360 for (int i = 0; i < maxc; i++) {
1361 if (c[i] == 0) continue;
1367 static void buildAccentsMap()
1369 accents["imath"] = "ı";
1371 accents["jmath"] = "ȷ";
1372 accents["cdot"] = "·";
1373 accents["textasciicircum"] = "^";
1374 accents["mathcircumflex"] = "^";
1375 accents["sim"] = "~";
1376 accents["guillemotright"] = "»";
1377 accents["guillemotleft"] = "«";
1378 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1379 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1380 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1381 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1382 accents["negmedspace"] = getutf8(0xf0005);
1383 accents["thickspace"] = getutf8(0xf0006);
1384 accents["negthickspace"] = getutf8(0xf0007);
1385 accents["lyx"] = getutf8(0xf0010); // Used logos
1386 accents["LyX"] = getutf8(0xf0010);
1387 accents["tex"] = getutf8(0xf0011);
1388 accents["TeX"] = getutf8(0xf0011);
1389 accents["latex"] = getutf8(0xf0012);
1390 accents["LaTeX"] = getutf8(0xf0012);
1391 accents["latexe"] = getutf8(0xf0013);
1392 accents["LaTeXe"] = getutf8(0xf0013);
1393 accents["lyxarrow"] = getutf8(0xf0020);
1394 accents["braceleft"] = getutf8(0xf0030);
1395 accents["braceright"] = getutf8(0xf0031);
1396 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1397 accents["backslash LyX"] = getutf8(0xf0010);
1398 accents["backslash tex"] = getutf8(0xf0011);
1399 accents["backslash TeX"] = getutf8(0xf0011);
1400 accents["backslash latex"] = getutf8(0xf0012);
1401 accents["backslash LaTeX"] = getutf8(0xf0012);
1402 accents["backslash latexe"] = getutf8(0xf0013);
1403 accents["backslash LaTeXe"] = getutf8(0xf0013);
1404 accents["backslash lyxarrow"] = getutf8(0xf0020);
1405 accents["ddot{\\imath}"] = "ï";
1406 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1407 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1408 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1409 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1410 accents["acute{\\imath}"] = "í";
1411 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1412 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1413 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1414 buildaccent("mathring|r", "aAuUwy",
1416 accents["check{\\imath}"] = "ǐ";
1417 accents["check{\\jmath}"] = "ǰ";
1418 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1419 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1420 accents["hat{\\imath}"] = "î";
1421 accents["hat{\\jmath}"] = "ĵ";
1422 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1423 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1424 accents["bar{\\imath}"] = "ī";
1425 buildaccent("bar|=", "aAeEiIoOuUyY",
1426 "āĀēĒīĪōŌūŪȳȲ"); // macron
1427 accents["tilde{\\imath}"] = "ĩ";
1428 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1429 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1430 accents["breve{\\imath}"] = "ĭ";
1431 buildaccent("breve|u", "aAeEgGiIoOuU",
1432 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1433 accents["grave{\\imath}"] = "ì";
1434 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1435 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1436 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1437 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1438 buildaccent("ogonek|k", "AaEeIiUuOo",
1439 "ĄąĘęĮįŲųǪǫ"); // ogonek
1440 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1441 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1442 buildaccent("subring|textsubring", "Aa",
1444 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1445 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1446 buildaccent("subtilde|textsubtilde", "EeIiUu",
1447 "ḚḛḬḭṴṵ"); // subtilde
1448 accents["dgrave{\\imath}"] = "ȉ";
1449 accents["textdoublegrave{\\i}"] = "ȉ";
1450 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1451 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1452 accents["rcap{\\imath}"] = "ȉ";
1453 accents["textroundcap{\\i}"] = "ȉ";
1454 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1455 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1456 buildaccent("slashed", "oO",
1461 * Created accents in math or regexp environment
1462 * are macros, but we need the utf8 equivalent
1464 void Intervall::removeAccents()
1466 if (accents.empty())
1468 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1469 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1470 "|((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]))");
1472 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1474 string key = sub.str(1);
1475 AccentsIterator it_ac = accents.find(key);
1476 if (it_ac != accents.end()) {
1477 string val = it_ac->second;
1478 size_t pos = sub.position(size_t(0));
1479 for (size_t i = 0; i < val.size(); i++) {
1480 par[pos+i] = val[i];
1482 // Remove possibly following space too
1483 if (par[pos+sub.str(0).size()] == ' ')
1484 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1486 addIntervall(pos+val.size(), pos + sub.str(0).size());
1487 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1488 // remove traces of any remaining chars
1493 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1498 void Intervall::handleOpenP(int i)
1501 depts[actualdeptindex] = i+1;
1502 closes[actualdeptindex] = -1;
1503 checkDepthIndex(actualdeptindex);
1506 void Intervall::handleCloseP(int i, bool closingAllowed)
1508 if (actualdeptindex <= 0) {
1509 if (! closingAllowed)
1510 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1511 // if we are at the very end
1512 addIntervall(i, i+1);
1515 closes[actualdeptindex] = i+1;
1520 void Intervall::resetOpenedP(int openPos)
1522 // Used as initializer for foreignlanguage entry
1523 actualdeptindex = 1;
1524 depts[1] = openPos+1;
1528 int Intervall::previousNotIgnored(int start) const
1530 int idx = 0; /* int intervalls */
1531 for (idx = ignoreidx; idx >= 0; --idx) {
1532 if (start > borders[idx].upper)
1534 if (start >= borders[idx].low)
1535 start = borders[idx].low-1;
1540 int Intervall::nextNotIgnored(int start) const
1542 int idx = 0; /* int intervalls */
1543 for (idx = 0; idx <= ignoreidx; idx++) {
1544 if (start < borders[idx].low)
1546 if (start < borders[idx].upper)
1547 start = borders[idx].upper;
1552 typedef unordered_map<string, KeyInfo> KeysMap;
1553 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1554 typedef vector< KeyInfo> Entries;
1555 static KeysMap keys = unordered_map<string, KeyInfo>();
1561 Intervall interval_;
1562 void buildKeys(bool);
1563 void buildEntries(bool);
1564 void makeKey(const string &, KeyInfo, bool isPatternString);
1565 void processRegion(int start, int region_end); /* remove {} parts */
1566 void removeHead(KeyInfo const &, int count=0);
1569 LatexInfo(string const & par, bool isPatternString)
1570 : entidx_(-1), interval_(isPatternString, par)
1572 buildKeys(isPatternString);
1573 entries_ = vector<KeyInfo>();
1574 buildEntries(isPatternString);
1578 if (entries_.empty()) {
1581 if (entries_[0].keytype == KeyInfo::isTitle) {
1582 interval_.hasTitle = true;
1583 if (! entries_[0].disabled) {
1584 interval_.titleValue = entries_[0].head;
1587 interval_.titleValue = "";
1589 removeHead(entries_[0]);
1590 if (entries_.size() > 1)
1599 if (int(entries_.size()) > entidx_) {
1606 bool setNextKey(int idx) {
1607 if ((idx == entidx_) && (entidx_ >= 0)) {
1614 int find(int start, KeyInfo::KeyType keytype) const {
1618 while (tmpIdx < int(entries_.size())) {
1619 if (entries_[tmpIdx].keytype == keytype)
1625 int process(ostringstream & os, KeyInfo const & actual);
1626 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1627 // string show(int lastpos) { return interval.show(lastpos);};
1628 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1629 KeyInfo &getKeyInfo(int keyinfo) {
1630 static KeyInfo invalidInfo = KeyInfo();
1631 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1634 return entries_[keyinfo];
1636 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1637 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1641 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1645 for (int i = start; i < end; i += 1 + skip) {
1649 if (c == '\\') skip = 1;
1653 else if (c == down) {
1656 if ((repeat <= 0) || (par[i+1] != up))
1670 size_t mathpostfixsize;
1672 size_t mathprefixsize;
1676 vector<MathEntry> entries_;
1681 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1682 MathEntry m = MathEntry();
1684 m.mathStart = start;
1685 m.mathprefixsize = prefixsize;
1686 m.mathEnd = end + postfixsize;
1687 m.mathpostfixsize = postfixsize;
1688 m.mathSize = m.mathEnd - m.mathStart;
1689 entries_.push_back(m);
1691 bool empty() const { return entries_.empty(); };
1692 size_t getEndPos() const {
1693 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1696 return entries_[actualIdx_].mathEnd;
1698 size_t getStartPos() const {
1699 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1700 return 100000; /* definitely enough? */
1702 return entries_[actualIdx_].mathStart;
1704 size_t getPrefixSize() const {
1705 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1708 return entries_[actualIdx_].mathprefixsize;
1710 size_t getPostfixSize() const {
1711 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1714 return entries_[actualIdx_].mathpostfixsize;
1716 size_t getFirstPos() {
1718 return getStartPos();
1720 size_t getSize() const {
1721 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1724 return entries_[actualIdx_].mathSize;
1726 void incrEntry() { actualIdx_++; };
1729 void LatexInfo::buildEntries(bool isPatternString)
1731 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1732 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1733 static bool disableLanguageOverride = false;
1734 smatch sub, submath;
1735 bool evaluatingRegexp = false;
1737 bool evaluatingMath = false;
1738 bool evaluatingCode = false;
1740 bool evaluatingOptional = false;
1741 size_t optionalEnd = 0;
1744 bool math_end_waiting = false;
1745 size_t math_pos = 10000;
1746 size_t math_prefix_size = 1;
1748 static vector<string> usedText = vector<string>();
1749 static bool removeMathHull = false;
1751 interval_.removeAccents();
1753 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1755 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1756 // prefixed by odd count of '\\'
1759 if (math_end_waiting) {
1760 size_t pos = submath.position(size_t(2));
1761 if ((math_end == "$") &&
1762 (submath.str(2) == "$")) {
1763 mi.insert("$", math_pos, 1, pos, 1);
1764 math_end_waiting = false;
1766 else if ((math_end == "\\]") &&
1767 (submath.str(2) == "\\]")) {
1768 mi.insert("\\]", math_pos, 2, pos, 2);
1769 math_end_waiting = false;
1771 else if ((submath.str(3).compare("end") == 0) &&
1772 (submath.str(4).compare(math_end) == 0)) {
1773 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
1774 math_end_waiting = false;
1780 if (submath.str(3).compare("begin") == 0) {
1781 math_end_waiting = true;
1782 math_end = submath.str(4);
1783 math_pos = submath.position(size_t(2));
1784 math_prefix_size = submath.str(2).length();
1786 else if (submath.str(2).compare("\\[") == 0) {
1787 math_end_waiting = true;
1789 math_pos = submath.position(size_t(2));
1791 else if (submath.str(2) == "$") {
1792 size_t pos = submath.position(size_t(2));
1793 math_end_waiting = true;
1799 // Ignore language if there is math somewhere in pattern-string
1800 if (isPatternString) {
1801 for (auto s: usedText) {
1802 // Remove entries created in previous search runs
1805 usedText = vector<string>();
1808 keys["foreignlanguage"].disabled = true;
1809 disableLanguageOverride = true;
1810 removeMathHull = false;
1813 removeMathHull = true; // used later if not isPatternString
1814 disableLanguageOverride = false;
1818 if (disableLanguageOverride) {
1819 keys["foreignlanguage"].disabled = true;
1822 math_pos = mi.getFirstPos();
1823 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1825 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1826 // prefixed by odd count of '\\'
1829 string key = sub.str(5);
1831 if (sub.str(2)[0] == '\\')
1832 key = sub.str(2)[1];
1837 KeysIterator it_key = keys.find(key);
1838 if (it_key != keys.end()) {
1839 if (it_key->second.keytype == KeyInfo::headRemove) {
1840 KeyInfo found1 = it_key->second;
1841 found1.disabled = true;
1842 found1.head = "\\" + key + "{";
1843 found1._tokenstart = sub.position(size_t(2));
1844 found1._tokensize = found1.head.length();
1845 found1._dataStart = found1._tokenstart + found1.head.length();
1846 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1847 found1._dataEnd = endpos;
1852 if (evaluatingRegexp) {
1853 if (sub.str(3).compare("endregexp") == 0) {
1854 evaluatingRegexp = false;
1855 // found._tokenstart already set
1856 found._dataEnd = sub.position(size_t(2)) + 13;
1857 found._dataStart = found._dataEnd;
1858 found._tokensize = found._dataEnd - found._tokenstart;
1859 found.parenthesiscount = 0;
1860 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1867 if (evaluatingMath) {
1868 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1870 evaluatingMath = false;
1872 math_pos = mi.getStartPos();
1874 if (it_key == keys.end()) {
1875 found = KeyInfo(KeyInfo::isStandard, 0, true);
1876 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1877 found = KeyInfo(KeyInfo::isText, 0, false);
1878 if (isPatternString) {
1879 found.keytype = KeyInfo::isChar;
1880 found.disabled = false;
1884 usedText.push_back(key);
1888 if (key.compare("regexp") == 0) {
1889 evaluatingRegexp = true;
1890 found._tokenstart = sub.position(size_t(2));
1891 found._tokensize = 0;
1895 // Handle the other params of key
1896 if (found.keytype == KeyInfo::isIgnored)
1898 else if (found.keytype == KeyInfo::isMath) {
1899 if (size_t(sub.position(size_t(2))) == math_pos) {
1901 found._tokenstart = sub.position(size_t(2));
1902 found._tokensize = mi.getSize();
1903 found._dataEnd = found._tokenstart + found._tokensize;
1904 found._dataStart = found._dataEnd;
1905 found.parenthesiscount = 0;
1906 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1907 if (removeMathHull) {
1908 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1909 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1911 evaluatingMath = true;
1914 // begin|end of unknown env, discard
1915 // First handle tables
1916 // longtable|tabular
1917 bool discardComment;
1919 found.keytype = KeyInfo::doRemove;
1920 if ((sub.str(7).compare("longtable") == 0) ||
1921 (sub.str(7).compare("tabular") == 0)) {
1922 discardComment = true; /* '%' */
1925 discardComment = false;
1926 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1928 string token = sub.str(7);
1929 if (regex_match(token, sub2, removeArgs)) {
1930 found.keytype = KeyInfo::removeWithArg;
1933 // discard spaces before pos(2)
1934 int pos = sub.position(size_t(2));
1936 for (count = 0; pos - count > 0; count++) {
1937 char c = interval_.par[pos-count-1];
1938 if (discardComment) {
1939 if ((c != ' ') && (c != '%'))
1945 found._tokenstart = pos - count;
1946 if (sub.str(3).compare(0, 5, "begin") == 0) {
1947 size_t pos1 = pos + sub.str(2).length();
1948 if (sub.str(7).compare("cjk") == 0) {
1949 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1950 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1952 found.keytype = KeyInfo::isMain;
1953 found._dataStart = pos1;
1954 found._dataEnd = interval_.par.length();
1955 found.disabled = keys["foreignlanguage"].disabled;
1956 found.used = keys["foreignlanguage"].used;
1957 found._tokensize = pos1 - found._tokenstart;
1958 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1961 // Swallow possible optional params
1962 while (interval_.par[pos1] == '[') {
1963 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1965 // Swallow also the eventual parameter
1966 if (interval_.par[pos1] == '{') {
1967 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1970 found._dataEnd = pos1;
1972 found._dataStart = found._dataEnd;
1973 found._tokensize = count + found._dataEnd - pos;
1974 found.parenthesiscount = 0;
1975 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1976 found.disabled = true;
1980 // Handle "\end{...}"
1981 found._dataStart = pos + sub.str(2).length();
1982 found._dataEnd = found._dataStart;
1983 found._tokensize = count + found._dataEnd - pos;
1984 found.parenthesiscount = 0;
1985 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1986 found.disabled = true;
1990 else if (found.keytype != KeyInfo::isRegex) {
1991 found._tokenstart = sub.position(size_t(2));
1992 if (found.parenthesiscount == 0) {
1993 // Probably to be discarded
1994 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1995 char following = interval_.par[following_pos];
1996 if (following == ' ')
1997 found.head = "\\" + sub.str(5) + " ";
1998 else if (following == '=') {
1999 // like \uldepth=1000pt
2000 found.head = sub.str(2);
2003 found.head = "\\" + key;
2004 found._tokensize = found.head.length();
2005 found._dataEnd = found._tokenstart + found._tokensize;
2006 found._dataStart = found._dataEnd;
2009 int params = found._tokenstart + key.length() + 1;
2010 if (evaluatingOptional) {
2011 if (size_t(found._tokenstart) > optionalEnd) {
2012 evaluatingOptional = false;
2015 found.disabled = true;
2018 int optend = params;
2019 while (interval_.par[optend] == '[') {
2020 // discard optional parameters
2021 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2023 if (optend > params) {
2024 key += interval_.par.substr(params, optend-params);
2025 evaluatingOptional = true;
2026 optionalEnd = optend;
2027 if (found.keytype == KeyInfo::isSectioning) {
2028 // Remove optional values (but still keep in header)
2029 interval_.addIntervall(params, optend);
2032 string token = sub.str(7);
2034 if (interval_.par[optend] != '{') {
2036 found.parenthesiscount = 0;
2037 found.head = "\\" + key;
2040 closings = found.parenthesiscount;
2041 if (found.parenthesiscount == 1) {
2042 found.head = "\\" + key + "{";
2044 else if (found.parenthesiscount > 1) {
2046 found.head = sub.str(2) + "{";
2047 closings = found.parenthesiscount - 1;
2050 found.head = "\\" + key + "{";
2053 found._tokensize = found.head.length();
2054 found._dataStart = found._tokenstart + found.head.length();
2055 if (found.keytype == KeyInfo::doRemove) {
2057 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2058 if (endpar >= interval_.par.length())
2059 found._dataStart = interval_.par.length();
2061 found._dataStart = endpar;
2062 found._tokensize = found._dataStart - found._tokenstart;
2065 found._dataStart = found._tokenstart + found._tokensize;
2069 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2070 found._dataStart += 15;
2074 endpos = found._dataStart - 1;
2076 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2077 if (found.keytype == KeyInfo::isList) {
2078 // Check if it really is list env
2079 static regex const listre("^([a-z]+)$");
2081 if (!regex_match(token, sub2, listre)) {
2082 // Change the key of this entry. It is not in a list/item environment
2083 found.keytype = KeyInfo::endArguments;
2086 if (found.keytype == KeyInfo::noMain) {
2087 evaluatingCode = true;
2089 codeStart = found._dataStart;
2091 else if (evaluatingCode) {
2092 if (size_t(found._dataStart) > codeEnd)
2093 evaluatingCode = false;
2094 else if (found.keytype == KeyInfo::isMain) {
2095 // Disable this key, treate it as standard
2096 found.keytype = KeyInfo::isStandard;
2097 found.disabled = true;
2098 if ((codeEnd +1 >= interval_.par.length()) &&
2099 (found._tokenstart == codeStart)) {
2100 // trickery, because the code inset starts
2101 // with \selectlanguage ...
2103 if (entries_.size() > 1) {
2104 entries_[entries_.size()-1]._dataEnd = codeEnd;
2109 if ((endpos == interval_.par.length()) &&
2110 (found.keytype == KeyInfo::doRemove)) {
2111 // Missing closing => error in latex-input?
2112 // therefore do not delete remaining data
2113 found._dataStart -= 1;
2114 found._dataEnd = found._dataStart;
2117 found._dataEnd = endpos;
2119 if (isPatternString) {
2120 keys[key].used = true;
2123 entries_.push_back(found);
2127 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2129 stringstream s(keysstring);
2131 const char delim = '|';
2132 while (getline(s, key, delim)) {
2133 KeyInfo keyII(keyI);
2134 if (isPatternString) {
2137 else if ( !keys[key].used)
2138 keyII.disabled = true;
2143 void LatexInfo::buildKeys(bool isPatternString)
2146 static bool keysBuilt = false;
2147 if (keysBuilt && !isPatternString) return;
2149 // Keys to ignore in any case
2150 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2151 // Known standard keys with 1 parameter.
2152 // Split is done, if not at start of region
2153 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2154 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2155 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2156 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2157 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2158 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2160 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2161 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2162 makeKey("section*|subsection*|subsubsection*|paragraph*",
2163 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2164 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2165 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2167 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2169 // Split is done, if not at start of region
2170 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2171 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2173 // Split is done always.
2174 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2178 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2179 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2180 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2181 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2183 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2184 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2185 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2186 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2188 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2189 // Custom space/skip, remove the content (== length value)
2190 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2191 // Found in fr/UserGuide.lyx
2192 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2194 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2195 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2196 // Known macros to remove (including their parameter)
2198 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2199 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2200 // handle like standard keys with 1 parameter.
2201 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2203 // Ignore deleted text
2204 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2205 // but preserve added text
2206 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2208 // Macros to remove, but let the parameter survive
2210 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2212 // Remove language spec from content of these insets
2213 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2215 // Same effect as previous, parameter will survive (because there is no one anyway)
2217 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2218 // Remove table decorations
2219 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2220 // Discard shape-header.
2221 // For footnote or shortcut too, because of lang settings
2222 // and wrong handling if used 'KeyInfo::noMain'
2223 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2224 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2225 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2226 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2227 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2228 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2229 // like ('tiny{}' or '\tiny ' ... )
2230 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2232 // Survives, like known character
2233 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2234 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2235 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2237 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2238 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2239 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2241 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2242 // Remove RTL/LTR marker
2243 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2244 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2245 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2246 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2247 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2248 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2249 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2250 if (isPatternString) {
2251 // Allow the first searched string to rebuild the keys too
2255 // no need to rebuild again
2261 * Keep the list of actual opened parentheses actual
2262 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2264 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2267 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2271 if (c == '\\') skip = 1;
2272 else if (c == '{') {
2275 else if (c == '}') {
2276 handleCloseP(i, closingAllowed);
2282 string Intervall::show(int lastpos)
2284 int idx = 0; /* int intervalls */
2287 for (idx = 0; idx <= ignoreidx; idx++) {
2288 while (i < lastpos) {
2290 if (i <= borders[idx].low) {
2291 if (borders[idx].low > lastpos)
2292 printsize = lastpos - i;
2294 printsize = borders[idx].low - i;
2295 s += par.substr(i, printsize);
2297 if (i >= borders[idx].low)
2298 i = borders[idx].upper;
2301 i = borders[idx].upper;
2307 s += par.substr(i, lastpos-i);
2313 void Intervall::output(ostringstream &os, int lastpos)
2315 // get number of chars to output
2316 int idx = 0; /* int intervalls */
2319 string startTitle = titleValue;
2320 for (idx = 0; idx <= ignoreidx; idx++) {
2322 if (i <= borders[idx].low) {
2324 if (borders[idx].low > lastpos)
2325 printsize = lastpos - i;
2327 printsize = borders[idx].low - i;
2328 if (printsize > 0) {
2329 os << startTitle << par.substr(i, printsize);
2331 printed += printsize;
2334 handleParentheses(i, false);
2335 if (i >= borders[idx].low)
2336 i = borders[idx].upper;
2339 i = borders[idx].upper;
2346 os << startTitle << par.substr(i, lastpos-i);
2347 printed += lastpos-i;
2349 handleParentheses(lastpos, false);
2351 if (keys["foreignlanguage"].disabled)
2352 startindex = actualdeptindex-langcount;
2354 startindex = actualdeptindex;
2355 for (int i = startindex; i > 0; --i) {
2358 if (hasTitle && (printed > 0))
2360 if (! isPatternString_)
2362 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2365 void LatexInfo::processRegion(int start, int region_end)
2367 while (start < region_end) { /* Let {[} and {]} survive */
2368 int cnt = interval_.isOpeningPar(start);
2370 // Closing is allowed past the region
2371 int closing = interval_.findclosing(start+1, interval_.par.length());
2372 interval_.addIntervall(start, start+1);
2373 interval_.addIntervall(closing, closing+1);
2377 start = interval_.nextNotIgnored(start+1);
2381 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2383 if (actual.parenthesiscount == 0) {
2384 // "{\tiny{} ...}" ==> "{{} ...}"
2385 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2388 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2389 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2390 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2394 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2397 switch (actual.keytype)
2399 case KeyInfo::isTitle: {
2401 nextKeyIdx = getNextKey();
2404 case KeyInfo::cleanToStart: {
2405 actual._dataEnd = actual._dataStart;
2406 nextKeyIdx = getNextKey();
2407 // Search for end of arguments
2408 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2410 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2411 entries_[i].disabled = true;
2413 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2415 while (interval_.par[actual._dataEnd] == ' ')
2417 interval_.addIntervall(0, actual._dataEnd+1);
2418 interval_.actualdeptindex = 0;
2419 interval_.depts[0] = actual._dataEnd+1;
2420 interval_.closes[0] = -1;
2423 case KeyInfo::isText:
2424 interval_.par[actual._tokenstart] = '#';
2425 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2426 nextKeyIdx = getNextKey();
2428 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2429 if (actual.disabled)
2430 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2432 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2435 case KeyInfo::isChar: {
2436 nextKeyIdx = getNextKey();
2439 case KeyInfo::isSize: {
2440 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2441 if (actual.parenthesiscount == 0)
2442 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2444 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2446 nextKeyIdx = getNextKey();
2448 // Here _dataStart points to '{', so correct it
2449 actual._dataStart += 1;
2450 actual._tokensize += 1;
2451 actual.parenthesiscount = 1;
2452 if (interval_.par[actual._dataStart] == '}') {
2453 // Determine the end if used like '{\tiny{}...}'
2454 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2455 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2458 // Determine the end if used like '\tiny{...}'
2459 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2461 // Split on this key if not at start
2462 int start = interval_.nextNotIgnored(previousStart);
2463 if (start < actual._tokenstart) {
2464 interval_.output(os, actual._tokenstart);
2465 interval_.addIntervall(start, actual._tokenstart);
2467 // discard entry if at end of actual
2468 nextKeyIdx = process(os, actual);
2472 case KeyInfo::endArguments: {
2473 // Remove trailing '{}' too
2474 actual._dataStart += 1;
2475 actual._dataEnd += 1;
2476 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2477 nextKeyIdx = getNextKey();
2480 case KeyInfo::noMain:
2482 case KeyInfo::isStandard: {
2483 if (actual.disabled) {
2485 processRegion(actual._dataStart, actual._dataStart+1);
2486 nextKeyIdx = getNextKey();
2488 // Split on this key if not at datastart of calling entry
2489 int start = interval_.nextNotIgnored(previousStart);
2490 if (start < actual._tokenstart) {
2491 interval_.output(os, actual._tokenstart);
2492 interval_.addIntervall(start, actual._tokenstart);
2494 // discard entry if at end of actual
2495 nextKeyIdx = process(os, actual);
2499 case KeyInfo::removeWithArg: {
2500 nextKeyIdx = getNextKey();
2501 // Search for end of arguments
2502 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2504 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2505 entries_[i].disabled = true;
2507 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2509 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2512 case KeyInfo::doRemove: {
2513 // Remove the key with all parameters and following spaces
2516 if (interval_.par[actual._dataEnd-1] == ' ')
2517 start = actual._dataEnd;
2519 start = actual._dataEnd+1;
2520 for (pos = start; pos < interval_.par.length(); pos++) {
2521 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2524 // Remove also enclosing parentheses [] and {}
2527 while (actual._tokenstart > numpars) {
2528 if (pos+numpars >= interval_.par.size())
2530 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2532 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2538 if (interval_.par[pos+numpars] == ' ')
2542 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2543 nextKeyIdx = getNextKey();
2546 case KeyInfo::isList: {
2547 // Discard space before _tokenstart
2549 for (count = 0; count < actual._tokenstart; count++) {
2550 if (interval_.par[actual._tokenstart-count-1] != ' ')
2553 nextKeyIdx = getNextKey();
2554 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2556 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2558 // How else can we catch this one?
2559 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2560 entries_[i].disabled = true;
2562 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2564 else if (nextKeyIdx > 0) {
2565 // Ignore any lang entries inside data region
2566 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2567 if (entries_[i].keytype == KeyInfo::isMain)
2568 entries_[i].disabled = true;
2571 if (actual.disabled) {
2572 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2575 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2577 if (interval_.par[actual._dataEnd+1] == '[') {
2578 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2579 if ((interval_.par[actual._dataEnd+2] == '{') &&
2580 (interval_.par[posdown-1] == '}')) {
2581 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2582 interval_.addIntervall(posdown-1, posdown+1);
2585 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2586 interval_.addIntervall(posdown, posdown+1);
2588 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2589 if (blk > posdown) {
2590 // Discard at most 1 space after empty item
2592 for (count = 0; count < 1; count++) {
2593 if (interval_.par[blk+count] != ' ')
2597 interval_.addIntervall(blk, blk+count);
2602 case KeyInfo::isSectioning: {
2603 // Discard spaces before _tokenstart
2605 int val = actual._tokenstart;
2606 for (count = 0; count < actual._tokenstart;) {
2607 val = interval_.previousNotIgnored(val-1);
2608 if (val < 0 || interval_.par[val] != ' ')
2611 count = actual._tokenstart - val;
2614 if (actual.disabled) {
2615 removeHead(actual, count);
2616 nextKeyIdx = getNextKey();
2618 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2619 nextKeyIdx = process(os, actual);
2623 case KeyInfo::isMath: {
2624 // Same as regex, use the content unchanged
2625 nextKeyIdx = getNextKey();
2628 case KeyInfo::isRegex: {
2629 // DO NOT SPLIT ON REGEX
2631 nextKeyIdx = getNextKey();
2634 case KeyInfo::isIgnored: {
2635 // Treat like a character for now
2636 nextKeyIdx = getNextKey();
2639 case KeyInfo::isMain: {
2640 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2641 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2642 if (actual._tokenstart > 0) {
2643 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2644 if ((prev >= 0) && interval_.par[prev] == '%')
2645 interval_.addIntervall(prev, prev+1);
2647 if (actual.disabled) {
2649 interval_.langcount++;
2650 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2651 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2652 // Discard also the space before math-equation
2653 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2655 nextKeyIdx = getNextKey();
2656 // interval.resetOpenedP(actual._dataStart-1);
2659 if (actual._tokenstart < 26) {
2660 // for the first (and maybe dummy) language
2661 interval_.setForDefaultLang(actual);
2663 interval_.resetOpenedP(actual._dataStart-1);
2667 case KeyInfo::invalid:
2668 case KeyInfo::headRemove:
2669 // These two cases cannot happen, already handled
2672 // LYXERR(Debug::INFO, "Unhandled keytype");
2673 nextKeyIdx = getNextKey();
2680 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2682 int end = interval_.nextNotIgnored(actual._dataEnd);
2683 int oldStart = actual._dataStart;
2684 int nextKeyIdx = getNextKey();
2686 if ((nextKeyIdx < 0) ||
2687 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2688 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2689 if (oldStart <= end) {
2690 processRegion(oldStart, end);
2695 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2697 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2698 (void) dispatch(os, actual._dataStart, nextKey);
2699 end = nextKey._tokenstart;
2702 processRegion(oldStart, nextKey._tokenstart);
2703 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2705 oldStart = nextKey._dataEnd+1;
2707 // now nextKey is either invalid or is outside of actual._dataEnd
2708 // output the remaining and discard myself
2709 if (oldStart <= end) {
2710 processRegion(oldStart, end);
2712 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2714 // This is the normal case.
2715 // But if using the firstlanguage, the closing may be missing
2717 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2719 if (actual._dataEnd < end)
2720 output_end = interval_.nextNotIgnored(actual._dataEnd);
2721 else if (interval_.par.size() > (size_t) end)
2722 output_end = interval_.nextNotIgnored(end);
2724 output_end = interval_.par.size();
2725 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2726 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2728 // Remove possible empty data
2729 int dstart = interval_.nextNotIgnored(actual._dataStart);
2730 while (interval_.isOpeningPar(dstart) == 1) {
2731 interval_.addIntervall(dstart, dstart+1);
2732 int dend = interval_.findclosing(dstart+1, output_end);
2733 interval_.addIntervall(dend, dend+1);
2734 dstart = interval_.nextNotIgnored(dstart+1);
2736 if (dstart < output_end)
2737 interval_.output(os, output_end);
2739 interval_.addIntervall(0, end);
2741 interval_.addIntervall(actual._tokenstart, end);
2745 string splitOnKnownMacros(string par, bool isPatternString)
2748 LatexInfo li(par, isPatternString);
2749 // LYXERR(Debug::INFO, "Berfore split: " << par);
2750 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2752 DummyKey._tokensize = 0;
2753 DummyKey._dataStart = 0;
2754 DummyKey._dataEnd = par.length();
2755 DummyKey.disabled = true;
2756 int firstkeyIdx = li.getFirstKey();
2758 if (firstkeyIdx >= 0) {
2759 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2760 DummyKey._tokenstart = firstKey._tokenstart;
2762 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2763 // Use dummy firstKey
2764 firstKey = DummyKey;
2765 (void) li.setNextKey(firstkeyIdx);
2768 if (par.substr(firstKey._dataStart, 2) == "% ")
2769 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2771 nextkeyIdx = li.process(os, firstKey);
2772 while (nextkeyIdx >= 0) {
2773 // Check for a possible gap between the last
2774 // entry and this one
2775 int datastart = li.nextNotIgnored(firstKey._dataStart);
2776 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2777 if ((nextKey._tokenstart > datastart)) {
2779 firstKey._dataStart = datastart;
2780 firstKey._dataEnd = par.length();
2781 (void) li.setNextKey(nextkeyIdx);
2782 // Fake the last opened parenthesis
2783 li.setForDefaultLang(firstKey);
2784 nextkeyIdx = li.process(os, firstKey);
2787 if (nextKey.keytype != KeyInfo::isMain) {
2788 firstKey._dataStart = datastart;
2789 firstKey._dataEnd = nextKey._dataEnd+1;
2790 (void) li.setNextKey(nextkeyIdx);
2791 li.setForDefaultLang(firstKey);
2792 nextkeyIdx = li.process(os, firstKey);
2795 nextkeyIdx = li.process(os, nextKey);
2799 // Handle the remaining
2800 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2801 firstKey._dataEnd = par.length();
2803 if ((firstKey._dataStart < firstKey._dataEnd) &&
2804 (par[firstKey._dataStart] != '}')) {
2805 li.setForDefaultLang(firstKey);
2806 (void) li.process(os, firstKey);
2810 // return string definitelly impossible to match
2811 s = "\\foreignlanguage{ignore}{ }";
2815 s = par; /* no known macros found */
2816 // LYXERR(Debug::INFO, "After split: " << s);
2821 * Try to unify the language specs in the latexified text.
2822 * Resulting modified string is set to "", if
2823 * the searched tex does not contain all the features in the search pattern
2825 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2827 static Features regex_f;
2828 static int missed = 0;
2829 static bool regex_with_format = false;
2831 int parlen = par.length();
2833 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2836 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2837 // Happens to be there in case of description or labeling environment
2842 // Split the latex input into pieces which
2843 // can be digested by our search engine
2844 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2845 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2846 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2847 string doclang = pbuf->params().language->polyglossia();
2848 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2850 bool toIgnoreLang = true;
2851 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2853 if (sub.str(2) != doclang) {
2854 toIgnoreLang = false;
2858 setIgnoreFormat("language", toIgnoreLang, false);
2861 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2862 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2865 result = par.substr(0, parlen);
2866 if (isPatternString) {
2869 regex_f = identifyFeatures(result);
2870 string features = "";
2871 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2872 string a = it->first;
2873 regex_with_format = true;
2874 features += " " + a;
2875 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2877 LYXERR(Debug::FIND, "Identified Features" << features);
2880 } else if (regex_with_format) {
2881 Features info = identifyFeatures(result);
2882 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2883 string a = it->first;
2884 bool b = it->second;
2885 if (b && ! info[a]) {
2887 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2894 // LYXERR(Debug::INFO, "No regex formats");
2900 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2901 static int identifyClosing(string & t)
2903 int open_braces = 0;
2905 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2906 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2908 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2910 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2912 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2921 static int num_replaced = 0;
2922 static bool previous_single_replace = true;
2924 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2927 // Handle \w properly
2928 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2929 if (! opt.casesensitive) {
2930 popts |= QRegularExpression::CaseInsensitiveOption;
2932 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2933 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2935 if (regexp.isValid() && regexp2.isValid()) {
2936 regexIsValid = true;
2937 // Check '{', '}' pairs inside the regex
2940 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2941 char c = par_as_string[i];
2948 else if (c == '}') {
2955 if (balanced != 0) {
2956 regexIsValid = false;
2957 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2961 regexIsValid = false;
2962 if (!regexp.isValid())
2963 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2965 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2968 if (opt.casesensitive) {
2969 regexp = regex(regexp_str);
2970 regexp2 = regex(regexp2_str);
2973 regexp = regex(regexp_str, std::regex_constants::icase);
2974 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2979 static void modifyRegexForMatchWord(string &t)
2982 regex wordre("(\\\\)*((\\.|\\\\b))");
2985 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2987 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2990 else if (sub.str(2) == "\\\\b")
2992 if (lastpos < (size_t) sub.position(2))
2993 s += t.substr(lastpos, sub.position(2) - lastpos);
2995 lastpos = sub.position(2) + sub.length(2);
2998 s = "\\b" + t + "\\b";
3002 else if (lastpos < t.length())
3003 s += t.substr(lastpos, t.length() - lastpos);
3004 t = "\\b" + s + "\\b";
3007 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3008 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3010 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3011 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3012 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3013 if (opt.replace_all && previous_single_replace) {
3014 previous_single_replace = false;
3017 else if (!opt.replace_all) {
3018 num_replaced = 0; // count number of replaced strings
3019 previous_single_replace = true;
3021 // When using regexp, braces are hacked already by escape_for_regex()
3022 par_as_string = normalize(ds);
3024 close_wildcards = 0;
3026 size_t lead_size = 0;
3027 // correct the language settings
3028 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3029 opt.matchAtStart = false;
3031 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3032 if (opt.ignoreformat) {
3036 lead_size = identifyLeading(par_as_string);
3038 lead_as_string = par_as_string.substr(0, lead_size);
3039 string lead_as_regex_string = string2regex(lead_as_string);
3040 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3041 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3042 /* Handle whole words too in this case
3044 if (opt.matchword) {
3045 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3046 opt.matchword = false;
3048 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3049 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3050 CreateRegexp(opt, regexp_str, regexp2_str);
3052 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3053 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3057 if (!opt.ignoreformat) {
3058 lead_size = identifyLeading(par_as_string);
3059 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3060 lead_as_string = par_as_string.substr(0, lead_size);
3061 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3064 // Here we are using regexp
3065 LASSERT(use_regexp, /**/);
3067 string lead_as_regexp;
3068 if (lead_size > 0) {
3069 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3070 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3071 par_as_string = par_as_string_nolead;
3072 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3073 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3075 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3076 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3077 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3078 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3080 size_t lng = par_as_string.size();
3081 if (!opt.ignoreformat) {
3082 // Remove extra '\}' at end if not part of \{\.\}
3084 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3086 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3095 if (lng < par_as_string.size())
3096 par_as_string = par_as_string.substr(0,lng);
3098 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3099 if ((lng > 0) && (par_as_string[0] == '^')) {
3100 par_as_string = par_as_string.substr(1);
3102 opt.matchAtStart = true;
3104 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3105 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3106 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3108 // If entered regexp must match at begin of searched string buffer
3109 // Kornel: Added parentheses to use $1 for size of the leading string
3113 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3114 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3115 // so the convert has no effect in that case
3116 for (int i = 7; i > 0; --i) {
3117 string orig = "\\\\" + std::to_string(i);
3118 string dest = "\\" + std::to_string(i+2);
3119 while (regex_replace(par_as_string, par_as_string, orig, dest));
3121 if (opt.matchword) {
3122 modifyRegexForMatchWord(par_as_string);
3123 opt.matchword = false;
3125 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3126 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3128 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3129 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3130 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3134 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3138 mres.searched_size = len;
3140 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3143 docstring docstr = stringifyFromForSearch(opt, cur, len);
3145 str = normalize(docstr);
3146 if (!opt.ignoreformat) {
3147 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3148 // remove closing '}' and '\n' to allow for use of '$' in regex
3149 size_t lng = str.size();
3150 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3152 if (lng != str.size()) {
3153 str = str.substr(0, lng);
3157 mres.match_len = -1;
3160 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3162 LASSERT(use_regexp, /**/);
3164 // use_regexp always true
3165 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3167 QString qstr = QString::fromStdString(str);
3168 QRegularExpression const *p_regexp;
3169 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3173 p_regexp = ®exp2;
3175 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3176 if (!match.hasMatch())
3179 regex const *p_regexp;
3180 regex_constants::match_flag_type flags;
3182 flags = regex_constants::match_continuous;
3185 flags = regex_constants::match_default;
3186 p_regexp = ®exp2;
3188 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3189 if (re_it == sregex_iterator())
3191 match_results<string::const_iterator> const & m = *re_it;
3193 // Whole found string, including the leading
3194 // std: m[0].second - m[0].first
3195 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3197 // Size of the leading string
3198 // std: m[1].second - m[1].first
3199 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3200 int leadingsize = 0;
3202 if (match.lastCapturedIndex() > 0) {
3203 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3208 leadingsize = m[1].second - m[1].first;
3212 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3213 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3214 // because of different number of closing at end of string
3215 // we have to 'unify' the length of the post-match.
3216 // Done by ignoring closing parenthesis and linefeeds at string end
3217 int matchend = match.capturedEnd(0);
3218 size_t strsize = qstr.size();
3219 if (!opt.ignoreformat) {
3220 while (mres.match_len > 0) {
3221 QChar c = qstr.at(matchend - 1);
3222 if ((c == '\n') || (c == '}') || (c == '{')) {
3229 while (strsize > (size_t) match.capturedEnd(0)) {
3230 QChar c = qstr.at(strsize-1);
3231 if ((c == '\n') || (c == '}')) {
3238 // LYXERR0(qstr.toStdString());
3239 mres.match2end = strsize - matchend;
3240 mres.pos = match.capturedStart(2);
3242 mres.match_prefix = m[2].second - m[2].first;
3243 mres.match_len = m[0].second - m[2].second;
3244 // ignore closing parenthesis and linefeeds at string end
3245 size_t strend = m[0].second - m[0].first;
3246 int matchend = strend;
3247 size_t strsize = str.size();
3248 if (!opt.ignoreformat) {
3249 while (mres.match_len > 0) {
3250 char c = str.at(matchend - 1);
3251 if ((c == '\n') || (c == '}') || (c == '{')) {
3258 while (strsize > strend) {
3259 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3267 mres.match2end = strsize - matchend;
3268 mres.pos = m[2].first - m[0].first;;
3270 if (mres.match2end < 0)
3272 mres.leadsize = leadingsize;
3274 if (mres.match_len > 0) {
3275 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3276 mres.result.push_back(a0);
3277 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3278 mres.result.push_back(match.captured(i).toStdString());
3282 if (mres.match_len > 0) {
3283 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3284 mres.result.push_back(a0);
3285 for (size_t i = 3; i < m.size(); i++) {
3286 mres.result.push_back(m[i]);
3295 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3297 MatchResult mres = findAux(cur, len, at_begin);
3298 int res = mres.match_len;
3300 "res=" << res << ", at_begin=" << at_begin
3301 << ", matchAtStart=" << opt.matchAtStart
3302 << ", inTexted=" << cur.inTexted());
3303 if (opt.matchAtStart) {
3306 else if (mres.match_prefix > 0)
3315 static bool simple_replace(string &t, string from, string to)
3317 regex repl("(\\\\)*(" + from + ")");
3321 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3323 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3325 if (lastpos < (size_t) sub.position(2))
3326 s += t.substr(lastpos, sub.position(2) - lastpos);
3328 lastpos = sub.position(2) + sub.length(2);
3332 else if (lastpos < t.length())
3333 s += t.substr(lastpos, t.length() - lastpos);
3339 string MatchStringAdv::normalize(docstring const & s) const
3342 t = lyx::to_utf8(s);
3343 // Remove \n at begin
3344 while (!t.empty() && t[0] == '\n')
3347 while (!t.empty() && t[t.size() - 1] == '\n')
3348 t = t.substr(0, t.size() - 1);
3350 // Handle all other '\n'
3351 while ((pos = t.find("\n")) != string::npos) {
3352 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3354 if (isAlnumASCII(t[pos+1])) {
3355 t.replace(pos-2, 3, " ");
3358 t.replace(pos-2, 3, "");
3361 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3362 // '\n' adjacent to non-alpha-numerics, discard
3363 t.replace(pos, 1, "");
3366 // Replace all other \n with spaces
3367 t.replace(pos, 1, " ");
3370 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3371 // Kornel: Added textsl, textsf, textit, texttt and noun
3372 // + allow to seach for colored text too
3373 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3374 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3375 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3376 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3377 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3378 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3384 docstring stringifyFromCursor(DocIterator const & cur, int len)
3386 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3387 if (cur.inTexted()) {
3388 Paragraph const & par = cur.paragraph();
3389 // TODO what about searching beyond/across paragraph breaks ?
3390 // TODO Try adding a AS_STR_INSERTS as last arg
3391 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3392 int(par.size()) : cur.pos() + len;
3393 // OutputParams runparams(&cur.buffer()->params().encoding());
3394 OutputParams runparams(encodings.fromLyXName("utf8"));
3395 runparams.nice = true;
3396 runparams.flavor = Flavor::XeTeX;
3397 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3398 // No side effect of file copying and image conversion
3399 runparams.dryrun = true;
3400 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3401 if (ignoreFormats.getDeleted()) {
3402 option |= AS_STR_SKIPDELETE;
3403 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3406 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3408 LYXERR(Debug::FIND, "Stringifying with cur: "
3409 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3410 return par.asString(cur.pos(), end,
3413 } else if (cur.inMathed()) {
3414 CursorSlice cs = cur.top();
3415 MathData md = cs.cell();
3416 MathData::const_iterator it_end =
3417 (( len == -1 || cs.pos() + len > int(md.size()))
3419 : md.begin() + cs.pos() + len );
3421 for (MathData::const_iterator it = md.begin() + cs.pos();
3424 docstring s = asString(md2);
3425 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3428 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3433 /** Computes the LaTeX export of buf starting from cur and ending len positions
3434 * after cur, if len is positive, or at the paragraph or innermost inset end
3437 docstring latexifyFromCursor(DocIterator const & cur, int len)
3440 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3441 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3442 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3444 Buffer const & buf = *cur.buffer();
3446 odocstringstream ods;
3448 //OutputParams runparams(&buf.params().encoding());
3449 OutputParams runparams(encodings.fromLyXName("utf8"));
3450 runparams.nice = false;
3451 runparams.flavor = Flavor::XeTeX;
3452 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3453 // No side effect of file copying and image conversion
3454 runparams.dryrun = true;
3455 if (ignoreFormats.getDeleted()) {
3456 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3459 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3462 if (cur.inTexted()) {
3463 // @TODO what about searching beyond/across paragraph breaks ?
3464 pos_type endpos = cur.paragraph().size();
3465 if (len != -1 && endpos > cur.pos() + len)
3466 endpos = cur.pos() + len;
3467 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3468 string(), cur.pos(), endpos);
3469 string s = lyx::to_utf8(ods.str());
3470 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3471 return(lyx::from_utf8(s));
3472 } else if (cur.inMathed()) {
3473 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3474 for (int s = cur.depth() - 1; s >= 0; --s) {
3475 CursorSlice const & cs = cur[s];
3476 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3477 TeXMathStream ws(os);
3478 cs.asInsetMath()->asHullInset()->header_write(ws);
3483 CursorSlice const & cs = cur.top();
3484 MathData md = cs.cell();
3485 MathData::const_iterator it_end =
3486 ((len == -1 || cs.pos() + len > int(md.size()))
3488 : md.begin() + cs.pos() + len);
3490 for (MathData::const_iterator it = md.begin() + cs.pos();
3494 ods << asString(md2);
3495 // Retrieve the math environment type, and add '$' or '$]'
3496 // or others (\end{equation}) accordingly
3497 for (int s = cur.depth() - 1; s >= 0; --s) {
3498 CursorSlice const & cs2 = cur[s];
3499 InsetMath * inset = cs2.asInsetMath();
3500 if (inset && inset->asHullInset()) {
3501 TeXMathStream ws(os);
3502 inset->asHullInset()->footer_write(ws);
3506 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3508 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3513 #if defined(ResultsDebug)
3515 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3517 LYXERR0( "from:\t\t\t" << from);
3519 if (mres.pos_len > 0) {
3521 status = "FINALSEARCH";
3524 if (mres.match_len > 0) {
3525 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3526 status = "Good Match";
3528 status = "Matched in";
3531 status = "MissedSearch";
3534 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3535 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3536 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3537 if ((mres.pos > 0) || (mres.match_prefix > 0))
3538 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3539 for (size_t i = 0; i < mres.result.size(); i++)
3540 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3542 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3544 #define displayMres(s, txt, cur)
3547 /** Finalize an advanced find operation, advancing the cursor to the innermost
3548 ** position that matches, plus computing the length of the matching text to
3550 ** Return the cur.pos() difference between start and end of found match
3552 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3554 // Search the foremost position that matches (avoids find of entire math
3555 // inset when match at start of it)
3556 DocIterator old_cur(cur.buffer());
3558 static MatchResult fail = MatchResult();
3559 MatchResult max_match;
3560 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3561 // Happens with e.g. hyperlinks
3562 // either one sees "http://www.bla.bla" or nothing
3563 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3564 // and although we search for only 3 chars, we find the whole hyperlink inset
3565 bool at_begin = (expected.match_prefix == 0);
3566 if (!match.opt.forward && match.opt.ignoreformat) {
3567 if (expected.pos > 0)
3570 LASSERT(at_begin, /**/);
3571 if (expected.match_len > 0 && at_begin) {
3572 // Search for deepest match
3574 max_match = expected;
3576 size_t d = cur.depth();
3580 if (cur.depth() < d)
3582 if (cur.depth() == d)
3585 while (cur && cur.depth() > lastd) {
3586 lastd = cur.depth();
3587 mres = match(cur, -1, at_begin);
3588 displayMres(mres, "Checking innermost", cur);
3589 if (mres.match_len > 0)
3594 if (mres.match_len < expected.match_len)
3602 // (expected.match_len <= 0)
3603 mres = match(cur); /* match valid only if not searching whole words */
3604 displayMres(mres, "Start with negative match", cur);
3607 if (max_match.match_len <= 0) return fail;
3608 LYXERR(Debug::FIND, "Ok");
3610 // Compute the match length
3612 if (cur.pos() + len > cur.lastpos())
3615 LASSERT(match.use_regexp, /**/);
3618 int maxl = cur.lastpos() - cur.pos();
3619 // Greedy behaviour while matching regexps
3620 while (maxl > minl) {
3622 mres2 = match(cur, len, at_begin);
3623 displayMres(mres2, "Finalize loop", cur);
3624 int actual_match_len = mres2.match_len;
3625 if (actual_match_len >= max_match.match_len) {
3626 // actual_match_len > max_match _can_ happen,
3627 // if the search area splits
3628 // some following word so that the regex
3629 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3631 // This means, the len value is too big
3632 actual_match_len = max_match.match_len;
3634 max_match.match_len = actual_match_len;
3636 if (maxl - minl < 4)
3637 len = (int)((maxl + minl)/2);
3639 len = (int)(minl + (maxl - minl + 3)/4);
3642 // (actual_match_len < max_match.match_len)
3644 len = (int)((maxl + minl)/2);
3649 // Search for real start of matched characters
3651 MatchResult actual_match;
3654 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3655 if (cur.depth() < old_cur.depth()) {
3657 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3660 if (cur.pos() != old_cur.pos()) {
3661 // OK, forwarded 1 pos in actual inset
3662 actual_match = match(cur, len-1, at_begin);
3663 if (actual_match.match_len == max_match.match_len) {
3664 // Ha, got it! The shorter selection has the same match length
3667 max_match = actual_match;
3670 // OK, the shorter selection matches less chars, revert to previous value
3676 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3677 actual_match = match(cur, len, at_begin);
3678 if (actual_match.match_len == max_match.match_len) {
3680 max_match = actual_match;
3687 max_match.pos_len = len;
3688 displayMres(max_match, "SEARCH RESULT", cur)
3695 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3699 bool repeat = false;
3700 DocIterator orig_cur; // to be used if repeat not successful
3701 MatchResult orig_mres;
3702 while (!theApp()->longOperationCancelled() && cur) {
3703 //(void) findAdvForwardInnermost(cur);
3704 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3705 MatchResult mres = match(cur, -1, false);
3706 string msg = "Starting";
3709 displayMres(mres, msg + " findForwardAdv", cur)
3710 int match_len = mres.match_len;
3711 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3712 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3715 if (match_len <= 0) {
3716 // This should exit nested insets, if any, or otherwise undefine the currsor.
3717 cur.pos() = cur.lastpos();
3718 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3721 else { // match_len > 0
3722 // Try to find the begin of searched string
3724 int firstInvalid = cur.lastpos() - cur.pos();
3726 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3727 int incrcur = (firstInvalid + 1 )*3/4;
3728 if (incrcur < incrmatch)
3729 increment = incrcur;
3731 increment = incrmatch;
3735 LYXERR(Debug::FIND, "Set increment to " << increment);
3736 while (increment > 0) {
3737 DocIterator old_cur = cur;
3738 if (cur.pos() + increment >= cur.lastpos()) {
3742 cur.pos() = cur.pos() + increment;
3743 MatchResult mres2 = match(cur, -1, false);
3744 displayMres(mres2, "findForwardAdv loop", cur)
3745 switch (interpretMatch(mres, mres2)) {
3746 case MatchResult::newIsTooFar:
3747 // behind the expected match
3748 firstInvalid = increment;
3752 case MatchResult::newIsBetter:
3753 // not reached yet, but cur.pos()+increment is bettert
3755 firstInvalid -= increment;
3756 if (increment > firstInvalid*3/4)
3757 increment = firstInvalid*3/4;
3758 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3759 if (increment >= mres2.match_prefix)
3760 increment = (mres2.match_prefix+1)*3/4;
3765 // Handle not like MatchResult::newIsTooFar
3766 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3768 increment = increment*3/4;
3773 if (mres.match_len > 0) {
3774 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3775 // The match seems to indicate some deeper level
3784 // should never be reached.
3788 // LYXERR0("Leaving first loop");
3789 LYXERR(Debug::FIND, "Finalizing 1");
3790 MatchResult found_match = findAdvFinalize(cur, match, mres);
3791 if (found_match.match_len > 0) {
3792 LASSERT(found_match.pos_len > 0, /**/);
3793 match.FillResults(found_match);
3794 return found_match.pos_len;
3797 // try next possible match
3808 /// Find the most backward consecutive match within same paragraph while searching backwards.
3809 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3811 DocIterator cur_begin = cur;
3812 cur_begin.pos() = 0;
3813 DocIterator tmp_cur = cur;
3814 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3815 Inset & inset = cur.inset();
3816 for (; cur != cur_begin; cur.backwardPos()) {
3817 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3818 DocIterator new_cur = cur;
3819 new_cur.backwardPos();
3820 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3822 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3823 if (new_mr.match_len == mr.match_len)
3827 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3833 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3837 // Backup of original position
3838 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3839 if (cur == cur_begin)
3842 DocIterator cur_orig(cur);
3843 bool pit_changed = false;
3846 MatchResult found_match = match(cur, -1, false);
3848 if (found_match.match_len > 0) {
3850 cur.pos() = cur.lastpos();
3852 cur.pos() = cur_orig.pos();
3853 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3854 DocIterator cur_prev_iter;
3856 found_match = match(cur);
3857 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3858 << (found_match.match_len > 0) << ", cur: " << cur);
3859 if (found_match.match_len > 0) {
3860 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3861 if (found_mr.pos_len > 0) {
3862 match.FillResults(found_mr);
3863 return found_mr.pos_len;
3867 // Stop if begin of document reached
3868 if (cur == cur_begin)
3870 cur_prev_iter = cur;
3874 if (cur == cur_begin)
3881 } while (!theApp()->longOperationCancelled());
3889 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3890 DocIterator const & cur, int len)
3892 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3894 if (!opt.ignoreformat)
3895 return latexifyFromCursor(cur, len);
3897 return stringifyFromCursor(cur, len);
3901 FindAndReplaceOptions::FindAndReplaceOptions(
3902 docstring const & _find_buf_name, bool _casesensitive,
3903 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3904 docstring const & _repl_buf_name, bool _keep_case,
3905 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3906 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3907 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3908 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3916 /** Check if 'len' letters following cursor are all non-lowercase */
3917 static bool allNonLowercase(Cursor const & cur, int len)
3919 pos_type beg_pos = cur.selectionBegin().pos();
3920 pos_type end_pos = cur.selectionBegin().pos() + len;
3921 if (len > cur.lastpos() + 1 - beg_pos) {
3922 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3923 len = cur.lastpos() + 1 - beg_pos;
3924 end_pos = beg_pos + len;
3926 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3927 if (isLowerCase(cur.paragraph().getChar(pos)))
3933 /** Check if first letter is upper case and second one is lower case */
3934 static bool firstUppercase(Cursor const & cur)
3937 pos_type pos = cur.selectionBegin().pos();
3938 if (pos >= cur.lastpos() - 1) {
3939 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3942 ch1 = cur.paragraph().getChar(pos);
3943 ch2 = cur.paragraph().getChar(pos + 1);
3944 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3945 LYXERR(Debug::FIND, "firstUppercase(): "
3946 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3947 << ch2 << "(" << char(ch2) << ")"
3948 << ", result=" << result << ", cur=" << cur);
3953 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3955 ** \fixme What to do with possible further paragraphs in replace buffer ?
3957 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3959 ParagraphList::iterator pit = buffer.paragraphs().begin();
3960 LASSERT(!pit->empty(), /**/);
3961 pos_type right = pos_type(1);
3962 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3963 right = pit->size();
3964 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3968 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3970 // Should replace the string "$" + std::to_string(matchnum) with replacement
3971 // if the char '$' is not prefixed with odd number of char '\\'
3972 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3976 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3978 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3980 int num = stoi(sub.str(3), nullptr, 10);
3981 if (num >= maxmatchnum)
3983 if (lastpos < (size_t) sub.position(2))
3984 s += t.substr(lastpos, sub.position(2) - lastpos);
3985 s += replacements[num];
3986 lastpos = sub.position(2) + sub.length(2);
3990 else if (lastpos < t.length())
3991 s += t.substr(lastpos, t.length() - lastpos);
3997 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3999 Cursor & cur = bv->cursor();
4000 if (opt.repl_buf_name.empty()
4001 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4002 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4005 DocIterator sel_beg = cur.selectionBegin();
4006 DocIterator sel_end = cur.selectionEnd();
4007 if (&sel_beg.inset() != &sel_end.inset()
4008 || sel_beg.pit() != sel_end.pit()
4009 || sel_beg.idx() != sel_end.idx())
4011 int sel_len = sel_end.pos() - sel_beg.pos();
4012 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4013 << ", sel_len: " << sel_len << endl);
4016 LASSERT(sel_len > 0, return 0);
4018 if (!matchAdv(sel_beg, sel_len).match_len)
4021 // Build a copy of the replace buffer, adapted to the KeepCase option
4022 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4024 repl_buffer_orig.write(oss);
4025 string lyx = oss.str();
4026 if (matchAdv.valid_matches > 0) {
4027 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4029 Buffer repl_buffer("", false);
4030 repl_buffer.setUnnamed(true);
4031 LASSERT(repl_buffer.readString(lyx), return 0);
4032 if (opt.keep_case && sel_len >= 2) {
4033 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4034 if (cur.inTexted()) {
4035 if (firstUppercase(cur))
4036 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4037 else if (allNonLowercase(cur, sel_len))
4038 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4041 cap::cutSelection(cur, false);
4042 if (cur.inTexted()) {
4043 repl_buffer.changeLanguage(
4044 repl_buffer.language(),
4045 cur.getFont().language());
4046 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4047 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4048 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4049 repl_buffer.params().documentClassPtr(),
4050 repl_buffer.params().authors(),
4051 bv->buffer().errorList("Paste"));
4052 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4053 sel_len = repl_buffer.paragraphs().begin()->size();
4054 } else if (cur.inMathed()) {
4055 odocstringstream ods;
4057 // OutputParams runparams(&repl_buffer.params().encoding());
4058 OutputParams runparams(encodings.fromLyXName("utf8"));
4059 runparams.nice = false;
4060 runparams.flavor = Flavor::XeTeX;
4061 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4062 runparams.dryrun = true;
4063 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4064 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4065 docstring repl_latex = ods.str();
4066 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4068 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4069 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4070 repl_latex = from_utf8(s);
4071 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4072 MathData ar(cur.buffer());
4073 asArray(repl_latex, ar, Parse::NORMAL);
4075 sel_len = ar.size();
4076 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4078 if (cur.pos() >= sel_len)
4079 cur.pos() -= sel_len;
4082 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4083 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4084 bv->processUpdateFlags(Update::Force);
4089 /// Perform a FindAdv operation.
4090 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4095 // e.g., when invoking word-findadv from mini-buffer wither with
4096 // wrong options syntax or before ever opening advanced F&R pane
4097 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4101 MatchStringAdv matchAdv(bv->buffer(), opt);
4103 if (!matchAdv.regexIsValid) {
4104 bv->message(lyx::from_utf8(matchAdv.regexError));
4108 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4110 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4111 num_replaced += findAdvReplace(bv, opt, matchAdv);
4114 pos_len = findForwardAdv(cur, matchAdv);
4116 pos_len = findBackwardsAdv(cur, matchAdv);
4117 } catch (exception & ex) {
4118 bv->message(from_utf8(ex.what()));
4123 if (num_replaced > 0) {
4124 switch (num_replaced)
4127 bv->message(_("One match has been replaced."));
4130 bv->message(_("Two matches have been replaced."));
4133 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4139 bv->message(_("Match not found."));
4144 if (num_replaced > 0)
4145 bv->message(_("Match has been replaced."));
4147 bv->message(_("Match found."));
4149 if (cur.pos() + pos_len > cur.lastpos()) {
4150 // Prevent crash in bv->putSelectionAt()
4151 // Should never happen, maybe LASSERT() here?
4152 pos_len = cur.lastpos() - cur.pos();
4154 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4155 bv->putSelectionAt(cur, pos_len, !opt.forward);
4161 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4163 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4164 << opt.casesensitive << ' '
4165 << opt.matchword << ' '
4166 << opt.forward << ' '
4167 << opt.expandmacros << ' '
4168 << opt.ignoreformat << ' '
4169 << opt.replace_all << ' '
4170 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4171 << opt.keep_case << ' '
4172 << int(opt.scope) << ' '
4175 LYXERR(Debug::FIND, "built: " << os.str());
4181 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4183 // LYXERR(Debug::FIND, "parsing");
4187 while (line != "EOSS") {
4191 if (is.eof()) // Tolerate malformed request
4195 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4196 opt.find_buf_name = from_utf8(s);
4197 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4198 is.get(); // Waste space before replace string
4201 while (line != "EOSS") {
4205 if (is.eof()) // Tolerate malformed request
4209 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4210 opt.repl_buf_name = from_utf8(s);
4211 is >> opt.keep_case;
4214 opt.scope = FindAndReplaceOptions::SearchScope(i);
4216 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4219 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4220 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4221 << opt.scope << ' ' << opt.restr);