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);
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;
133 bool ignoreDeleted_ = true;
136 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
138 if (type == "color") {
139 ignoreColor_ = value;
141 else if (type == "language") {
142 ignoreLanguage_ = value;
144 else if (type == "sectioning") {
145 ignoreSectioning_ = value;
146 ignoreFrontMatter_ = value;
148 else if (type == "font") {
149 ignoreSeries_ = value;
150 ignoreShape_ = value;
151 ignoreFamily_ = value;
153 else if (type == "series") {
154 ignoreSeries_ = value;
156 else if (type == "shape") {
157 ignoreShape_ = value;
159 else if (type == "family") {
160 ignoreFamily_ = value;
162 else if (type == "markup") {
163 ignoreMarkUp_ = value;
165 else if (type == "underline") {
166 ignoreUnderline_ = value;
168 else if (type == "strike") {
169 ignoreStrikeOut_ = value;
171 else if (type == "deleted") {
172 ignoreDeleted_ = value;
176 // The global variable that can be changed from outside
177 IgnoreFormats ignoreFormats;
180 void setIgnoreFormat(string const & type, bool value)
182 ignoreFormats.setIgnoreFormat(type, value);
188 bool parse_bool(docstring & howto)
193 howto = split(howto, var, ' ');
201 MatchString(docstring const & s, bool cs, bool mw)
202 : str(s), case_sens(cs), whole_words(mw)
205 // returns true if the specified string is at the specified position
206 // del specifies whether deleted strings in ct mode will be considered
207 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
209 return par.find(str, case_sens, whole_words, pos, del);
217 // match whole words only
222 int findForward(DocIterator & cur, MatchString const & match,
223 bool find_del = true)
225 for (; cur; cur.forwardChar())
226 if (cur.inTexted()) {
227 int len = match(cur.paragraph(), cur.pos(), find_del);
235 int findBackwards(DocIterator & cur, MatchString const & match,
236 bool find_del = true)
240 if (cur.inTexted()) {
241 int len = match(cur.paragraph(), cur.pos(), find_del);
250 bool searchAllowed(docstring const & str)
253 frontend::Alert::error(_("Search error"), _("Search string is empty"));
260 bool findOne(BufferView * bv, docstring const & searchstr,
261 bool case_sens, bool whole, bool forward,
262 bool find_del = true, bool check_wrap = false)
264 if (!searchAllowed(searchstr))
267 DocIterator cur = forward
268 ? bv->cursor().selectionEnd()
269 : bv->cursor().selectionBegin();
271 MatchString const match(searchstr, case_sens, whole);
273 int match_len = forward
274 ? findForward(cur, match, find_del)
275 : findBackwards(cur, match, find_del);
278 bv->putSelectionAt(cur, match_len, !forward);
279 else if (check_wrap) {
280 DocIterator cur_orig(bv->cursor());
283 q = _("End of file reached while searching forward.\n"
284 "Continue searching from the beginning?");
286 q = _("Beginning of file reached while searching backward.\n"
287 "Continue searching from the end?");
288 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
289 q, 0, 1, _("&Yes"), _("&No"));
290 if (wrap_answer == 0) {
292 bv->cursor().clear();
293 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
295 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
296 bv->cursor().backwardPos();
298 bv->clearSelection();
299 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
302 bv->cursor().setCursor(cur_orig);
306 return match_len > 0;
310 int replaceAll(BufferView * bv,
311 docstring const & searchstr, docstring const & replacestr,
312 bool case_sens, bool whole)
314 Buffer & buf = bv->buffer();
316 if (!searchAllowed(searchstr) || buf.isReadonly())
319 DocIterator cur_orig(bv->cursor());
321 MatchString const match(searchstr, case_sens, whole);
324 int const rsize = replacestr.size();
325 int const ssize = searchstr.size();
328 cur.setCursor(doc_iterator_begin(&buf));
329 int match_len = findForward(cur, match, false);
330 while (match_len > 0) {
331 // Backup current cursor position and font.
332 pos_type const pos = cur.pos();
333 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
335 int striked = ssize -
336 cur.paragraph().eraseChars(pos, pos + match_len,
337 buf.params().track_changes);
338 cur.paragraph().insert(pos, replacestr, font,
339 Change(buf.params().track_changes
341 : Change::UNCHANGED));
342 for (int i = 0; i < rsize + striked; ++i)
345 match_len = findForward(cur, match, false);
348 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
350 cur_orig.fixIfBroken();
351 bv->setCursor(cur_orig);
357 // the idea here is that we are going to replace the string that
358 // is selected IF it is the search string.
359 // if there is a selection, but it is not the search string, then
360 // we basically ignore it. (FIXME We ought to replace only within
362 // if there is no selection, then:
363 // (i) if some search string has been provided, then we find it.
364 // (think of how the dialog works when you hit "replace" the
366 // (ii) if no search string has been provided, then we treat the
367 // word the cursor is in as the search string. (why? i have no
368 // idea.) but this only works in text?
370 // returns the number of replacements made (one, if any) and
371 // whether anything at all was done.
372 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
373 docstring const & replacestr, bool case_sens,
374 bool whole, bool forward, bool findnext)
376 Cursor & cur = bv->cursor();
377 if (!cur.selection()) {
378 // no selection, non-empty search string: find it
379 if (!searchstr.empty()) {
380 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
381 return make_pair(found, 0);
383 // empty search string
386 return make_pair(false, 0);
387 // select current word and treat it as the search string.
388 // This causes a minor bug as undo will restore this selection,
389 // which the user did not create (#8986).
390 cur.innerText()->selectWord(cur, WHOLE_WORD);
391 searchstr = cur.selectionAsString(false, true);
394 // if we still don't have a search string, report the error
396 if (!searchAllowed(searchstr))
397 return make_pair(false, 0);
399 bool have_selection = cur.selection();
400 docstring const selected = cur.selectionAsString(false, true);
403 ? searchstr == selected
404 : compare_no_case(searchstr, selected) == 0;
406 // no selection or current selection is not search word:
407 // just find the search word
408 if (!have_selection || !match) {
409 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
410 return make_pair(found, 0);
413 // we're now actually ready to replace. if the buffer is
414 // read-only, we can't, though.
415 if (bv->buffer().isReadonly())
416 return make_pair(false, 0);
418 cap::replaceSelectionWithString(cur, replacestr);
420 cur.pos() += replacestr.length();
421 LASSERT(cur.pos() <= cur.lastpos(),
422 cur.pos() = cur.lastpos());
425 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
427 return make_pair(true, 1);
433 docstring const find2string(docstring const & search,
434 bool casesensitive, bool matchword, bool forward)
438 << int(casesensitive) << ' '
439 << int(matchword) << ' '
445 docstring const replace2string(docstring const & replace,
446 docstring const & search,
447 bool casesensitive, bool matchword,
448 bool all, bool forward, bool findnext)
451 ss << replace << '\n'
453 << int(casesensitive) << ' '
454 << int(matchword) << ' '
456 << int(forward) << ' '
462 bool lyxfind(BufferView * bv, FuncRequest const & ev)
464 if (!bv || ev.action() != LFUN_WORD_FIND)
467 //lyxerr << "find called, cmd: " << ev << endl;
469 // data is of the form
471 // <casesensitive> <matchword> <forward>"
473 docstring howto = split(ev.argument(), search, '\n');
475 bool casesensitive = parse_bool(howto);
476 bool matchword = parse_bool(howto);
477 bool forward = parse_bool(howto);
479 return findOne(bv, search, casesensitive, matchword, forward, false, true);
483 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
485 if (!bv || ev.action() != LFUN_WORD_REPLACE)
488 // data is of the form
491 // <casesensitive> <matchword> <all> <forward> <findnext>"
494 docstring howto = split(ev.argument(), rplc, '\n');
495 howto = split(howto, search, '\n');
497 bool casesensitive = parse_bool(howto);
498 bool matchword = parse_bool(howto);
499 bool all = parse_bool(howto);
500 bool forward = parse_bool(howto);
501 bool findnext = howto.empty() ? true : parse_bool(howto);
505 int replace_count = 0;
507 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
508 update = replace_count > 0;
511 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
513 replace_count = rv.second;
516 Buffer const & buf = bv->buffer();
518 // emit message signal.
519 buf.message(_("String not found."));
521 if (replace_count == 0) {
522 buf.message(_("String found."));
523 } else if (replace_count == 1) {
524 buf.message(_("String has been replaced."));
526 docstring const str =
527 bformat(_("%1$d strings have been replaced."), replace_count);
535 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
537 for (; cur; cur.forwardPos())
538 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
542 DocIterator cur_orig(bv->cursor());
543 docstring q = _("End of file reached while searching forward.\n"
544 "Continue searching from the beginning?");
545 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
546 q, 0, 1, _("&Yes"), _("&No"));
547 if (wrap_answer == 0) {
548 bv->cursor().clear();
549 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
550 bv->clearSelection();
551 cur.setCursor(bv->cursor().selectionBegin());
552 if (findNextChange(bv, cur, false))
555 bv->cursor().setCursor(cur_orig);
562 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
564 for (cur.backwardPos(); cur; cur.backwardPos()) {
565 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
570 DocIterator cur_orig(bv->cursor());
571 docstring q = _("Beginning of file reached while searching backward.\n"
572 "Continue searching from the end?");
573 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
574 q, 0, 1, _("&Yes"), _("&No"));
575 if (wrap_answer == 0) {
576 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
577 bv->cursor().backwardPos();
578 bv->clearSelection();
579 cur.setCursor(bv->cursor().selectionBegin());
580 if (findPreviousChange(bv, cur, false))
583 bv->cursor().setCursor(cur_orig);
590 bool selectChange(Cursor & cur, bool forward)
592 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
594 Change ch = cur.paragraph().lookupChange(cur.pos());
596 CursorSlice tip1 = cur.top();
597 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
598 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
599 if (!ch2.isSimilarTo(ch))
602 CursorSlice tip2 = cur.top();
603 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
605 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
606 if (!ch2.isSimilarTo(ch)) {
607 // take a step forward to correctly set the selection
615 cur.bv().mouseSetCursor(cur, false);
617 cur.bv().mouseSetCursor(cur, true);
625 bool findChange(BufferView * bv, bool forward)
628 cur.setCursor(forward ? bv->cursor().selectionEnd()
629 : bv->cursor().selectionBegin());
630 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
631 return selectChange(cur, forward);
636 bool findNextChange(BufferView * bv)
638 return findChange(bv, true);
642 bool findPreviousChange(BufferView * bv)
644 return findChange(bv, false);
651 typedef vector<pair<string, string> > Escapes;
653 string string2regex(string in)
655 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
656 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
661 while (fl_pos < temp.size()) {
662 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
663 if (fl_pos == string::npos)
666 temp2 += temp.substr(lastpos, fl_pos - lastpos);
672 if (lastpos < temp.size()) {
673 temp2 += temp.substr(lastpos, temp.size() - lastpos);
678 string correctRegex(string t, bool withformat)
680 /* Convert \backslash => \
681 * and \{, \}, \[, \] => {, }, [, ]
684 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
687 bool backslashed = false;
688 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
691 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
695 if (sub.str(4) == "backslash") {
698 // transforms '\backslash \{' into '\{'
700 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
701 if ((next == "\\{") || (next == "\\}")) {
707 else if (sub.str(4) == "mathcircumflex")
709 else if (backslashed) {
711 if (withformat && (sub.str(3) == "{"))
712 replace = accents["braceleft"];
713 else if (withformat && (sub.str(3) == "}"))
714 replace = accents["braceright"];
716 // else part should not exist
721 replace = sub.str(3);
723 if (lastpos < (size_t) sub.position(2))
724 s += t.substr(lastpos, sub.position(2) - lastpos);
726 lastpos = sub.position(2) + sub.length(2);
730 else if (lastpos < t.length())
731 s += t.substr(lastpos, t.length() - lastpos);
735 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
736 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
737 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
738 string escape_for_regex(string s, bool withformat)
742 while (lastpos < s.size()) {
743 size_t regex_pos = s.find("\\regexp{", lastpos);
744 if (regex_pos == string::npos) {
745 regex_pos = s.size();
747 if (regex_pos > lastpos) {
748 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
750 if (lastpos == s.size())
753 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
754 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
755 lastpos = end_pos + 13;
761 /// Wrapper for lyx::regex_replace with simpler interface
762 bool regex_replace(string const & s, string & t, string const & searchstr,
763 string const & replacestr)
765 regex e(searchstr, regex_constants::ECMAScript);
767 ostream_iterator<char, char> it(oss);
768 regex_replace(it, s.begin(), s.end(), e, replacestr);
769 // tolerate t and s be references to the same variable
770 bool rv = (s != oss.str());
789 vector <string> result = vector <string>();
790 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
793 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
795 if (newres.match2end < oldres.match2end)
796 return MatchResult::newIsTooFar;
797 if (newres.match_len < oldres.match_len)
798 return MatchResult::newIsTooFar;
800 if (newres.match_len == oldres.match_len) {
801 if (newres.match2end == oldres.match2end)
802 return MatchResult::newIsBetter;
804 return MatchResult::newIsInvalid;
807 /** The class performing a match between a position in the document and the FindAdvOptions.
810 class MatchStringAdv {
812 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
814 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
815 ** constructor as opt.search, under the opt.* options settings.
818 ** If set, then match is searched only against beginning of text starting at cur.
819 ** If unset, then match is searched anywhere in text starting at cur.
822 ** The length of the matching text, or zero if no match was found.
824 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
833 /// first buffer on which search was started
834 lyx::Buffer * const p_first_buf;
836 FindAndReplaceOptions const & opt;
839 /// Auxiliary find method (does not account for opt.matchword)
840 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
841 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
843 /** Normalize a stringified or latexified LyX paragraph.
847 ** <li>if search is not casesensitive, then lowercase the string;
848 ** <li>remove any newline at begin or end of the string;
849 ** <li>replace any newline in the middle of the string with a simple space;
850 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
853 ** @todo Normalization should also expand macros, if the corresponding
854 ** search option was checked.
856 string normalize(docstring const & s) const;
857 // normalized string to search
858 string par_as_string;
859 // regular expression to use for searching
860 // regexp2 is same as regexp, but prefixed with a ".*?"
862 QRegularExpression regexp;
863 QRegularExpression regexp2;
868 // leading format material as string
869 string lead_as_string;
870 // par_as_string after removal of lead_as_string
871 string par_as_string_nolead;
872 // unmatched open braces in the search string/regexp
874 // number of (.*?) subexpressions added at end of search regexp for closing
875 // environments, math mode, styles, etc...
878 // Are we searching with regular expressions ?
880 static int valid_matches;
881 static vector <string> matches;
882 void FillResults(MatchResult &found_mr);
885 int MatchStringAdv::valid_matches = 0;
886 vector <string> MatchStringAdv::matches = vector <string>(10);
888 void MatchStringAdv::FillResults(MatchResult &found_mr)
890 if (found_mr.match_len > 0) {
891 valid_matches = found_mr.result.size();
892 for (size_t i = 0; i < found_mr.result.size(); i++)
893 matches[i] = found_mr.result[i];
899 static docstring buffer_to_latex(Buffer & buffer)
901 //OutputParams runparams(&buffer.params().encoding());
902 OutputParams runparams(encodings.fromLyXName("utf8"));
903 odocstringstream ods;
905 runparams.nice = true;
906 runparams.flavor = Flavor::XeTeX;
907 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
908 // No side effect of file copying and image conversion
909 runparams.dryrun = true;
910 if (ignoreFormats.getDeleted())
911 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
913 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
914 pit_type const endpit = buffer.paragraphs().size();
915 for (pit_type pit = 0; pit != endpit; ++pit) {
916 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
917 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
923 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
926 if (!opt.ignoreformat) {
927 str = buffer_to_latex(buffer);
929 // OutputParams runparams(&buffer.params().encoding());
930 OutputParams runparams(encodings.fromLyXName("utf8"));
931 runparams.nice = true;
932 runparams.flavor = Flavor::XeTeX;
933 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
934 runparams.dryrun = true;
935 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
936 if (ignoreFormats.getDeleted()) {
937 option |= AS_STR_SKIPDELETE;
938 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
941 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
943 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
944 Paragraph const & par = buffer.paragraphs().at(pit);
945 LYXERR(Debug::FIND, "Adding to search string: '"
946 << par.asString(pos_type(0), par.size(),
950 str += par.asString(pos_type(0), par.size(),
954 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
955 string t = to_utf8(str);
956 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
963 /// Return separation pos between the leading material and the rest
964 static size_t identifyLeading(string const & s)
967 // @TODO Support \item[text]
968 // Kornel: Added textsl, textsf, textit, texttt and noun
969 // + allow to search for colored text too
970 while (regex_replace(t, t, "^\\\\(("
971 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
972 "lyxaddress|lyxrightaddress|"
973 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
974 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
975 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
976 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
977 || regex_replace(t, t, "^\\$", "")
978 || regex_replace(t, t, "^\\\\\\[", "")
979 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
980 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
982 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
987 * Given a latexified string, retrieve some handled features
988 * The features of the regex will later be compared with the features
989 * of the searched text. If the regex features are not a
990 * subset of the analized, then, in not format ignoring search
991 * we can early stop the search in the relevant inset.
993 typedef map<string, bool> Features;
995 static Features identifyFeatures(string const & s)
997 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
998 static regex const valid("^("
1000 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1001 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1002 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1003 "(u|uu)line|(s|x)out|uwave|"
1004 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1005 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1010 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1013 if (sub.str(1).compare("regexp") == 0) {
1017 string token = sub.str(1);
1019 if (regex_match(token, sub2, valid)) {
1027 if (sub.str(1).compare("endregexp") == 0) {
1037 * defines values features of a key "\\[a-z]+{"
1042 /* Char type with content discarded
1043 * like \hspace{1cm} */
1045 /* Char, like \backslash */
1047 /* replace starting backslash with '#' */
1049 /* \part, \section*, ... */
1051 /* title, author etc */
1053 /* \foreignlanguage{ngerman}, ... */
1056 * to discard language in content */
1059 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1061 /* fonts, colors, markups, ... */
1063 /* footnotesize, ... large, ...
1064 * Ignore all of them */
1067 /* inputencoding, ...
1068 * Discard also content, because they do not help in search */
1071 * like remove, but also all arguments */
1073 /* item, listitem */
1075 /* tex, latex, ... like isChar */
1077 /* like \lettrine[lines=5]{}{} */
1079 // like isStandard, but always remove head
1081 /* End of arguments marker for lettrine,
1082 * so that they can be ignored */
1085 KeyInfo() = default;
1086 KeyInfo(KeyType type, int parcount, bool disable)
1088 parenthesiscount(parcount),
1089 disabled(disable) {}
1090 KeyType keytype = invalid;
1092 int _tokensize = -1;
1093 int _tokenstart = -1;
1094 int _dataStart = -1;
1096 int parenthesiscount = 1;
1097 bool disabled = false;
1098 bool used = false; /* by pattern */
1103 Border(int l=0, int u=0) : low(l), upper(u) {};
1108 #define MAXOPENED 30
1110 bool isPatternString_;
1112 explicit Intervall(bool isPattern, string const & p) :
1113 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1114 hasTitle(false), langcount(0)
1122 static vector<Border> borders;
1123 int depts[MAXOPENED];
1124 int closes[MAXOPENED];
1125 int actualdeptindex;
1126 int previousNotIgnored(int) const;
1127 int nextNotIgnored(int) const;
1128 void handleOpenP(int i);
1129 void handleCloseP(int i, bool closingAllowed);
1130 void resetOpenedP(int openPos);
1131 void addIntervall(int upper);
1132 void addIntervall(int low, int upper); /* if explicit */
1133 void removeAccents();
1134 void setForDefaultLang(KeyInfo const & defLang) const;
1135 int findclosing(int start, int end, char up, char down, int repeat);
1136 void handleParentheses(int lastpos, bool closingAllowed);
1138 int langcount; // Number of disabled language specs up to current position in actual interval
1139 int isOpeningPar(int pos) const;
1141 void output(ostringstream &os, int lastpos);
1142 // string show(int lastpos);
1145 vector<Border> Intervall::borders = vector<Border>(30);
1147 int Intervall::isOpeningPar(int pos) const
1149 if ((pos < 0) || (size_t(pos) >= par.size()))
1151 if (par[pos] != '{')
1153 if (size_t(pos) + 2 >= par.size())
1155 if (par[pos+2] != '}')
1157 if (par[pos+1] == '[' || par[pos+1] == ']')
1162 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1164 // Enable the use of first token again
1165 if (ignoreidx >= 0) {
1166 int value = defLang._tokenstart + defLang._tokensize;
1172 if (borders[borderidx].low < value)
1173 borders[borderidx].low = value;
1174 if (borders[borderidx].upper < value)
1175 borders[borderidx].upper = value;
1180 static void checkDepthIndex(int val)
1182 static int maxdepthidx = MAXOPENED-2;
1183 static int lastmaxdepth = 0;
1184 if (val > lastmaxdepth) {
1185 LYXERR(Debug::INFO, "Depth reached " << val);
1188 if (val > maxdepthidx) {
1190 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1195 // Not needed, because borders are now dynamically expanded
1196 static void checkIgnoreIdx(int val)
1198 static int lastmaxignore = -1;
1199 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1200 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1201 lastmaxignore = val;
1207 * Expand the region of ignored parts of the input latex string
1208 * The region is only relevant in output()
1210 void Intervall::addIntervall(int low, int upper)
1213 if (low == upper) return;
1214 for (idx = ignoreidx+1; idx > 0; --idx) {
1215 if (low > borders[idx-1].upper) {
1219 Border br(low, upper);
1220 if (idx > ignoreidx) {
1221 if (borders.size() <= size_t(idx)) {
1222 borders.push_back(br);
1228 // checkIgnoreIdx(ignoreidx);
1232 // Expand only if one of the new bound is inside the interwall
1233 // We know here that br.low > borders[idx-1].upper
1234 if (br.upper < borders[idx].low) {
1235 // We have to insert at this pos
1236 if (size_t(ignoreidx+1) >= borders.size()) {
1237 borders.push_back(borders[ignoreidx]);
1240 borders[ignoreidx+1] = borders[ignoreidx];
1242 for (int i = ignoreidx; i > idx; --i) {
1243 borders[i] = borders[i-1];
1247 // checkIgnoreIdx(ignoreidx);
1250 // Here we know, that we are overlapping
1251 if (br.low > borders[idx].low)
1252 br.low = borders[idx].low;
1253 // check what has to be concatenated
1255 for (int i = idx; i <= ignoreidx; i++) {
1256 if (br.upper >= borders[i].low) {
1258 if (br.upper < borders[i].upper)
1259 br.upper = borders[i].upper;
1265 // count should be >= 1 here
1268 for (int i = idx + count; i <= ignoreidx; i++) {
1269 borders[i-count+1] = borders[i];
1271 ignoreidx -= count - 1;
1277 static void buildaccent(string n, string param, string values)
1281 const char delim = '|';
1282 while (getline(s, name, delim)) {
1284 for (char c : param) {
1285 string key = name + "{" + c + "}";
1286 // get the corresponding utf8-value
1287 if ((values[start] & 0xc0) != 0xc0) {
1288 // should not happen, utf8 encoding starts at least with 11xxxxxx
1289 // but value for '\dot{i}' is 'i', which is ascii
1290 if ((values[start] & 0x80) == 0) {
1292 accents[key] = values.substr(start, 1);
1293 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1298 for (int j = 1; ;j++) {
1299 if (start + j >= values.size()) {
1300 accents[key] = values.substr(start, j);
1301 start = values.size() - 1;
1304 else if ((values[start+j] & 0xc0) != 0x80) {
1305 // This is the first byte of following utf8 char
1306 accents[key] = values.substr(start, j);
1308 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1317 static string getutf8(unsigned uchar)
1320 string ret = string();
1322 if (uchar <= 0x7f) {
1323 c[maxc-1] = uchar & 0x7f;
1326 unsigned char rest = 0x40;
1327 unsigned char first = 0x80;
1329 for (int i = start; i >=0; --i) {
1331 c[i] = first + uchar;
1334 c[i] = 0x80 | (uchar & 0x3f);
1341 for (int i = 0; i < maxc; i++) {
1342 if (c[i] == 0) continue;
1348 static void buildAccentsMap()
1350 accents["imath"] = "ı";
1352 accents["jmath"] = "ȷ";
1353 accents["cdot"] = "·";
1354 accents["textasciicircum"] = "^";
1355 accents["mathcircumflex"] = "^";
1356 accents["sim"] = "~";
1357 accents["guillemotright"] = "»";
1358 accents["guillemotleft"] = "«";
1359 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1360 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1361 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1362 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1363 accents["negmedspace"] = getutf8(0xf0005);
1364 accents["thickspace"] = getutf8(0xf0006);
1365 accents["negthickspace"] = getutf8(0xf0007);
1366 accents["lyx"] = getutf8(0xf0010); // Used logos
1367 accents["LyX"] = getutf8(0xf0010);
1368 accents["tex"] = getutf8(0xf0011);
1369 accents["TeX"] = getutf8(0xf0011);
1370 accents["latex"] = getutf8(0xf0012);
1371 accents["LaTeX"] = getutf8(0xf0012);
1372 accents["latexe"] = getutf8(0xf0013);
1373 accents["LaTeXe"] = getutf8(0xf0013);
1374 accents["lyxarrow"] = getutf8(0xf0020);
1375 accents["braceleft"] = getutf8(0xf0030);
1376 accents["braceright"] = getutf8(0xf0031);
1377 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1378 accents["backslash LyX"] = getutf8(0xf0010);
1379 accents["backslash tex"] = getutf8(0xf0011);
1380 accents["backslash TeX"] = getutf8(0xf0011);
1381 accents["backslash latex"] = getutf8(0xf0012);
1382 accents["backslash LaTeX"] = getutf8(0xf0012);
1383 accents["backslash latexe"] = getutf8(0xf0013);
1384 accents["backslash LaTeXe"] = getutf8(0xf0013);
1385 accents["backslash lyxarrow"] = getutf8(0xf0020);
1386 accents["ddot{\\imath}"] = "ï";
1387 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1388 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1389 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1390 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1391 accents["acute{\\imath}"] = "í";
1392 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1393 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1394 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1395 buildaccent("mathring|r", "aAuUwy",
1397 accents["check{\\imath}"] = "ǐ";
1398 accents["check{\\jmath}"] = "ǰ";
1399 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1400 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1401 accents["hat{\\imath}"] = "î";
1402 accents["hat{\\jmath}"] = "ĵ";
1403 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1404 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1405 accents["bar{\\imath}"] = "ī";
1406 buildaccent("bar|=", "aAeEiIoOuUyY",
1407 "āĀēĒīĪōŌūŪȳȲ"); // macron
1408 accents["tilde{\\imath}"] = "ĩ";
1409 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1410 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1411 accents["breve{\\imath}"] = "ĭ";
1412 buildaccent("breve|u", "aAeEgGiIoOuU",
1413 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1414 accents["grave{\\imath}"] = "ì";
1415 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1416 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1417 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1418 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1419 buildaccent("ogonek|k", "AaEeIiUuOo",
1420 "ĄąĘęĮįŲųǪǫ"); // ogonek
1421 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1422 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1423 buildaccent("subring|textsubring", "Aa",
1425 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1426 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1427 buildaccent("subtilde|textsubtilde", "EeIiUu",
1428 "ḚḛḬḭṴṵ"); // subtilde
1429 accents["dgrave{\\imath}"] = "ȉ";
1430 accents["textdoublegrave{\\i}"] = "ȉ";
1431 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1432 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1433 accents["rcap{\\imath}"] = "ȉ";
1434 accents["textroundcap{\\i}"] = "ȉ";
1435 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1436 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1437 buildaccent("slashed", "oO",
1442 * Created accents in math or regexp environment
1443 * are macros, but we need the utf8 equivalent
1445 void Intervall::removeAccents()
1447 if (accents.empty())
1449 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1450 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1451 "|((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]))");
1453 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1455 string key = sub.str(1);
1456 AccentsIterator it_ac = accents.find(key);
1457 if (it_ac != accents.end()) {
1458 string val = it_ac->second;
1459 size_t pos = sub.position(size_t(0));
1460 for (size_t i = 0; i < val.size(); i++) {
1461 par[pos+i] = val[i];
1463 // Remove possibly following space too
1464 if (par[pos+sub.str(0).size()] == ' ')
1465 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1467 addIntervall(pos+val.size(), pos + sub.str(0).size());
1468 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1469 // remove traces of any remaining chars
1474 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1479 void Intervall::handleOpenP(int i)
1482 depts[actualdeptindex] = i+1;
1483 closes[actualdeptindex] = -1;
1484 checkDepthIndex(actualdeptindex);
1487 void Intervall::handleCloseP(int i, bool closingAllowed)
1489 if (actualdeptindex <= 0) {
1490 if (! closingAllowed)
1491 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1492 // if we are at the very end
1493 addIntervall(i, i+1);
1496 closes[actualdeptindex] = i+1;
1501 void Intervall::resetOpenedP(int openPos)
1503 // Used as initializer for foreignlanguage entry
1504 actualdeptindex = 1;
1505 depts[1] = openPos+1;
1509 int Intervall::previousNotIgnored(int start) const
1511 int idx = 0; /* int intervalls */
1512 for (idx = ignoreidx; idx >= 0; --idx) {
1513 if (start > borders[idx].upper)
1515 if (start >= borders[idx].low)
1516 start = borders[idx].low-1;
1521 int Intervall::nextNotIgnored(int start) const
1523 int idx = 0; /* int intervalls */
1524 for (idx = 0; idx <= ignoreidx; idx++) {
1525 if (start < borders[idx].low)
1527 if (start < borders[idx].upper)
1528 start = borders[idx].upper;
1533 typedef unordered_map<string, KeyInfo> KeysMap;
1534 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1535 typedef vector< KeyInfo> Entries;
1536 static KeysMap keys = unordered_map<string, KeyInfo>();
1542 Intervall interval_;
1543 void buildKeys(bool);
1544 void buildEntries(bool);
1545 void makeKey(const string &, KeyInfo, bool isPatternString);
1546 void processRegion(int start, int region_end); /* remove {} parts */
1547 void removeHead(KeyInfo const &, int count=0);
1550 LatexInfo(string const & par, bool isPatternString)
1551 : entidx_(-1), interval_(isPatternString, par)
1553 buildKeys(isPatternString);
1554 entries_ = vector<KeyInfo>();
1555 buildEntries(isPatternString);
1559 if (entries_.empty()) {
1562 if (entries_[0].keytype == KeyInfo::isTitle) {
1563 interval_.hasTitle = true;
1564 if (! entries_[0].disabled) {
1565 interval_.titleValue = entries_[0].head;
1568 interval_.titleValue = "";
1570 removeHead(entries_[0]);
1571 if (entries_.size() > 1)
1580 if (int(entries_.size()) > entidx_) {
1587 bool setNextKey(int idx) {
1588 if ((idx == entidx_) && (entidx_ >= 0)) {
1595 int find(int start, KeyInfo::KeyType keytype) const {
1599 while (tmpIdx < int(entries_.size())) {
1600 if (entries_[tmpIdx].keytype == keytype)
1606 int process(ostringstream & os, KeyInfo const & actual);
1607 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1608 // string show(int lastpos) { return interval.show(lastpos);};
1609 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1610 KeyInfo &getKeyInfo(int keyinfo) {
1611 static KeyInfo invalidInfo = KeyInfo();
1612 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1615 return entries_[keyinfo];
1617 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1618 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1622 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1626 for (int i = start; i < end; i += 1 + skip) {
1630 if (c == '\\') skip = 1;
1634 else if (c == down) {
1637 if ((repeat <= 0) || (par[i+1] != up))
1651 size_t mathpostfixsize;
1653 size_t mathprefixsize;
1657 vector<MathEntry> entries_;
1662 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1663 MathEntry m = MathEntry();
1665 m.mathStart = start;
1666 m.mathprefixsize = prefixsize;
1668 m.mathpostfixsize = postfixsize;
1669 m.mathSize = end - start;
1670 entries_.push_back(m);
1672 bool empty() const { return entries_.empty(); };
1673 size_t getEndPos() const {
1674 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1677 return entries_[actualIdx_].mathEnd;
1679 size_t getStartPos() const {
1680 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1681 return 100000; /* definitely enough? */
1683 return entries_[actualIdx_].mathStart;
1685 size_t getPrefixSize() const {
1686 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1689 return entries_[actualIdx_].mathprefixsize;
1691 size_t getPostfixSize() const {
1692 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1695 return entries_[actualIdx_].mathpostfixsize;
1697 size_t getFirstPos() {
1699 return getStartPos();
1701 size_t getSize() const {
1702 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1705 return entries_[actualIdx_].mathSize;
1707 void incrEntry() { actualIdx_++; };
1710 void LatexInfo::buildEntries(bool isPatternString)
1712 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1713 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1714 static bool disableLanguageOverride = false;
1715 smatch sub, submath;
1716 bool evaluatingRegexp = false;
1718 bool evaluatingMath = false;
1719 bool evaluatingCode = false;
1721 bool evaluatingOptional = false;
1722 size_t optionalEnd = 0;
1725 bool math_end_waiting = false;
1726 size_t math_pos = 10000;
1727 size_t math_prefix_size = 1;
1729 static vector<string> usedText = vector<string>();
1730 static bool removeMathHull = false;
1732 interval_.removeAccents();
1734 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1736 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1737 // prefixed by odd count of '\\'
1740 if (math_end_waiting) {
1741 size_t pos = submath.position(size_t(2));
1742 if ((math_end == "$") &&
1743 (submath.str(2) == "$")) {
1744 mi.insert("$", math_pos, 1, pos + 1, 1);
1745 math_end_waiting = false;
1747 else if ((math_end == "\\]") &&
1748 (submath.str(2) == "\\]")) {
1749 mi.insert("\\]", math_pos, 2, pos + 2, 2);
1750 math_end_waiting = false;
1752 else if ((submath.str(3).compare("end") == 0) &&
1753 (submath.str(4).compare(math_end) == 0)) {
1754 mi.insert(math_end, math_pos, math_prefix_size, pos + submath.str(2).length(), submath.str(2).length());
1755 math_end_waiting = false;
1761 if (submath.str(3).compare("begin") == 0) {
1762 math_end_waiting = true;
1763 math_end = submath.str(4);
1764 math_pos = submath.position(size_t(2));
1765 math_prefix_size = submath.str(2).length();
1767 else if (submath.str(2).compare("\\[") == 0) {
1768 math_end_waiting = true;
1770 math_pos = submath.position(size_t(2));
1772 else if (submath.str(2) == "$") {
1773 size_t pos = submath.position(size_t(2));
1774 math_end_waiting = true;
1780 // Ignore language if there is math somewhere in pattern-string
1781 if (isPatternString) {
1782 for (auto s: usedText) {
1783 // Remove entries created in previous search runs
1786 usedText = vector<string>();
1789 keys["foreignlanguage"].disabled = true;
1790 disableLanguageOverride = true;
1791 removeMathHull = false;
1794 removeMathHull = true; // used later if not isPatternString
1795 disableLanguageOverride = false;
1799 if (disableLanguageOverride) {
1800 keys["foreignlanguage"].disabled = true;
1803 math_pos = mi.getFirstPos();
1804 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1806 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1807 // prefixed by odd count of '\\'
1810 string key = sub.str(5);
1812 if (sub.str(2)[0] == '\\')
1813 key = sub.str(2)[1];
1818 KeysIterator it_key = keys.find(key);
1819 if (it_key != keys.end()) {
1820 if (it_key->second.keytype == KeyInfo::headRemove) {
1821 KeyInfo found1 = it_key->second;
1822 found1.disabled = true;
1823 found1.head = "\\" + key + "{";
1824 found1._tokenstart = sub.position(size_t(2));
1825 found1._tokensize = found1.head.length();
1826 found1._dataStart = found1._tokenstart + found1.head.length();
1827 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1828 found1._dataEnd = endpos;
1833 if (evaluatingRegexp) {
1834 if (sub.str(3).compare("endregexp") == 0) {
1835 evaluatingRegexp = false;
1836 // found._tokenstart already set
1837 found._dataEnd = sub.position(size_t(2)) + 13;
1838 found._dataStart = found._dataEnd;
1839 found._tokensize = found._dataEnd - found._tokenstart;
1840 found.parenthesiscount = 0;
1841 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1848 if (evaluatingMath) {
1849 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1851 evaluatingMath = false;
1853 math_pos = mi.getStartPos();
1855 if (it_key == keys.end()) {
1856 found = KeyInfo(KeyInfo::isStandard, 0, true);
1857 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1858 found = KeyInfo(KeyInfo::isText, 0, false);
1859 if (isPatternString) {
1860 found.keytype = KeyInfo::isChar;
1861 found.disabled = false;
1865 usedText.push_back(key);
1869 if (key.compare("regexp") == 0) {
1870 evaluatingRegexp = true;
1871 found._tokenstart = sub.position(size_t(2));
1872 found._tokensize = 0;
1876 // Handle the other params of key
1877 if (found.keytype == KeyInfo::isIgnored)
1879 else if (found.keytype == KeyInfo::isMath) {
1880 if (size_t(sub.position(size_t(2))) == math_pos) {
1882 found._tokenstart = sub.position(size_t(2));
1883 found._tokensize = mi.getSize();
1884 found._dataEnd = found._tokenstart + found._tokensize;
1885 found._dataStart = found._dataEnd;
1886 found.parenthesiscount = 0;
1887 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1888 if (removeMathHull) {
1889 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1890 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1892 evaluatingMath = true;
1895 // begin|end of unknown env, discard
1896 // First handle tables
1897 // longtable|tabular
1898 bool discardComment;
1900 found.keytype = KeyInfo::doRemove;
1901 if ((sub.str(7).compare("longtable") == 0) ||
1902 (sub.str(7).compare("tabular") == 0)) {
1903 discardComment = true; /* '%' */
1906 discardComment = false;
1907 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1909 string token = sub.str(7);
1910 if (regex_match(token, sub2, removeArgs)) {
1911 found.keytype = KeyInfo::removeWithArg;
1914 // discard spaces before pos(2)
1915 int pos = sub.position(size_t(2));
1917 for (count = 0; pos - count > 0; count++) {
1918 char c = interval_.par[pos-count-1];
1919 if (discardComment) {
1920 if ((c != ' ') && (c != '%'))
1926 found._tokenstart = pos - count;
1927 if (sub.str(3).compare(0, 5, "begin") == 0) {
1928 size_t pos1 = pos + sub.str(2).length();
1929 if (sub.str(7).compare("cjk") == 0) {
1930 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1931 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1933 found.keytype = KeyInfo::isMain;
1934 found._dataStart = pos1;
1935 found._dataEnd = interval_.par.length();
1936 found.disabled = keys["foreignlanguage"].disabled;
1937 found.used = keys["foreignlanguage"].used;
1938 found._tokensize = pos1 - found._tokenstart;
1939 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1942 // Swallow possible optional params
1943 while (interval_.par[pos1] == '[') {
1944 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1946 // Swallow also the eventual parameter
1947 if (interval_.par[pos1] == '{') {
1948 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1951 found._dataEnd = pos1;
1953 found._dataStart = found._dataEnd;
1954 found._tokensize = count + found._dataEnd - pos;
1955 found.parenthesiscount = 0;
1956 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1957 found.disabled = true;
1961 // Handle "\end{...}"
1962 found._dataStart = pos + sub.str(2).length();
1963 found._dataEnd = found._dataStart;
1964 found._tokensize = count + found._dataEnd - pos;
1965 found.parenthesiscount = 0;
1966 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1967 found.disabled = true;
1971 else if (found.keytype != KeyInfo::isRegex) {
1972 found._tokenstart = sub.position(size_t(2));
1973 if (found.parenthesiscount == 0) {
1974 // Probably to be discarded
1975 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1976 char following = interval_.par[following_pos];
1977 if (following == ' ')
1978 found.head = "\\" + sub.str(5) + " ";
1979 else if (following == '=') {
1980 // like \uldepth=1000pt
1981 found.head = sub.str(2);
1984 found.head = "\\" + key;
1985 found._tokensize = found.head.length();
1986 found._dataEnd = found._tokenstart + found._tokensize;
1987 found._dataStart = found._dataEnd;
1990 int params = found._tokenstart + key.length() + 1;
1991 if (evaluatingOptional) {
1992 if (size_t(found._tokenstart) > optionalEnd) {
1993 evaluatingOptional = false;
1996 found.disabled = true;
1999 int optend = params;
2000 while (interval_.par[optend] == '[') {
2001 // discard optional parameters
2002 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2004 if (optend > params) {
2005 key += interval_.par.substr(params, optend-params);
2006 evaluatingOptional = true;
2007 optionalEnd = optend;
2008 if (found.keytype == KeyInfo::isSectioning) {
2009 // Remove optional values (but still keep in header)
2010 interval_.addIntervall(params, optend);
2013 string token = sub.str(7);
2015 if (interval_.par[optend] != '{') {
2017 found.parenthesiscount = 0;
2018 found.head = "\\" + key;
2021 closings = found.parenthesiscount;
2022 if (found.parenthesiscount == 1) {
2023 found.head = "\\" + key + "{";
2025 else if (found.parenthesiscount > 1) {
2027 found.head = sub.str(2) + "{";
2028 closings = found.parenthesiscount - 1;
2031 found.head = "\\" + key + "{";
2034 found._tokensize = found.head.length();
2035 found._dataStart = found._tokenstart + found.head.length();
2036 if (found.keytype == KeyInfo::doRemove) {
2038 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2039 if (endpar >= interval_.par.length())
2040 found._dataStart = interval_.par.length();
2042 found._dataStart = endpar;
2043 found._tokensize = found._dataStart - found._tokenstart;
2046 found._dataStart = found._tokenstart + found._tokensize;
2050 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2051 found._dataStart += 15;
2055 endpos = found._dataStart - 1;
2057 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2058 if (found.keytype == KeyInfo::isList) {
2059 // Check if it really is list env
2060 static regex const listre("^([a-z]+)$");
2062 if (!regex_match(token, sub2, listre)) {
2063 // Change the key of this entry. It is not in a list/item environment
2064 found.keytype = KeyInfo::endArguments;
2067 if (found.keytype == KeyInfo::noMain) {
2068 evaluatingCode = true;
2070 codeStart = found._dataStart;
2072 else if (evaluatingCode) {
2073 if (size_t(found._dataStart) > codeEnd)
2074 evaluatingCode = false;
2075 else if (found.keytype == KeyInfo::isMain) {
2076 // Disable this key, treate it as standard
2077 found.keytype = KeyInfo::isStandard;
2078 found.disabled = true;
2079 if ((codeEnd +1 >= interval_.par.length()) &&
2080 (found._tokenstart == codeStart)) {
2081 // trickery, because the code inset starts
2082 // with \selectlanguage ...
2084 if (entries_.size() > 1) {
2085 entries_[entries_.size()-1]._dataEnd = codeEnd;
2090 if ((endpos == interval_.par.length()) &&
2091 (found.keytype == KeyInfo::doRemove)) {
2092 // Missing closing => error in latex-input?
2093 // therefore do not delete remaining data
2094 found._dataStart -= 1;
2095 found._dataEnd = found._dataStart;
2098 found._dataEnd = endpos;
2100 if (isPatternString) {
2101 keys[key].used = true;
2104 entries_.push_back(found);
2108 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2110 stringstream s(keysstring);
2112 const char delim = '|';
2113 while (getline(s, key, delim)) {
2114 KeyInfo keyII(keyI);
2115 if (isPatternString) {
2118 else if ( !keys[key].used)
2119 keyII.disabled = true;
2124 void LatexInfo::buildKeys(bool isPatternString)
2127 static bool keysBuilt = false;
2128 if (keysBuilt && !isPatternString) return;
2130 // Keys to ignore in any case
2131 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2132 // Known standard keys with 1 parameter.
2133 // Split is done, if not at start of region
2134 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2135 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2136 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2137 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2138 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2139 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2141 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2142 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2143 makeKey("section*|subsection*|subsubsection*|paragraph*",
2144 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2145 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2146 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2148 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2150 // Split is done, if not at start of region
2151 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2152 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2154 // Split is done always.
2155 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2159 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2160 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2161 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2162 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2164 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2165 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2166 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2167 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2169 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2170 // Custom space/skip, remove the content (== length value)
2171 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2172 // Found in fr/UserGuide.lyx
2173 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2175 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2176 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2177 // Known macros to remove (including their parameter)
2179 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2180 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2181 // handle like standard keys with 1 parameter.
2182 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2184 // Ignore deleted text
2185 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2186 // but preserve added text
2187 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2189 // Macros to remove, but let the parameter survive
2191 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2193 // Remove language spec from content of these insets
2194 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2196 // Same effect as previous, parameter will survive (because there is no one anyway)
2198 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2199 // Remove table decorations
2200 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2201 // Discard shape-header.
2202 // For footnote or shortcut too, because of lang settings
2203 // and wrong handling if used 'KeyInfo::noMain'
2204 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2205 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2206 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2207 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2208 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2209 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2210 // like ('tiny{}' or '\tiny ' ... )
2211 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2213 // Survives, like known character
2214 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2215 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2216 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2218 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2219 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2220 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2222 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2223 // Remove RTL/LTR marker
2224 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2225 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2226 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2227 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2228 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2229 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2230 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2231 if (isPatternString) {
2232 // Allow the first searched string to rebuild the keys too
2236 // no need to rebuild again
2242 * Keep the list of actual opened parentheses actual
2243 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2245 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2248 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2252 if (c == '\\') skip = 1;
2253 else if (c == '{') {
2256 else if (c == '}') {
2257 handleCloseP(i, closingAllowed);
2263 string Intervall::show(int lastpos)
2265 int idx = 0; /* int intervalls */
2268 for (idx = 0; idx <= ignoreidx; idx++) {
2269 while (i < lastpos) {
2271 if (i <= borders[idx].low) {
2272 if (borders[idx].low > lastpos)
2273 printsize = lastpos - i;
2275 printsize = borders[idx].low - i;
2276 s += par.substr(i, printsize);
2278 if (i >= borders[idx].low)
2279 i = borders[idx].upper;
2282 i = borders[idx].upper;
2288 s += par.substr(i, lastpos-i);
2294 void Intervall::output(ostringstream &os, int lastpos)
2296 // get number of chars to output
2297 int idx = 0; /* int intervalls */
2300 string startTitle = titleValue;
2301 for (idx = 0; idx <= ignoreidx; idx++) {
2303 if (i <= borders[idx].low) {
2305 if (borders[idx].low > lastpos)
2306 printsize = lastpos - i;
2308 printsize = borders[idx].low - i;
2309 if (printsize > 0) {
2310 os << startTitle << par.substr(i, printsize);
2312 printed += printsize;
2315 handleParentheses(i, false);
2316 if (i >= borders[idx].low)
2317 i = borders[idx].upper;
2320 i = borders[idx].upper;
2327 os << startTitle << par.substr(i, lastpos-i);
2328 printed += lastpos-i;
2330 handleParentheses(lastpos, false);
2332 if (keys["foreignlanguage"].disabled)
2333 startindex = actualdeptindex-langcount;
2335 startindex = actualdeptindex;
2336 for (int i = startindex; i > 0; --i) {
2339 if (hasTitle && (printed > 0))
2341 if (! isPatternString_)
2343 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2346 void LatexInfo::processRegion(int start, int region_end)
2348 while (start < region_end) { /* Let {[} and {]} survive */
2349 int cnt = interval_.isOpeningPar(start);
2351 // Closing is allowed past the region
2352 int closing = interval_.findclosing(start+1, interval_.par.length());
2353 interval_.addIntervall(start, start+1);
2354 interval_.addIntervall(closing, closing+1);
2358 start = interval_.nextNotIgnored(start+1);
2362 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2364 if (actual.parenthesiscount == 0) {
2365 // "{\tiny{} ...}" ==> "{{} ...}"
2366 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2369 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2370 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2371 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2375 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2378 switch (actual.keytype)
2380 case KeyInfo::isTitle: {
2382 nextKeyIdx = getNextKey();
2385 case KeyInfo::cleanToStart: {
2386 actual._dataEnd = actual._dataStart;
2387 nextKeyIdx = getNextKey();
2388 // Search for end of arguments
2389 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2391 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2392 entries_[i].disabled = true;
2394 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2396 while (interval_.par[actual._dataEnd] == ' ')
2398 interval_.addIntervall(0, actual._dataEnd+1);
2399 interval_.actualdeptindex = 0;
2400 interval_.depts[0] = actual._dataEnd+1;
2401 interval_.closes[0] = -1;
2404 case KeyInfo::isText:
2405 interval_.par[actual._tokenstart] = '#';
2406 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2407 nextKeyIdx = getNextKey();
2409 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2410 if (actual.disabled)
2411 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2413 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2416 case KeyInfo::isChar: {
2417 nextKeyIdx = getNextKey();
2420 case KeyInfo::isSize: {
2421 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2422 if (actual.parenthesiscount == 0)
2423 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2425 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2427 nextKeyIdx = getNextKey();
2429 // Here _dataStart points to '{', so correct it
2430 actual._dataStart += 1;
2431 actual._tokensize += 1;
2432 actual.parenthesiscount = 1;
2433 if (interval_.par[actual._dataStart] == '}') {
2434 // Determine the end if used like '{\tiny{}...}'
2435 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2436 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2439 // Determine the end if used like '\tiny{...}'
2440 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2442 // Split on this key if not at start
2443 int start = interval_.nextNotIgnored(previousStart);
2444 if (start < actual._tokenstart) {
2445 interval_.output(os, actual._tokenstart);
2446 interval_.addIntervall(start, actual._tokenstart);
2448 // discard entry if at end of actual
2449 nextKeyIdx = process(os, actual);
2453 case KeyInfo::endArguments: {
2454 // Remove trailing '{}' too
2455 actual._dataStart += 1;
2456 actual._dataEnd += 1;
2457 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2458 nextKeyIdx = getNextKey();
2461 case KeyInfo::noMain:
2463 case KeyInfo::isStandard: {
2464 if (actual.disabled) {
2466 processRegion(actual._dataStart, actual._dataStart+1);
2467 nextKeyIdx = getNextKey();
2469 // Split on this key if not at datastart of calling entry
2470 int start = interval_.nextNotIgnored(previousStart);
2471 if (start < actual._tokenstart) {
2472 interval_.output(os, actual._tokenstart);
2473 interval_.addIntervall(start, actual._tokenstart);
2475 // discard entry if at end of actual
2476 nextKeyIdx = process(os, actual);
2480 case KeyInfo::removeWithArg: {
2481 nextKeyIdx = getNextKey();
2482 // Search for end of arguments
2483 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2485 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2486 entries_[i].disabled = true;
2488 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2490 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2493 case KeyInfo::doRemove: {
2494 // Remove the key with all parameters and following spaces
2497 if (interval_.par[actual._dataEnd-1] == ' ')
2498 start = actual._dataEnd;
2500 start = actual._dataEnd+1;
2501 for (pos = start; pos < interval_.par.length(); pos++) {
2502 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2505 // Remove also enclosing parentheses [] and {}
2508 while (actual._tokenstart > numpars) {
2509 if (pos+numpars >= interval_.par.size())
2511 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2513 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2519 if (interval_.par[pos+numpars] == ' ')
2523 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2524 nextKeyIdx = getNextKey();
2527 case KeyInfo::isList: {
2528 // Discard space before _tokenstart
2530 for (count = 0; count < actual._tokenstart; count++) {
2531 if (interval_.par[actual._tokenstart-count-1] != ' ')
2534 nextKeyIdx = getNextKey();
2535 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2537 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2539 // How else can we catch this one?
2540 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2541 entries_[i].disabled = true;
2543 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2545 else if (nextKeyIdx > 0) {
2546 // Ignore any lang entries inside data region
2547 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2548 if (entries_[i].keytype == KeyInfo::isMain)
2549 entries_[i].disabled = true;
2552 if (actual.disabled) {
2553 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2556 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2558 if (interval_.par[actual._dataEnd+1] == '[') {
2559 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2560 if ((interval_.par[actual._dataEnd+2] == '{') &&
2561 (interval_.par[posdown-1] == '}')) {
2562 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2563 interval_.addIntervall(posdown-1, posdown+1);
2566 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2567 interval_.addIntervall(posdown, posdown+1);
2569 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2570 if (blk > posdown) {
2571 // Discard at most 1 space after empty item
2573 for (count = 0; count < 1; count++) {
2574 if (interval_.par[blk+count] != ' ')
2578 interval_.addIntervall(blk, blk+count);
2583 case KeyInfo::isSectioning: {
2584 // Discard spaces before _tokenstart
2586 int val = actual._tokenstart;
2587 for (count = 0; count < actual._tokenstart;) {
2588 val = interval_.previousNotIgnored(val-1);
2589 if (val < 0 || interval_.par[val] != ' ')
2592 count = actual._tokenstart - val;
2595 if (actual.disabled) {
2596 removeHead(actual, count);
2597 nextKeyIdx = getNextKey();
2599 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2600 nextKeyIdx = process(os, actual);
2604 case KeyInfo::isMath: {
2605 // Same as regex, use the content unchanged
2606 nextKeyIdx = getNextKey();
2609 case KeyInfo::isRegex: {
2610 // DO NOT SPLIT ON REGEX
2612 nextKeyIdx = getNextKey();
2615 case KeyInfo::isIgnored: {
2616 // Treat like a character for now
2617 nextKeyIdx = getNextKey();
2620 case KeyInfo::isMain: {
2621 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2622 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2623 if (actual._tokenstart > 0) {
2624 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2625 if ((prev >= 0) && interval_.par[prev] == '%')
2626 interval_.addIntervall(prev, prev+1);
2628 if (actual.disabled) {
2630 interval_.langcount++;
2631 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2632 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2633 // Discard also the space before math-equation
2634 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2636 nextKeyIdx = getNextKey();
2637 // interval.resetOpenedP(actual._dataStart-1);
2640 if (actual._tokenstart < 26) {
2641 // for the first (and maybe dummy) language
2642 interval_.setForDefaultLang(actual);
2644 interval_.resetOpenedP(actual._dataStart-1);
2648 case KeyInfo::invalid:
2649 case KeyInfo::headRemove:
2650 // These two cases cannot happen, already handled
2653 // LYXERR(Debug::INFO, "Unhandled keytype");
2654 nextKeyIdx = getNextKey();
2661 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2663 int end = interval_.nextNotIgnored(actual._dataEnd);
2664 int oldStart = actual._dataStart;
2665 int nextKeyIdx = getNextKey();
2667 if ((nextKeyIdx < 0) ||
2668 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2669 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2670 if (oldStart <= end) {
2671 processRegion(oldStart, end);
2676 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2678 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2679 (void) dispatch(os, actual._dataStart, nextKey);
2680 end = nextKey._tokenstart;
2683 processRegion(oldStart, nextKey._tokenstart);
2684 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2686 oldStart = nextKey._dataEnd+1;
2688 // now nextKey is either invalid or is outside of actual._dataEnd
2689 // output the remaining and discard myself
2690 if (oldStart <= end) {
2691 processRegion(oldStart, end);
2693 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2695 // This is the normal case.
2696 // But if using the firstlanguage, the closing may be missing
2698 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2700 if (actual._dataEnd < end)
2701 output_end = interval_.nextNotIgnored(actual._dataEnd);
2702 else if (interval_.par.size() > (size_t) end)
2703 output_end = interval_.nextNotIgnored(end);
2705 output_end = interval_.par.size();
2706 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2707 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2709 // Remove possible empty data
2710 int dstart = interval_.nextNotIgnored(actual._dataStart);
2711 while (interval_.isOpeningPar(dstart) == 1) {
2712 interval_.addIntervall(dstart, dstart+1);
2713 int dend = interval_.findclosing(dstart+1, output_end);
2714 interval_.addIntervall(dend, dend+1);
2715 dstart = interval_.nextNotIgnored(dstart+1);
2717 if (dstart < output_end)
2718 interval_.output(os, output_end);
2720 interval_.addIntervall(0, end);
2722 interval_.addIntervall(actual._tokenstart, end);
2726 string splitOnKnownMacros(string par, bool isPatternString)
2729 LatexInfo li(par, isPatternString);
2730 // LYXERR(Debug::INFO, "Berfore split: " << par);
2731 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2733 DummyKey._tokensize = 0;
2734 DummyKey._dataStart = 0;
2735 DummyKey._dataEnd = par.length();
2736 DummyKey.disabled = true;
2737 int firstkeyIdx = li.getFirstKey();
2739 if (firstkeyIdx >= 0) {
2740 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2741 DummyKey._tokenstart = firstKey._tokenstart;
2743 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2744 // Use dummy firstKey
2745 firstKey = DummyKey;
2746 (void) li.setNextKey(firstkeyIdx);
2749 if (par.substr(firstKey._dataStart, 2) == "% ")
2750 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2752 nextkeyIdx = li.process(os, firstKey);
2753 while (nextkeyIdx >= 0) {
2754 // Check for a possible gap between the last
2755 // entry and this one
2756 int datastart = li.nextNotIgnored(firstKey._dataStart);
2757 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2758 if ((nextKey._tokenstart > datastart)) {
2760 firstKey._dataStart = datastart;
2761 firstKey._dataEnd = par.length();
2762 (void) li.setNextKey(nextkeyIdx);
2763 // Fake the last opened parenthesis
2764 li.setForDefaultLang(firstKey);
2765 nextkeyIdx = li.process(os, firstKey);
2768 if (nextKey.keytype != KeyInfo::isMain) {
2769 firstKey._dataStart = datastart;
2770 firstKey._dataEnd = nextKey._dataEnd+1;
2771 (void) li.setNextKey(nextkeyIdx);
2772 li.setForDefaultLang(firstKey);
2773 nextkeyIdx = li.process(os, firstKey);
2776 nextkeyIdx = li.process(os, nextKey);
2780 // Handle the remaining
2781 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2782 firstKey._dataEnd = par.length();
2784 if ((firstKey._dataStart < firstKey._dataEnd) &&
2785 (par[firstKey._dataStart] != '}')) {
2786 li.setForDefaultLang(firstKey);
2787 (void) li.process(os, firstKey);
2791 // return string definitelly impossible to match
2792 s = "\\foreignlanguage{ignore}{ }";
2796 s = par; /* no known macros found */
2797 // LYXERR(Debug::INFO, "After split: " << s);
2802 * Try to unify the language specs in the latexified text.
2803 * Resulting modified string is set to "", if
2804 * the searched tex does not contain all the features in the search pattern
2806 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2808 static Features regex_f;
2809 static int missed = 0;
2810 static bool regex_with_format = false;
2812 int parlen = par.length();
2814 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2817 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2818 // Happens to be there in case of description or labeling environment
2823 // Split the latex input into pieces which
2824 // can be digested by our search engine
2825 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2826 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2827 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2828 string doclang = pbuf->params().language->polyglossia();
2829 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2831 bool toIgnoreLang = true;
2832 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2834 if (sub.str(2) != doclang) {
2835 toIgnoreLang = false;
2839 setIgnoreFormat("language", toIgnoreLang);
2842 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2843 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2846 result = par.substr(0, parlen);
2847 if (isPatternString) {
2850 regex_f = identifyFeatures(result);
2851 string features = "";
2852 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2853 string a = it->first;
2854 regex_with_format = true;
2855 features += " " + a;
2856 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2858 LYXERR(Debug::FIND, "Identified Features" << features);
2861 } else if (regex_with_format) {
2862 Features info = identifyFeatures(result);
2863 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2864 string a = it->first;
2865 bool b = it->second;
2866 if (b && ! info[a]) {
2868 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2875 // LYXERR(Debug::INFO, "No regex formats");
2881 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2882 static int identifyClosing(string & t)
2884 int open_braces = 0;
2886 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2887 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2889 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2891 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2893 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2902 static int num_replaced = 0;
2903 static bool previous_single_replace = true;
2905 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2908 // Handle \w properly
2909 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2910 if (! opt.casesensitive) {
2911 popts |= QRegularExpression::CaseInsensitiveOption;
2913 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2914 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2916 if (regexp.isValid() && regexp2.isValid()) {
2917 regexIsValid = true;
2918 // Check '{', '}' pairs inside the regex
2921 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2922 char c = par_as_string[i];
2929 else if (c == '}') {
2936 if (balanced != 0) {
2937 regexIsValid = false;
2938 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2942 regexIsValid = false;
2943 if (!regexp.isValid())
2944 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2946 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2949 if (opt.casesensitive) {
2950 regexp = regex(regexp_str);
2951 regexp2 = regex(regexp2_str);
2954 regexp = regex(regexp_str, std::regex_constants::icase);
2955 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2960 static void modifyRegexForMatchWord(string &t)
2963 regex wordre("(\\\\)*((\\.|\\\\b))");
2966 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2968 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2971 else if (sub.str(2) == "\\\\b")
2973 if (lastpos < (size_t) sub.position(2))
2974 s += t.substr(lastpos, sub.position(2) - lastpos);
2976 lastpos = sub.position(2) + sub.length(2);
2979 s = "\\b" + t + "\\b";
2983 else if (lastpos < t.length())
2984 s += t.substr(lastpos, t.length() - lastpos);
2985 t = "\\b" + s + "\\b";
2988 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
2989 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2991 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2992 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2993 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2994 if (opt.replace_all && previous_single_replace) {
2995 previous_single_replace = false;
2998 else if (!opt.replace_all) {
2999 num_replaced = 0; // count number of replaced strings
3000 previous_single_replace = true;
3002 // When using regexp, braces are hacked already by escape_for_regex()
3003 par_as_string = normalize(ds);
3005 close_wildcards = 0;
3007 size_t lead_size = 0;
3008 // correct the language settings
3009 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3010 opt.matchAtStart = false;
3012 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3013 if (opt.ignoreformat) {
3017 lead_size = identifyLeading(par_as_string);
3019 lead_as_string = par_as_string.substr(0, lead_size);
3020 string lead_as_regex_string = string2regex(lead_as_string);
3021 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3022 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3023 /* Handle whole words too in this case
3025 if (opt.matchword) {
3026 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3027 opt.matchword = false;
3029 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3030 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3031 CreateRegexp(opt, regexp_str, regexp2_str);
3033 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3034 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3038 if (!opt.ignoreformat) {
3039 lead_size = identifyLeading(par_as_string);
3040 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3041 lead_as_string = par_as_string.substr(0, lead_size);
3042 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3045 // Here we are using regexp
3046 LASSERT(use_regexp, /**/);
3048 string lead_as_regexp;
3049 if (lead_size > 0) {
3050 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3051 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3052 par_as_string = par_as_string_nolead;
3053 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3054 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3056 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3057 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3058 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3059 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3061 size_t lng = par_as_string.size();
3062 if (!opt.ignoreformat) {
3063 // Remove extra '\}' at end if not part of \{\.\}
3065 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3067 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3076 if (lng < par_as_string.size())
3077 par_as_string = par_as_string.substr(0,lng);
3079 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3080 if ((lng > 0) && (par_as_string[0] == '^')) {
3081 par_as_string = par_as_string.substr(1);
3083 opt.matchAtStart = true;
3085 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3086 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3087 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3089 // If entered regexp must match at begin of searched string buffer
3090 // Kornel: Added parentheses to use $1 for size of the leading string
3094 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3095 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3096 // so the convert has no effect in that case
3097 for (int i = 7; i > 0; --i) {
3098 string orig = "\\\\" + std::to_string(i);
3099 string dest = "\\" + std::to_string(i+2);
3100 while (regex_replace(par_as_string, par_as_string, orig, dest));
3102 if (opt.matchword) {
3103 modifyRegexForMatchWord(par_as_string);
3104 opt.matchword = false;
3106 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3107 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3109 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3110 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3111 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3115 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3119 mres.searched_size = len;
3121 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3124 docstring docstr = stringifyFromForSearch(opt, cur, len);
3126 str = normalize(docstr);
3127 if (!opt.ignoreformat) {
3128 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3129 // remove closing '}' and '\n' to allow for use of '$' in regex
3130 size_t lng = str.size();
3131 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3133 if (lng != str.size()) {
3134 str = str.substr(0, lng);
3138 mres.match_len = -1;
3141 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3143 LASSERT(use_regexp, /**/);
3145 // use_regexp always true
3146 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3148 QString qstr = QString::fromStdString(str);
3149 QRegularExpression const *p_regexp;
3150 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3154 p_regexp = ®exp2;
3156 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3157 if (!match.hasMatch())
3160 regex const *p_regexp;
3161 regex_constants::match_flag_type flags;
3163 flags = regex_constants::match_continuous;
3166 flags = regex_constants::match_default;
3167 p_regexp = ®exp2;
3169 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3170 if (re_it == sregex_iterator())
3172 match_results<string::const_iterator> const & m = *re_it;
3174 // Whole found string, including the leading
3175 // std: m[0].second - m[0].first
3176 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3178 // Size of the leading string
3179 // std: m[1].second - m[1].first
3180 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3181 int leadingsize = 0;
3183 if (match.lastCapturedIndex() > 0) {
3184 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3189 leadingsize = m[1].second - m[1].first;
3193 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3194 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3195 // because of different number of closing at end of string
3196 // we have to 'unify' the length of the post-match.
3197 // Done by ignoring closing parenthesis and linefeeds at string end
3198 int matchend = match.capturedEnd(0);
3199 size_t strsize = qstr.size();
3200 if (!opt.ignoreformat) {
3201 while (mres.match_len > 0) {
3202 QChar c = qstr.at(matchend - 1);
3203 if ((c == '\n') || (c == '}') || (c == '{')) {
3210 while (strsize > (size_t) match.capturedEnd(0)) {
3211 QChar c = qstr.at(strsize-1);
3212 if ((c == '\n') || (c == '}')) {
3219 // LYXERR0(qstr.toStdString());
3220 mres.match2end = strsize - matchend;
3221 mres.pos = match.capturedStart(2);
3223 mres.match_prefix = m[2].second - m[2].first;
3224 mres.match_len = m[0].second - m[2].second;
3225 // ignore closing parenthesis and linefeeds at string end
3226 size_t strend = m[0].second - m[0].first;
3227 int matchend = strend;
3228 size_t strsize = str.size();
3229 if (!opt.ignoreformat) {
3230 while (mres.match_len > 0) {
3231 char c = str.at(matchend - 1);
3232 if ((c == '\n') || (c == '}') || (c == '{')) {
3239 while (strsize > strend) {
3240 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3248 mres.match2end = strsize - matchend;
3249 mres.pos = m[2].first - m[0].first;;
3251 if (mres.match2end < 0)
3253 mres.leadsize = leadingsize;
3255 if (mres.match_len > 0) {
3256 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3257 mres.result.push_back(a0);
3258 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3259 mres.result.push_back(match.captured(i).toStdString());
3263 if (mres.match_len > 0) {
3264 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3265 mres.result.push_back(a0);
3266 for (size_t i = 3; i < m.size(); i++) {
3267 mres.result.push_back(m[i]);
3276 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3278 MatchResult mres = findAux(cur, len, at_begin);
3279 int res = mres.match_len;
3281 "res=" << res << ", at_begin=" << at_begin
3282 << ", matchAtStart=" << opt.matchAtStart
3283 << ", inTexted=" << cur.inTexted());
3284 if (opt.matchAtStart) {
3287 else if (mres.match_prefix > 0)
3296 static bool simple_replace(string &t, string from, string to)
3298 regex repl("(\\\\)*(" + from + ")");
3302 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3304 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3306 if (lastpos < (size_t) sub.position(2))
3307 s += t.substr(lastpos, sub.position(2) - lastpos);
3309 lastpos = sub.position(2) + sub.length(2);
3313 else if (lastpos < t.length())
3314 s += t.substr(lastpos, t.length() - lastpos);
3320 string MatchStringAdv::normalize(docstring const & s) const
3323 t = lyx::to_utf8(s);
3324 // Remove \n at begin
3325 while (!t.empty() && t[0] == '\n')
3328 while (!t.empty() && t[t.size() - 1] == '\n')
3329 t = t.substr(0, t.size() - 1);
3331 // Handle all other '\n'
3332 while ((pos = t.find("\n")) != string::npos) {
3333 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3335 if (isAlnumASCII(t[pos+1])) {
3336 t.replace(pos-2, 3, " ");
3339 t.replace(pos-2, 3, "");
3342 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3343 // '\n' adjacent to non-alpha-numerics, discard
3344 t.replace(pos, 1, "");
3347 // Replace all other \n with spaces
3348 t.replace(pos, 1, " ");
3351 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3352 // Kornel: Added textsl, textsf, textit, texttt and noun
3353 // + allow to seach for colored text too
3354 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3355 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3356 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3357 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3358 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3359 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3365 docstring stringifyFromCursor(DocIterator const & cur, int len)
3367 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3368 if (cur.inTexted()) {
3369 Paragraph const & par = cur.paragraph();
3370 // TODO what about searching beyond/across paragraph breaks ?
3371 // TODO Try adding a AS_STR_INSERTS as last arg
3372 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3373 int(par.size()) : cur.pos() + len;
3374 // OutputParams runparams(&cur.buffer()->params().encoding());
3375 OutputParams runparams(encodings.fromLyXName("utf8"));
3376 runparams.nice = true;
3377 runparams.flavor = Flavor::XeTeX;
3378 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3379 // No side effect of file copying and image conversion
3380 runparams.dryrun = true;
3381 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3382 if (ignoreFormats.getDeleted()) {
3383 option |= AS_STR_SKIPDELETE;
3384 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3387 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3389 LYXERR(Debug::FIND, "Stringifying with cur: "
3390 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3391 return par.asString(cur.pos(), end,
3394 } else if (cur.inMathed()) {
3395 CursorSlice cs = cur.top();
3396 MathData md = cs.cell();
3397 MathData::const_iterator it_end =
3398 (( len == -1 || cs.pos() + len > int(md.size()))
3400 : md.begin() + cs.pos() + len );
3402 for (MathData::const_iterator it = md.begin() + cs.pos();
3405 docstring s = asString(md2);
3406 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3409 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3414 /** Computes the LaTeX export of buf starting from cur and ending len positions
3415 * after cur, if len is positive, or at the paragraph or innermost inset end
3418 docstring latexifyFromCursor(DocIterator const & cur, int len)
3421 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3422 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3423 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3425 Buffer const & buf = *cur.buffer();
3427 odocstringstream ods;
3429 //OutputParams runparams(&buf.params().encoding());
3430 OutputParams runparams(encodings.fromLyXName("utf8"));
3431 runparams.nice = false;
3432 runparams.flavor = Flavor::XeTeX;
3433 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3434 // No side effect of file copying and image conversion
3435 runparams.dryrun = true;
3436 if (ignoreFormats.getDeleted()) {
3437 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3440 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3443 if (cur.inTexted()) {
3444 // @TODO what about searching beyond/across paragraph breaks ?
3445 pos_type endpos = cur.paragraph().size();
3446 if (len != -1 && endpos > cur.pos() + len)
3447 endpos = cur.pos() + len;
3448 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3449 string(), cur.pos(), endpos);
3450 string s = lyx::to_utf8(ods.str());
3451 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3452 return(lyx::from_utf8(s));
3453 } else if (cur.inMathed()) {
3454 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3455 for (int s = cur.depth() - 1; s >= 0; --s) {
3456 CursorSlice const & cs = cur[s];
3457 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3458 TeXMathStream ws(os);
3459 cs.asInsetMath()->asHullInset()->header_write(ws);
3464 CursorSlice const & cs = cur.top();
3465 MathData md = cs.cell();
3466 MathData::const_iterator it_end =
3467 ((len == -1 || cs.pos() + len > int(md.size()))
3469 : md.begin() + cs.pos() + len);
3471 for (MathData::const_iterator it = md.begin() + cs.pos();
3475 ods << asString(md2);
3476 // Retrieve the math environment type, and add '$' or '$]'
3477 // or others (\end{equation}) accordingly
3478 for (int s = cur.depth() - 1; s >= 0; --s) {
3479 CursorSlice const & cs2 = cur[s];
3480 InsetMath * inset = cs2.asInsetMath();
3481 if (inset && inset->asHullInset()) {
3482 TeXMathStream ws(os);
3483 inset->asHullInset()->footer_write(ws);
3487 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3489 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3494 #if defined(ResultsDebug)
3496 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3498 LYXERR0( "from:\t\t\t" << from);
3500 if (mres.pos_len > 0) {
3502 status = "FINALSEARCH";
3505 if (mres.match_len > 0) {
3506 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3507 status = "Good Match";
3509 status = "Matched in";
3512 status = "MissedSearch";
3515 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3516 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3517 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3518 if ((mres.pos > 0) || (mres.match_prefix > 0))
3519 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3520 for (size_t i = 0; i < mres.result.size(); i++)
3521 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3523 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3525 #define displayMres(s, txt, cur)
3528 /** Finalize an advanced find operation, advancing the cursor to the innermost
3529 ** position that matches, plus computing the length of the matching text to
3531 ** Return the cur.pos() difference between start and end of found match
3533 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3535 // Search the foremost position that matches (avoids find of entire math
3536 // inset when match at start of it)
3537 DocIterator old_cur(cur.buffer());
3539 static MatchResult fail = MatchResult();
3540 MatchResult max_match;
3541 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3542 // Happens with e.g. hyperlinks
3543 // either one sees "http://www.bla.bla" or nothing
3544 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3545 // and although we search for only 3 chars, we find the whole hyperlink inset
3546 bool at_begin = (expected.match_prefix == 0);
3547 if (!match.opt.forward && match.opt.ignoreformat) {
3548 if (expected.pos > 0)
3551 LASSERT(at_begin, /**/);
3552 if (expected.match_len > 0 && at_begin) {
3553 // Search for deepest match
3555 max_match = expected;
3557 size_t d = cur.depth();
3561 if (cur.depth() < d)
3563 if (cur.depth() == d)
3566 while (cur && cur.depth() > lastd) {
3567 lastd = cur.depth();
3568 mres = match(cur, -1, at_begin);
3569 displayMres(mres, "Checking innermost", cur);
3570 if (mres.match_len > 0)
3575 if (mres.match_len < expected.match_len)
3583 // (expected.match_len <= 0)
3584 mres = match(cur); /* match valid only if not searching whole words */
3585 displayMres(mres, "Start with negative match", cur);
3588 if (max_match.match_len <= 0) return fail;
3589 LYXERR(Debug::FIND, "Ok");
3591 // Compute the match length
3593 if (cur.pos() + len > cur.lastpos())
3596 LASSERT(match.use_regexp, /**/);
3599 int maxl = cur.lastpos() - cur.pos();
3600 // Greedy behaviour while matching regexps
3601 while (maxl > minl) {
3603 mres2 = match(cur, len, at_begin);
3604 displayMres(mres2, "Finalize loop", cur);
3605 int actual_match_len = mres2.match_len;
3606 if (actual_match_len >= max_match.match_len) {
3607 // actual_match_len > max_match _can_ happen,
3608 // if the search area splits
3609 // some following word so that the regex
3610 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3612 // This means, the len value is too big
3613 actual_match_len = max_match.match_len;
3615 max_match.match_len = actual_match_len;
3617 if (maxl - minl < 4)
3618 len = (int)((maxl + minl)/2);
3620 len = (int)(minl + (maxl - minl + 3)/4);
3623 // (actual_match_len < max_match.match_len)
3625 len = (int)((maxl + minl)/2);
3630 // Search for real start of matched characters
3632 MatchResult actual_match;
3635 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3636 if (cur.depth() < old_cur.depth()) {
3638 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3641 if (cur.pos() != old_cur.pos()) {
3642 // OK, forwarded 1 pos in actual inset
3643 actual_match = match(cur, len-1, at_begin);
3644 if (actual_match.match_len == max_match.match_len) {
3645 // Ha, got it! The shorter selection has the same match length
3648 max_match = actual_match;
3651 // OK, the shorter selection matches less chars, revert to previous value
3657 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3658 actual_match = match(cur, len, at_begin);
3659 if (actual_match.match_len == max_match.match_len) {
3661 max_match = actual_match;
3668 max_match.pos_len = len;
3669 displayMres(max_match, "SEARCH RESULT", cur)
3676 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3680 bool repeat = false;
3681 DocIterator orig_cur; // to be used if repeat not successful
3682 MatchResult orig_mres;
3683 while (!theApp()->longOperationCancelled() && cur) {
3684 //(void) findAdvForwardInnermost(cur);
3685 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3686 MatchResult mres = match(cur, -1, false);
3687 string msg = "Starting";
3690 displayMres(mres, msg + " findForwardAdv", cur)
3691 int match_len = mres.match_len;
3692 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3693 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3696 if (match_len <= 0) {
3697 // This should exit nested insets, if any, or otherwise undefine the currsor.
3698 cur.pos() = cur.lastpos();
3699 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3702 else { // match_len > 0
3703 // Try to find the begin of searched string
3705 int firstInvalid = cur.lastpos() - cur.pos();
3707 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3708 int incrcur = (firstInvalid + 1 )*3/4;
3709 if (incrcur < incrmatch)
3710 increment = incrcur;
3712 increment = incrmatch;
3716 LYXERR(Debug::FIND, "Set increment to " << increment);
3717 while (increment > 0) {
3718 DocIterator old_cur = cur;
3719 if (cur.pos() + increment >= cur.lastpos()) {
3723 cur.pos() = cur.pos() + increment;
3724 MatchResult mres2 = match(cur, -1, false);
3725 displayMres(mres2, "findForwardAdv loop", cur)
3726 switch (interpretMatch(mres, mres2)) {
3727 case MatchResult::newIsTooFar:
3728 // behind the expected match
3729 firstInvalid = increment;
3733 case MatchResult::newIsBetter:
3734 // not reached yet, but cur.pos()+increment is bettert
3736 firstInvalid -= increment;
3737 if (increment > firstInvalid*3/4)
3738 increment = firstInvalid*3/4;
3739 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3740 if (increment >= mres2.match_prefix)
3741 increment = (mres2.match_prefix+1)*3/4;
3746 // Handle not like MatchResult::newIsTooFar
3747 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3749 increment = increment*3/4;
3754 if (mres.match_len > 0) {
3755 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3756 // The match seems to indicate some deeper level
3765 // should never be reached.
3769 // LYXERR0("Leaving first loop");
3770 LYXERR(Debug::FIND, "Finalizing 1");
3771 MatchResult found_match = findAdvFinalize(cur, match, mres);
3772 if (found_match.match_len > 0) {
3773 LASSERT(found_match.pos_len > 0, /**/);
3774 match.FillResults(found_match);
3775 return found_match.pos_len;
3778 // try next possible match
3789 /// Find the most backward consecutive match within same paragraph while searching backwards.
3790 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3792 DocIterator cur_begin = cur;
3793 cur_begin.pos() = 0;
3794 DocIterator tmp_cur = cur;
3795 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3796 Inset & inset = cur.inset();
3797 for (; cur != cur_begin; cur.backwardPos()) {
3798 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3799 DocIterator new_cur = cur;
3800 new_cur.backwardPos();
3801 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3803 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3804 if (new_mr.match_len == mr.match_len)
3808 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3814 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3818 // Backup of original position
3819 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3820 if (cur == cur_begin)
3823 DocIterator cur_orig(cur);
3824 bool pit_changed = false;
3827 MatchResult found_match = match(cur, -1, false);
3829 if (found_match.match_len > 0) {
3831 cur.pos() = cur.lastpos();
3833 cur.pos() = cur_orig.pos();
3834 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3835 DocIterator cur_prev_iter;
3837 found_match = match(cur);
3838 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3839 << (found_match.match_len > 0) << ", cur: " << cur);
3840 if (found_match.match_len > 0) {
3841 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3842 if (found_mr.pos_len > 0) {
3843 match.FillResults(found_mr);
3844 return found_mr.pos_len;
3848 // Stop if begin of document reached
3849 if (cur == cur_begin)
3851 cur_prev_iter = cur;
3855 if (cur == cur_begin)
3862 } while (!theApp()->longOperationCancelled());
3870 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3871 DocIterator const & cur, int len)
3873 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3875 if (!opt.ignoreformat)
3876 return latexifyFromCursor(cur, len);
3878 return stringifyFromCursor(cur, len);
3882 FindAndReplaceOptions::FindAndReplaceOptions(
3883 docstring const & _find_buf_name, bool _casesensitive,
3884 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3885 docstring const & _repl_buf_name, bool _keep_case,
3886 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3887 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3888 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3889 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3897 /** Check if 'len' letters following cursor are all non-lowercase */
3898 static bool allNonLowercase(Cursor const & cur, int len)
3900 pos_type beg_pos = cur.selectionBegin().pos();
3901 pos_type end_pos = cur.selectionBegin().pos() + len;
3902 if (len > cur.lastpos() + 1 - beg_pos) {
3903 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3904 len = cur.lastpos() + 1 - beg_pos;
3905 end_pos = beg_pos + len;
3907 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3908 if (isLowerCase(cur.paragraph().getChar(pos)))
3914 /** Check if first letter is upper case and second one is lower case */
3915 static bool firstUppercase(Cursor const & cur)
3918 pos_type pos = cur.selectionBegin().pos();
3919 if (pos >= cur.lastpos() - 1) {
3920 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3923 ch1 = cur.paragraph().getChar(pos);
3924 ch2 = cur.paragraph().getChar(pos + 1);
3925 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3926 LYXERR(Debug::FIND, "firstUppercase(): "
3927 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3928 << ch2 << "(" << char(ch2) << ")"
3929 << ", result=" << result << ", cur=" << cur);
3934 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3936 ** \fixme What to do with possible further paragraphs in replace buffer ?
3938 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3940 ParagraphList::iterator pit = buffer.paragraphs().begin();
3941 LASSERT(!pit->empty(), /**/);
3942 pos_type right = pos_type(1);
3943 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3944 right = pit->size();
3945 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3949 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3951 // Should replace the string "$" + std::to_string(matchnum) with replacement
3952 // if the char '$' is not prefixed with odd number of char '\\'
3953 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3957 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3959 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3961 int num = stoi(sub.str(3), nullptr, 10);
3962 if (num >= maxmatchnum)
3964 if (lastpos < (size_t) sub.position(2))
3965 s += t.substr(lastpos, sub.position(2) - lastpos);
3966 s += replacements[num];
3967 lastpos = sub.position(2) + sub.length(2);
3971 else if (lastpos < t.length())
3972 s += t.substr(lastpos, t.length() - lastpos);
3978 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3980 Cursor & cur = bv->cursor();
3981 if (opt.repl_buf_name.empty()
3982 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3983 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3986 DocIterator sel_beg = cur.selectionBegin();
3987 DocIterator sel_end = cur.selectionEnd();
3988 if (&sel_beg.inset() != &sel_end.inset()
3989 || sel_beg.pit() != sel_end.pit()
3990 || sel_beg.idx() != sel_end.idx())
3992 int sel_len = sel_end.pos() - sel_beg.pos();
3993 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3994 << ", sel_len: " << sel_len << endl);
3997 LASSERT(sel_len > 0, return 0);
3999 if (!matchAdv(sel_beg, sel_len).match_len)
4002 // Build a copy of the replace buffer, adapted to the KeepCase option
4003 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4005 repl_buffer_orig.write(oss);
4006 string lyx = oss.str();
4007 if (matchAdv.valid_matches > 0) {
4008 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4010 Buffer repl_buffer("", false);
4011 repl_buffer.setUnnamed(true);
4012 LASSERT(repl_buffer.readString(lyx), return 0);
4013 if (opt.keep_case && sel_len >= 2) {
4014 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4015 if (cur.inTexted()) {
4016 if (firstUppercase(cur))
4017 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4018 else if (allNonLowercase(cur, sel_len))
4019 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4022 cap::cutSelection(cur, false);
4023 if (cur.inTexted()) {
4024 repl_buffer.changeLanguage(
4025 repl_buffer.language(),
4026 cur.getFont().language());
4027 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4028 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4029 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4030 repl_buffer.params().documentClassPtr(),
4031 repl_buffer.params().authors(),
4032 bv->buffer().errorList("Paste"));
4033 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4034 sel_len = repl_buffer.paragraphs().begin()->size();
4035 } else if (cur.inMathed()) {
4036 odocstringstream ods;
4038 // OutputParams runparams(&repl_buffer.params().encoding());
4039 OutputParams runparams(encodings.fromLyXName("utf8"));
4040 runparams.nice = false;
4041 runparams.flavor = Flavor::XeTeX;
4042 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4043 runparams.dryrun = true;
4044 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4045 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4046 docstring repl_latex = ods.str();
4047 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4049 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4050 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4051 repl_latex = from_utf8(s);
4052 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4053 MathData ar(cur.buffer());
4054 asArray(repl_latex, ar, Parse::NORMAL);
4056 sel_len = ar.size();
4057 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4059 if (cur.pos() >= sel_len)
4060 cur.pos() -= sel_len;
4063 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4064 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4065 bv->processUpdateFlags(Update::Force);
4070 /// Perform a FindAdv operation.
4071 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4076 // e.g., when invoking word-findadv from mini-buffer wither with
4077 // wrong options syntax or before ever opening advanced F&R pane
4078 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4082 MatchStringAdv matchAdv(bv->buffer(), opt);
4084 if (!matchAdv.regexIsValid) {
4085 bv->message(lyx::from_utf8(matchAdv.regexError));
4089 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4091 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4092 num_replaced += findAdvReplace(bv, opt, matchAdv);
4095 pos_len = findForwardAdv(cur, matchAdv);
4097 pos_len = findBackwardsAdv(cur, matchAdv);
4098 } catch (exception & ex) {
4099 bv->message(from_utf8(ex.what()));
4104 if (num_replaced > 0) {
4105 switch (num_replaced)
4108 bv->message(_("One match has been replaced."));
4111 bv->message(_("Two matches have been replaced."));
4114 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4120 bv->message(_("Match not found."));
4125 if (num_replaced > 0)
4126 bv->message(_("Match has been replaced."));
4128 bv->message(_("Match found."));
4130 if (cur.pos() + pos_len > cur.lastpos()) {
4131 // Prevent crash in bv->putSelectionAt()
4132 // Should never happen, maybe LASSERT() here?
4133 pos_len = cur.lastpos() - cur.pos();
4135 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4136 bv->putSelectionAt(cur, pos_len, !opt.forward);
4142 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4144 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4145 << opt.casesensitive << ' '
4146 << opt.matchword << ' '
4147 << opt.forward << ' '
4148 << opt.expandmacros << ' '
4149 << opt.ignoreformat << ' '
4150 << opt.replace_all << ' '
4151 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4152 << opt.keep_case << ' '
4153 << int(opt.scope) << ' '
4156 LYXERR(Debug::FIND, "built: " << os.str());
4162 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4164 // LYXERR(Debug::FIND, "parsing");
4168 while (line != "EOSS") {
4172 if (is.eof()) // Tolerate malformed request
4176 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4177 opt.find_buf_name = from_utf8(s);
4178 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4179 is.get(); // Waste space before replace string
4182 while (line != "EOSS") {
4186 if (is.eof()) // Tolerate malformed request
4190 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4191 opt.repl_buf_name = from_utf8(s);
4192 is >> opt.keep_case;
4195 opt.scope = FindAndReplaceOptions::SearchScope(i);
4197 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4200 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4201 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4202 << opt.scope << ' ' << opt.restr);