3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathData.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/FileName.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
53 #include <unordered_map>
56 //#define ResultsDebug
57 #define USE_QT_FOR_SEARCH
58 #if defined(USE_QT_FOR_SEARCH)
59 #include <QtCore> // sets QT_VERSION
60 #if (QT_VERSION >= 0x050000)
61 #include <QRegularExpression>
71 using namespace lyx::support;
75 typedef unordered_map<string, string> AccentsMap;
76 typedef unordered_map<string,string>::const_iterator AccentsIterator;
77 static AccentsMap accents = unordered_map<string, string>();
79 // Helper class for deciding what should be ignored
83 IgnoreFormats() = default;
85 bool getFamily() const { return ignoreFamily_; }
87 bool getSeries() const { return ignoreSeries_; }
89 bool getShape() const { return ignoreShape_; }
91 bool getUnderline() const { return ignoreUnderline_; }
93 bool getMarkUp() const { return ignoreMarkUp_; }
95 bool getStrikeOut() const { return ignoreStrikeOut_; }
97 bool getSectioning() const { return ignoreSectioning_; }
99 bool getFrontMatter() const { return ignoreFrontMatter_; }
101 bool getColor() const { return ignoreColor_; }
103 bool getLanguage() const { return ignoreLanguage_; }
105 bool getDeleted() const { return ignoreDeleted_; }
107 void setIgnoreDeleted(bool value);
109 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreUnderline_ = false;
121 bool ignoreMarkUp_ = false;
123 bool ignoreStrikeOut_ = false;
125 bool ignoreSectioning_ = false;
127 bool ignoreFrontMatter_ = false;
129 bool ignoreColor_ = false;
131 bool ignoreLanguage_ = false;
132 bool userSelectedIgnoreLanguage_ = false;
134 bool ignoreDeleted_ = true;
137 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
139 if (type == "color") {
140 ignoreColor_ = value;
142 else if (type == "language") {
144 userSelectedIgnoreLanguage_ = value;
145 ignoreLanguage_ = value;
148 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
150 else if (type == "sectioning") {
151 ignoreSectioning_ = value;
152 ignoreFrontMatter_ = value;
154 else if (type == "font") {
155 ignoreSeries_ = value;
156 ignoreShape_ = value;
157 ignoreFamily_ = value;
159 else if (type == "series") {
160 ignoreSeries_ = value;
162 else if (type == "shape") {
163 ignoreShape_ = value;
165 else if (type == "family") {
166 ignoreFamily_ = value;
168 else if (type == "markup") {
169 ignoreMarkUp_ = value;
171 else if (type == "underline") {
172 ignoreUnderline_ = value;
174 else if (type == "strike") {
175 ignoreStrikeOut_ = value;
177 else if (type == "deleted") {
178 ignoreDeleted_ = value;
182 // The global variable that can be changed from outside
183 IgnoreFormats ignoreFormats;
186 void setIgnoreFormat(string const & type, bool value, bool fromUser)
188 ignoreFormats.setIgnoreFormat(type, value, fromUser);
194 bool parse_bool(docstring & howto, bool const defvalue = false)
199 howto = split(howto, var, ' ');
207 MatchString(docstring const & s, bool cs, bool mw)
208 : str(s), case_sens(cs), whole_words(mw)
211 // returns true if the specified string is at the specified position
212 // del specifies whether deleted strings in ct mode will be considered
213 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
215 return par.find(str, case_sens, whole_words, pos, del);
223 // match whole words only
228 int findForward(DocIterator & cur, MatchString const & match,
229 bool find_del = true)
231 for (; cur; cur.forwardChar())
232 if (cur.inTexted()) {
233 int len = match(cur.paragraph(), cur.pos(), find_del);
241 int findBackwards(DocIterator & cur, MatchString const & match,
242 bool find_del = true)
246 if (cur.inTexted()) {
247 int len = match(cur.paragraph(), cur.pos(), find_del);
256 bool searchAllowed(docstring const & str)
259 frontend::Alert::error(_("Search error"), _("Search string is empty"));
268 bool findOne(BufferView * bv, docstring const & searchstr,
269 bool case_sens, bool whole, bool forward,
270 bool find_del, bool check_wrap, bool auto_wrap)
272 if (!searchAllowed(searchstr))
275 DocIterator cur = forward
276 ? bv->cursor().selectionEnd()
277 : bv->cursor().selectionBegin();
279 MatchString const match(searchstr, case_sens, whole);
281 int match_len = forward
282 ? findForward(cur, match, find_del)
283 : findBackwards(cur, match, find_del);
286 bv->putSelectionAt(cur, match_len, !forward);
287 else if (check_wrap) {
288 DocIterator cur_orig(bv->cursor());
292 q = _("End of file reached while searching forward.\n"
293 "Continue searching from the beginning?");
295 q = _("Beginning of file reached while searching backward.\n"
296 "Continue searching from the end?");
297 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
298 q, 0, 1, _("&Yes"), _("&No"));
299 auto_wrap = wrap_answer == 0;
303 bv->cursor().clear();
304 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
306 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
307 bv->cursor().backwardPos();
309 bv->clearSelection();
310 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false, false))
313 bv->cursor().setCursor(cur_orig);
317 return match_len > 0;
323 int replaceAll(BufferView * bv,
324 docstring const & searchstr, docstring const & replacestr,
325 bool case_sens, bool whole)
327 Buffer & buf = bv->buffer();
329 if (!searchAllowed(searchstr) || buf.isReadonly())
332 DocIterator cur_orig(bv->cursor());
334 MatchString const match(searchstr, case_sens, whole);
337 int const rsize = replacestr.size();
338 int const ssize = searchstr.size();
341 cur.setCursor(doc_iterator_begin(&buf));
342 int match_len = findForward(cur, match, false);
343 while (match_len > 0) {
344 // Backup current cursor position and font.
345 pos_type const pos = cur.pos();
346 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
348 int striked = ssize -
349 cur.paragraph().eraseChars(pos, pos + match_len,
350 buf.params().track_changes);
351 cur.paragraph().insert(pos, replacestr, font,
352 Change(buf.params().track_changes
354 : Change::UNCHANGED));
355 for (int i = 0; i < rsize + striked; ++i)
358 match_len = findForward(cur, match, false);
361 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
363 cur_orig.fixIfBroken();
364 bv->setCursor(cur_orig);
370 // the idea here is that we are going to replace the string that
371 // is selected IF it is the search string.
372 // if there is a selection, but it is not the search string, then
373 // we basically ignore it. (FIXME We ought to replace only within
375 // if there is no selection, then:
376 // (i) if some search string has been provided, then we find it.
377 // (think of how the dialog works when you hit "replace" the
379 // (ii) if no search string has been provided, then we treat the
380 // word the cursor is in as the search string. (why? i have no
381 // idea.) but this only works in text?
383 // returns the number of replacements made (one, if any) and
384 // whether anything at all was done.
385 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
386 docstring const & replacestr, bool case_sens,
387 bool whole, bool forward, bool findnext, bool wrap)
389 Cursor & cur = bv->cursor();
390 if (!cur.selection()) {
391 // no selection, non-empty search string: find it
392 if (!searchstr.empty()) {
393 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext, wrap);
394 return make_pair(found, 0);
396 // empty search string
399 return make_pair(false, 0);
400 // select current word and treat it as the search string.
401 // This causes a minor bug as undo will restore this selection,
402 // which the user did not create (#8986).
403 cur.innerText()->selectWord(cur, WHOLE_WORD);
404 searchstr = cur.selectionAsString(false, true);
407 // if we still don't have a search string, report the error
409 if (!searchAllowed(searchstr))
410 return make_pair(false, 0);
412 bool have_selection = cur.selection();
413 docstring const selected = cur.selectionAsString(false, true);
416 ? searchstr == selected
417 : compare_no_case(searchstr, selected) == 0;
419 // no selection or current selection is not search word:
420 // just find the search word
421 if (!have_selection || !match) {
422 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext, wrap);
423 return make_pair(found, 0);
426 // we're now actually ready to replace. if the buffer is
427 // read-only, we can't, though.
428 if (bv->buffer().isReadonly())
429 return make_pair(false, 0);
431 cap::replaceSelectionWithString(cur, replacestr);
433 cur.pos() += replacestr.length();
434 LASSERT(cur.pos() <= cur.lastpos(),
435 cur.pos() = cur.lastpos());
438 findOne(bv, searchstr, case_sens, whole, forward, false, findnext, wrap);
440 return make_pair(true, 1);
446 docstring const find2string(docstring const & search,
447 bool casesensitive, bool matchword,
448 bool forward, bool wrap)
452 << int(casesensitive) << ' '
453 << int(matchword) << ' '
454 << int(forward) << ' '
460 docstring const replace2string(docstring const & replace,
461 docstring const & search,
462 bool casesensitive, bool matchword,
463 bool all, bool forward, bool findnext, bool wrap)
466 ss << replace << '\n'
468 << int(casesensitive) << ' '
469 << int(matchword) << ' '
471 << int(forward) << ' '
472 << int(findnext) << ' '
478 docstring const string2find(docstring const & argument,
484 // data is of the form
486 // <casesensitive> <matchword> <forward> <wrap>"
488 docstring howto = split(argument, search, '\n');
490 casesensitive = parse_bool(howto);
491 matchword = parse_bool(howto);
492 forward = parse_bool(howto, true);
493 wrap = parse_bool(howto, true);
499 bool lyxfind(BufferView * bv, FuncRequest const & ev)
501 if (!bv || ev.action() != LFUN_WORD_FIND)
504 //lyxerr << "find called, cmd: " << ev << endl;
509 docstring search = string2find(ev.argument(), casesensitive, matchword, forward, wrap);
511 return findOne(bv, search, casesensitive, matchword, forward, false, true, wrap);
515 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
517 if (!bv || ev.action() != LFUN_WORD_REPLACE)
520 // data is of the form
523 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap>"
526 docstring howto = split(ev.argument(), rplc, '\n');
527 howto = split(howto, search, '\n');
529 bool casesensitive = parse_bool(howto);
530 bool matchword = parse_bool(howto);
531 bool all = parse_bool(howto);
532 bool forward = parse_bool(howto, true);
533 bool findnext = parse_bool(howto, true);
534 bool wrap = parse_bool(howto);
538 int replace_count = 0;
540 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
541 update = replace_count > 0;
544 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext, wrap);
546 replace_count = rv.second;
549 Buffer const & buf = bv->buffer();
551 // emit message signal.
552 buf.message(_("String not found."));
554 if (replace_count == 0) {
555 buf.message(_("String found."));
556 } else if (replace_count == 1) {
557 buf.message(_("String has been replaced."));
559 docstring const str =
560 bformat(_("%1$d strings have been replaced."), replace_count);
568 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
570 for (; cur; cur.forwardPos())
571 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
575 DocIterator cur_orig(bv->cursor());
576 docstring q = _("End of file reached while searching forward.\n"
577 "Continue searching from the beginning?");
578 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
579 q, 0, 1, _("&Yes"), _("&No"));
580 if (wrap_answer == 0) {
581 bv->cursor().clear();
582 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
583 bv->clearSelection();
584 cur.setCursor(bv->cursor().selectionBegin());
585 if (findNextChange(bv, cur, false))
588 bv->cursor().setCursor(cur_orig);
595 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
597 for (cur.backwardPos(); cur; cur.backwardPos()) {
598 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
603 DocIterator cur_orig(bv->cursor());
604 docstring q = _("Beginning of file reached while searching backward.\n"
605 "Continue searching from the end?");
606 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
607 q, 0, 1, _("&Yes"), _("&No"));
608 if (wrap_answer == 0) {
609 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
610 bv->cursor().backwardPos();
611 bv->clearSelection();
612 cur.setCursor(bv->cursor().selectionBegin());
613 if (findPreviousChange(bv, cur, false))
616 bv->cursor().setCursor(cur_orig);
623 bool selectChange(Cursor & cur, bool forward)
625 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
627 Change ch = cur.paragraph().lookupChange(cur.pos());
629 CursorSlice tip1 = cur.top();
630 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
631 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
632 if (!ch2.isSimilarTo(ch))
635 CursorSlice tip2 = cur.top();
636 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
638 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
639 if (!ch2.isSimilarTo(ch)) {
640 // take a step forward to correctly set the selection
648 cur.bv().mouseSetCursor(cur, false);
650 cur.bv().mouseSetCursor(cur, true);
658 bool findChange(BufferView * bv, bool forward)
661 cur.setCursor(forward ? bv->cursor().selectionEnd()
662 : bv->cursor().selectionBegin());
663 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
664 return selectChange(cur, forward);
669 bool findNextChange(BufferView * bv)
671 return findChange(bv, true);
675 bool findPreviousChange(BufferView * bv)
677 return findChange(bv, false);
684 typedef vector<pair<string, string> > Escapes;
686 string string2regex(string in)
688 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
689 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
694 while (fl_pos < temp.size()) {
695 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
696 if (fl_pos == string::npos)
699 temp2 += temp.substr(lastpos, fl_pos - lastpos);
705 if (lastpos < temp.size()) {
706 temp2 += temp.substr(lastpos, temp.size() - lastpos);
711 string correctRegex(string t, bool withformat)
713 /* Convert \backslash => \
714 * and \{, \}, \[, \] => {, }, [, ]
717 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
720 bool backslashed = false;
721 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
724 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
728 if (sub.str(4) == "backslash") {
731 // transforms '\backslash \{' into '\{'
733 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
734 if ((next == "\\{") || (next == "\\}")) {
740 else if (sub.str(4) == "mathcircumflex")
742 else if (backslashed) {
744 if (withformat && (sub.str(3) == "{"))
745 replace = accents["braceleft"];
746 else if (withformat && (sub.str(3) == "}"))
747 replace = accents["braceright"];
749 // else part should not exist
754 replace = sub.str(3);
756 if (lastpos < (size_t) sub.position(2))
757 s += t.substr(lastpos, sub.position(2) - lastpos);
759 lastpos = sub.position(2) + sub.length(2);
763 else if (lastpos < t.length())
764 s += t.substr(lastpos, t.length() - lastpos);
768 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
769 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
770 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
771 string escape_for_regex(string s, bool withformat)
775 while (lastpos < s.size()) {
776 size_t regex_pos = s.find("\\regexp{", lastpos);
777 if (regex_pos == string::npos) {
778 regex_pos = s.size();
780 if (regex_pos > lastpos) {
781 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
783 if (lastpos == s.size())
786 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
787 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
788 lastpos = end_pos + 13;
794 /// Wrapper for lyx::regex_replace with simpler interface
795 bool regex_replace(string const & s, string & t, string const & searchstr,
796 string const & replacestr)
798 regex e(searchstr, regex_constants::ECMAScript);
800 ostream_iterator<char, char> it(oss);
801 regex_replace(it, s.begin(), s.end(), e, replacestr);
802 // tolerate t and s be references to the same variable
803 bool rv = (s != oss.str());
822 vector <string> result = vector <string>();
823 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
826 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
828 if (newres.match2end < oldres.match2end)
829 return MatchResult::newIsTooFar;
830 if (newres.match_len < oldres.match_len)
831 return MatchResult::newIsTooFar;
833 if (newres.match_len == oldres.match_len) {
834 if (newres.match2end == oldres.match2end)
835 return MatchResult::newIsBetter;
837 return MatchResult::newIsInvalid;
840 /** The class performing a match between a position in the document and the FindAdvOptions.
843 class MatchStringAdv {
845 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
847 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
848 ** constructor as opt.search, under the opt.* options settings.
851 ** If set, then match is searched only against beginning of text starting at cur.
852 ** If unset, then match is searched anywhere in text starting at cur.
855 ** The length of the matching text, or zero if no match was found.
857 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
866 /// first buffer on which search was started
867 lyx::Buffer * const p_first_buf;
869 FindAndReplaceOptions const & opt;
872 /// Auxiliary find method (does not account for opt.matchword)
873 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
874 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
876 /** Normalize a stringified or latexified LyX paragraph.
880 ** <li>if search is not casesensitive, then lowercase the string;
881 ** <li>remove any newline at begin or end of the string;
882 ** <li>replace any newline in the middle of the string with a simple space;
883 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
886 ** @todo Normalization should also expand macros, if the corresponding
887 ** search option was checked.
889 string normalize(docstring const & s) const;
890 // normalized string to search
891 string par_as_string;
892 // regular expression to use for searching
893 // regexp2 is same as regexp, but prefixed with a ".*?"
895 QRegularExpression regexp;
896 QRegularExpression regexp2;
901 // leading format material as string
902 string lead_as_string;
903 // par_as_string after removal of lead_as_string
904 string par_as_string_nolead;
905 // unmatched open braces in the search string/regexp
907 // number of (.*?) subexpressions added at end of search regexp for closing
908 // environments, math mode, styles, etc...
911 // Are we searching with regular expressions ?
913 static int valid_matches;
914 static vector <string> matches;
915 void FillResults(MatchResult &found_mr);
918 int MatchStringAdv::valid_matches = 0;
919 vector <string> MatchStringAdv::matches = vector <string>(10);
921 void MatchStringAdv::FillResults(MatchResult &found_mr)
923 if (found_mr.match_len > 0) {
924 valid_matches = found_mr.result.size();
925 for (size_t i = 0; i < found_mr.result.size(); i++)
926 matches[i] = found_mr.result[i];
932 static docstring buffer_to_latex(Buffer & buffer)
934 //OutputParams runparams(&buffer.params().encoding());
935 OutputParams runparams(encodings.fromLyXName("utf8"));
936 odocstringstream ods;
938 runparams.nice = true;
939 runparams.flavor = Flavor::XeTeX;
940 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
941 // No side effect of file copying and image conversion
942 runparams.dryrun = true;
943 if (ignoreFormats.getDeleted())
944 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
946 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
947 pit_type const endpit = buffer.paragraphs().size();
948 for (pit_type pit = 0; pit != endpit; ++pit) {
949 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
950 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
956 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
959 if (!opt.ignoreformat) {
960 str = buffer_to_latex(buffer);
962 // OutputParams runparams(&buffer.params().encoding());
963 OutputParams runparams(encodings.fromLyXName("utf8"));
964 runparams.nice = true;
965 runparams.flavor = Flavor::XeTeX;
966 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
967 runparams.dryrun = true;
968 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
969 if (ignoreFormats.getDeleted()) {
970 option |= AS_STR_SKIPDELETE;
971 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
974 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
976 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
977 Paragraph const & par = buffer.paragraphs().at(pit);
978 LYXERR(Debug::FIND, "Adding to search string: '"
979 << par.asString(pos_type(0), par.size(),
983 str += par.asString(pos_type(0), par.size(),
987 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
988 string t = to_utf8(str);
989 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
996 /// Return separation pos between the leading material and the rest
997 static size_t identifyLeading(string const & s)
1000 // @TODO Support \item[text]
1001 // Kornel: Added textsl, textsf, textit, texttt and noun
1002 // + allow to search for colored text too
1003 while (regex_replace(t, t, "^\\\\(("
1004 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1005 "lyxaddress|lyxrightaddress|"
1006 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1007 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1008 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1009 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1010 || regex_replace(t, t, "^\\$", "")
1011 || regex_replace(t, t, "^\\\\\\[", "")
1012 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1013 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1015 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1020 * Given a latexified string, retrieve some handled features
1021 * The features of the regex will later be compared with the features
1022 * of the searched text. If the regex features are not a
1023 * subset of the analized, then, in not format ignoring search
1024 * we can early stop the search in the relevant inset.
1026 typedef map<string, bool> Features;
1028 static Features identifyFeatures(string const & s)
1030 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1031 static regex const valid("^("
1033 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1034 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1035 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1036 "(u|uu)line|(s|x)out|uwave|"
1037 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1038 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1043 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1046 if (sub.str(1).compare("regexp") == 0) {
1050 string token = sub.str(1);
1052 if (regex_match(token, sub2, valid)) {
1060 if (sub.str(1).compare("endregexp") == 0) {
1070 * defines values features of a key "\\[a-z]+{"
1075 /* Char type with content discarded
1076 * like \hspace{1cm} */
1078 /* Char, like \backslash */
1080 /* replace starting backslash with '#' */
1082 /* \part, \section*, ... */
1084 /* title, author etc */
1086 /* \foreignlanguage{ngerman}, ... */
1089 * to discard language in content */
1092 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1094 /* fonts, colors, markups, ... */
1096 /* footnotesize, ... large, ...
1097 * Ignore all of them */
1100 /* inputencoding, ...
1101 * Discard also content, because they do not help in search */
1104 * like remove, but also all arguments */
1106 /* item, listitem */
1108 /* tex, latex, ... like isChar */
1110 /* like \lettrine[lines=5]{}{} */
1112 // like isStandard, but always remove head
1114 /* End of arguments marker for lettrine,
1115 * so that they can be ignored */
1118 KeyInfo() = default;
1119 KeyInfo(KeyType type, int parcount, bool disable)
1121 parenthesiscount(parcount),
1122 disabled(disable) {}
1123 KeyType keytype = invalid;
1125 int _tokensize = -1;
1126 int _tokenstart = -1;
1127 int _dataStart = -1;
1129 int parenthesiscount = 1;
1130 bool disabled = false;
1131 bool used = false; /* by pattern */
1136 Border(int l=0, int u=0) : low(l), upper(u) {};
1141 #define MAXOPENED 30
1143 bool isPatternString_;
1145 explicit Intervall(bool isPattern, string const & p) :
1146 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1147 hasTitle(false), langcount(0)
1155 static vector<Border> borders;
1156 int depts[MAXOPENED];
1157 int closes[MAXOPENED];
1158 int actualdeptindex;
1159 int previousNotIgnored(int) const;
1160 int nextNotIgnored(int) const;
1161 void handleOpenP(int i);
1162 void handleCloseP(int i, bool closingAllowed);
1163 void resetOpenedP(int openPos);
1164 void addIntervall(int upper);
1165 void addIntervall(int low, int upper); /* if explicit */
1166 void removeAccents();
1167 void setForDefaultLang(KeyInfo const & defLang) const;
1168 int findclosing(int start, int end, char up, char down, int repeat);
1169 void handleParentheses(int lastpos, bool closingAllowed);
1171 int langcount; // Number of disabled language specs up to current position in actual interval
1172 int isOpeningPar(int pos) const;
1174 void output(ostringstream &os, int lastpos);
1175 // string show(int lastpos);
1178 vector<Border> Intervall::borders = vector<Border>(30);
1180 int Intervall::isOpeningPar(int pos) const
1182 if ((pos < 0) || (size_t(pos) >= par.size()))
1184 if (par[pos] != '{')
1186 if (size_t(pos) + 2 >= par.size())
1188 if (par[pos+2] != '}')
1190 if (par[pos+1] == '[' || par[pos+1] == ']')
1195 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1197 // Enable the use of first token again
1198 if (ignoreidx >= 0) {
1199 int value = defLang._tokenstart + defLang._tokensize;
1205 if (borders[borderidx].low < value)
1206 borders[borderidx].low = value;
1207 if (borders[borderidx].upper < value)
1208 borders[borderidx].upper = value;
1213 static void checkDepthIndex(int val)
1215 static int maxdepthidx = MAXOPENED-2;
1216 static int lastmaxdepth = 0;
1217 if (val > lastmaxdepth) {
1218 LYXERR(Debug::INFO, "Depth reached " << val);
1221 if (val > maxdepthidx) {
1223 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1228 // Not needed, because borders are now dynamically expanded
1229 static void checkIgnoreIdx(int val)
1231 static int lastmaxignore = -1;
1232 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1233 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1234 lastmaxignore = val;
1240 * Expand the region of ignored parts of the input latex string
1241 * The region is only relevant in output()
1243 void Intervall::addIntervall(int low, int upper)
1246 if (low == upper) return;
1247 for (idx = ignoreidx+1; idx > 0; --idx) {
1248 if (low > borders[idx-1].upper) {
1252 Border br(low, upper);
1253 if (idx > ignoreidx) {
1254 if (borders.size() <= size_t(idx)) {
1255 borders.push_back(br);
1261 // checkIgnoreIdx(ignoreidx);
1265 // Expand only if one of the new bound is inside the interwall
1266 // We know here that br.low > borders[idx-1].upper
1267 if (br.upper < borders[idx].low) {
1268 // We have to insert at this pos
1269 if (size_t(ignoreidx+1) >= borders.size()) {
1270 borders.push_back(borders[ignoreidx]);
1273 borders[ignoreidx+1] = borders[ignoreidx];
1275 for (int i = ignoreidx; i > idx; --i) {
1276 borders[i] = borders[i-1];
1280 // checkIgnoreIdx(ignoreidx);
1283 // Here we know, that we are overlapping
1284 if (br.low > borders[idx].low)
1285 br.low = borders[idx].low;
1286 // check what has to be concatenated
1288 for (int i = idx; i <= ignoreidx; i++) {
1289 if (br.upper >= borders[i].low) {
1291 if (br.upper < borders[i].upper)
1292 br.upper = borders[i].upper;
1298 // count should be >= 1 here
1301 for (int i = idx + count; i <= ignoreidx; i++) {
1302 borders[i-count+1] = borders[i];
1304 ignoreidx -= count - 1;
1310 static void buildaccent(string n, string param, string values)
1314 const char delim = '|';
1315 while (getline(s, name, delim)) {
1317 for (char c : param) {
1318 string key = name + "{" + c + "}";
1319 // get the corresponding utf8-value
1320 if ((values[start] & 0xc0) != 0xc0) {
1321 // should not happen, utf8 encoding starts at least with 11xxxxxx
1322 // but value for '\dot{i}' is 'i', which is ascii
1323 if ((values[start] & 0x80) == 0) {
1325 accents[key] = values.substr(start, 1);
1326 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1331 for (int j = 1; ;j++) {
1332 if (start + j >= values.size()) {
1333 accents[key] = values.substr(start, j);
1334 start = values.size() - 1;
1337 else if ((values[start+j] & 0xc0) != 0x80) {
1338 // This is the first byte of following utf8 char
1339 accents[key] = values.substr(start, j);
1341 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1350 static string getutf8(unsigned uchar)
1353 string ret = string();
1355 if (uchar <= 0x7f) {
1356 c[maxc-1] = uchar & 0x7f;
1359 unsigned char rest = 0x40;
1360 unsigned char first = 0x80;
1362 for (int i = start; i >=0; --i) {
1364 c[i] = first + uchar;
1367 c[i] = 0x80 | (uchar & 0x3f);
1374 for (int i = 0; i < maxc; i++) {
1375 if (c[i] == 0) continue;
1381 static void buildAccentsMap()
1383 accents["imath"] = "ı";
1385 accents["jmath"] = "ȷ";
1386 accents["cdot"] = "·";
1387 accents["textasciicircum"] = "^";
1388 accents["mathcircumflex"] = "^";
1389 accents["sim"] = "~";
1390 accents["guillemotright"] = "»";
1391 accents["guillemotleft"] = "«";
1392 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1393 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1394 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1395 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1396 accents["negmedspace"] = getutf8(0xf0005);
1397 accents["thickspace"] = getutf8(0xf0006);
1398 accents["negthickspace"] = getutf8(0xf0007);
1399 accents["lyx"] = getutf8(0xf0010); // Used logos
1400 accents["LyX"] = getutf8(0xf0010);
1401 accents["tex"] = getutf8(0xf0011);
1402 accents["TeX"] = getutf8(0xf0011);
1403 accents["latex"] = getutf8(0xf0012);
1404 accents["LaTeX"] = getutf8(0xf0012);
1405 accents["latexe"] = getutf8(0xf0013);
1406 accents["LaTeXe"] = getutf8(0xf0013);
1407 accents["lyxarrow"] = getutf8(0xf0020);
1408 accents["braceleft"] = getutf8(0xf0030);
1409 accents["braceright"] = getutf8(0xf0031);
1410 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1411 accents["backslash LyX"] = getutf8(0xf0010);
1412 accents["backslash tex"] = getutf8(0xf0011);
1413 accents["backslash TeX"] = getutf8(0xf0011);
1414 accents["backslash latex"] = getutf8(0xf0012);
1415 accents["backslash LaTeX"] = getutf8(0xf0012);
1416 accents["backslash latexe"] = getutf8(0xf0013);
1417 accents["backslash LaTeXe"] = getutf8(0xf0013);
1418 accents["backslash lyxarrow"] = getutf8(0xf0020);
1419 accents["ddot{\\imath}"] = "ï";
1420 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1421 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1422 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1423 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1424 accents["acute{\\imath}"] = "í";
1425 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1426 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1427 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1428 buildaccent("mathring|r", "aAuUwy",
1430 accents["check{\\imath}"] = "ǐ";
1431 accents["check{\\jmath}"] = "ǰ";
1432 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1433 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1434 accents["hat{\\imath}"] = "î";
1435 accents["hat{\\jmath}"] = "ĵ";
1436 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1437 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1438 accents["bar{\\imath}"] = "ī";
1439 buildaccent("bar|=", "aAeEiIoOuUyY",
1440 "āĀēĒīĪōŌūŪȳȲ"); // macron
1441 accents["tilde{\\imath}"] = "ĩ";
1442 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1443 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1444 accents["breve{\\imath}"] = "ĭ";
1445 buildaccent("breve|u", "aAeEgGiIoOuU",
1446 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1447 accents["grave{\\imath}"] = "ì";
1448 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1449 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1450 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1451 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1452 buildaccent("ogonek|k", "AaEeIiUuOo",
1453 "ĄąĘęĮįŲųǪǫ"); // ogonek
1454 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1455 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1456 buildaccent("subring|textsubring", "Aa",
1458 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1459 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1460 buildaccent("subtilde|textsubtilde", "EeIiUu",
1461 "ḚḛḬḭṴṵ"); // subtilde
1462 accents["dgrave{\\imath}"] = "ȉ";
1463 accents["textdoublegrave{\\i}"] = "ȉ";
1464 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1465 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1466 accents["rcap{\\imath}"] = "ȉ";
1467 accents["textroundcap{\\i}"] = "ȉ";
1468 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1469 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1470 buildaccent("slashed", "oO",
1475 * Created accents in math or regexp environment
1476 * are macros, but we need the utf8 equivalent
1478 void Intervall::removeAccents()
1480 if (accents.empty())
1482 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1483 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1484 "|((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]))");
1486 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1488 string key = sub.str(1);
1489 AccentsIterator it_ac = accents.find(key);
1490 if (it_ac != accents.end()) {
1491 string val = it_ac->second;
1492 size_t pos = sub.position(size_t(0));
1493 for (size_t i = 0; i < val.size(); i++) {
1494 par[pos+i] = val[i];
1496 // Remove possibly following space too
1497 if (par[pos+sub.str(0).size()] == ' ')
1498 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1500 addIntervall(pos+val.size(), pos + sub.str(0).size());
1501 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1502 // remove traces of any remaining chars
1507 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1512 void Intervall::handleOpenP(int i)
1515 depts[actualdeptindex] = i+1;
1516 closes[actualdeptindex] = -1;
1517 checkDepthIndex(actualdeptindex);
1520 void Intervall::handleCloseP(int i, bool closingAllowed)
1522 if (actualdeptindex <= 0) {
1523 if (! closingAllowed)
1524 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1525 // if we are at the very end
1526 addIntervall(i, i+1);
1529 closes[actualdeptindex] = i+1;
1534 void Intervall::resetOpenedP(int openPos)
1536 // Used as initializer for foreignlanguage entry
1537 actualdeptindex = 1;
1538 depts[1] = openPos+1;
1542 int Intervall::previousNotIgnored(int start) const
1544 int idx = 0; /* int intervalls */
1545 for (idx = ignoreidx; idx >= 0; --idx) {
1546 if (start > borders[idx].upper)
1548 if (start >= borders[idx].low)
1549 start = borders[idx].low-1;
1554 int Intervall::nextNotIgnored(int start) const
1556 int idx = 0; /* int intervalls */
1557 for (idx = 0; idx <= ignoreidx; idx++) {
1558 if (start < borders[idx].low)
1560 if (start < borders[idx].upper)
1561 start = borders[idx].upper;
1566 typedef unordered_map<string, KeyInfo> KeysMap;
1567 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1568 typedef vector< KeyInfo> Entries;
1569 static KeysMap keys = unordered_map<string, KeyInfo>();
1575 Intervall interval_;
1576 void buildKeys(bool);
1577 void buildEntries(bool);
1578 void makeKey(const string &, KeyInfo, bool isPatternString);
1579 void processRegion(int start, int region_end); /* remove {} parts */
1580 void removeHead(KeyInfo const &, int count=0);
1583 LatexInfo(string const & par, bool isPatternString)
1584 : entidx_(-1), interval_(isPatternString, par)
1586 buildKeys(isPatternString);
1587 entries_ = vector<KeyInfo>();
1588 buildEntries(isPatternString);
1592 if (entries_.empty()) {
1595 if (entries_[0].keytype == KeyInfo::isTitle) {
1596 interval_.hasTitle = true;
1597 if (! entries_[0].disabled) {
1598 interval_.titleValue = entries_[0].head;
1601 interval_.titleValue = "";
1603 removeHead(entries_[0]);
1604 if (entries_.size() > 1)
1613 if (int(entries_.size()) > entidx_) {
1620 bool setNextKey(int idx) {
1621 if ((idx == entidx_) && (entidx_ >= 0)) {
1628 int find(int start, KeyInfo::KeyType keytype) const {
1632 while (tmpIdx < int(entries_.size())) {
1633 if (entries_[tmpIdx].keytype == keytype)
1639 int process(ostringstream & os, KeyInfo const & actual);
1640 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1641 // string show(int lastpos) { return interval.show(lastpos);};
1642 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1643 KeyInfo &getKeyInfo(int keyinfo) {
1644 static KeyInfo invalidInfo = KeyInfo();
1645 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1648 return entries_[keyinfo];
1650 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1651 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1655 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1659 for (int i = start; i < end; i += 1 + skip) {
1663 if (c == '\\') skip = 1;
1667 else if (c == down) {
1670 if ((repeat <= 0) || (par[i+1] != up))
1684 size_t mathpostfixsize;
1686 size_t mathprefixsize;
1690 vector<MathEntry> entries_;
1695 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1696 MathEntry m = MathEntry();
1698 m.mathStart = start;
1699 m.mathprefixsize = prefixsize;
1700 m.mathEnd = end + postfixsize;
1701 m.mathpostfixsize = postfixsize;
1702 m.mathSize = m.mathEnd - m.mathStart;
1703 entries_.push_back(m);
1705 bool empty() const { return entries_.empty(); };
1706 size_t getEndPos() const {
1707 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1710 return entries_[actualIdx_].mathEnd;
1712 size_t getStartPos() const {
1713 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1714 return 100000; /* definitely enough? */
1716 return entries_[actualIdx_].mathStart;
1718 size_t getPrefixSize() const {
1719 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1722 return entries_[actualIdx_].mathprefixsize;
1724 size_t getPostfixSize() const {
1725 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1728 return entries_[actualIdx_].mathpostfixsize;
1730 size_t getFirstPos() {
1732 return getStartPos();
1734 size_t getSize() const {
1735 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1738 return entries_[actualIdx_].mathSize;
1740 void incrEntry() { actualIdx_++; };
1743 void LatexInfo::buildEntries(bool isPatternString)
1745 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1746 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1747 static bool disableLanguageOverride = false;
1748 smatch sub, submath;
1749 bool evaluatingRegexp = false;
1751 bool evaluatingMath = false;
1752 bool evaluatingCode = false;
1754 bool evaluatingOptional = false;
1755 size_t optionalEnd = 0;
1758 bool math_end_waiting = false;
1759 size_t math_pos = 10000;
1760 size_t math_prefix_size = 1;
1762 static vector<string> usedText = vector<string>();
1763 static bool removeMathHull = false;
1765 interval_.removeAccents();
1767 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1769 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1770 // prefixed by odd count of '\\'
1773 if (math_end_waiting) {
1774 size_t pos = submath.position(size_t(2));
1775 if ((math_end == "$") &&
1776 (submath.str(2) == "$")) {
1777 mi.insert("$", math_pos, 1, pos, 1);
1778 math_end_waiting = false;
1780 else if ((math_end == "\\]") &&
1781 (submath.str(2) == "\\]")) {
1782 mi.insert("\\]", math_pos, 2, pos, 2);
1783 math_end_waiting = false;
1785 else if ((submath.str(3).compare("end") == 0) &&
1786 (submath.str(4).compare(math_end) == 0)) {
1787 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
1788 math_end_waiting = false;
1794 if (submath.str(3).compare("begin") == 0) {
1795 math_end_waiting = true;
1796 math_end = submath.str(4);
1797 math_pos = submath.position(size_t(2));
1798 math_prefix_size = submath.str(2).length();
1800 else if (submath.str(2).compare("\\[") == 0) {
1801 math_end_waiting = true;
1803 math_pos = submath.position(size_t(2));
1805 else if (submath.str(2) == "$") {
1806 size_t pos = submath.position(size_t(2));
1807 math_end_waiting = true;
1813 // Ignore language if there is math somewhere in pattern-string
1814 if (isPatternString) {
1815 for (auto s: usedText) {
1816 // Remove entries created in previous search runs
1819 usedText = vector<string>();
1822 keys["foreignlanguage"].disabled = true;
1823 disableLanguageOverride = true;
1824 removeMathHull = false;
1827 removeMathHull = true; // used later if not isPatternString
1828 disableLanguageOverride = false;
1832 if (disableLanguageOverride) {
1833 keys["foreignlanguage"].disabled = true;
1836 math_pos = mi.getFirstPos();
1837 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1839 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1840 // prefixed by odd count of '\\'
1843 string key = sub.str(5);
1845 if (sub.str(2)[0] == '\\')
1846 key = sub.str(2)[1];
1851 KeysIterator it_key = keys.find(key);
1852 if (it_key != keys.end()) {
1853 if (it_key->second.keytype == KeyInfo::headRemove) {
1854 KeyInfo found1 = it_key->second;
1855 found1.disabled = true;
1856 found1.head = "\\" + key + "{";
1857 found1._tokenstart = sub.position(size_t(2));
1858 found1._tokensize = found1.head.length();
1859 found1._dataStart = found1._tokenstart + found1.head.length();
1860 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1861 found1._dataEnd = endpos;
1866 if (evaluatingRegexp) {
1867 if (sub.str(3).compare("endregexp") == 0) {
1868 evaluatingRegexp = false;
1869 // found._tokenstart already set
1870 found._dataEnd = sub.position(size_t(2)) + 13;
1871 found._dataStart = found._dataEnd;
1872 found._tokensize = found._dataEnd - found._tokenstart;
1873 found.parenthesiscount = 0;
1874 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1881 if (evaluatingMath) {
1882 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1884 evaluatingMath = false;
1886 math_pos = mi.getStartPos();
1888 if (it_key == keys.end()) {
1889 found = KeyInfo(KeyInfo::isStandard, 0, true);
1890 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1891 found = KeyInfo(KeyInfo::isText, 0, false);
1892 if (isPatternString) {
1893 found.keytype = KeyInfo::isChar;
1894 found.disabled = false;
1898 usedText.push_back(key);
1902 if (key.compare("regexp") == 0) {
1903 evaluatingRegexp = true;
1904 found._tokenstart = sub.position(size_t(2));
1905 found._tokensize = 0;
1909 // Handle the other params of key
1910 if (found.keytype == KeyInfo::isIgnored)
1912 else if (found.keytype == KeyInfo::isMath) {
1913 if (size_t(sub.position(size_t(2))) == math_pos) {
1915 found._tokenstart = sub.position(size_t(2));
1916 found._tokensize = mi.getSize();
1917 found._dataEnd = found._tokenstart + found._tokensize;
1918 found._dataStart = found._dataEnd;
1919 found.parenthesiscount = 0;
1920 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1921 if (removeMathHull) {
1922 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1923 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1925 evaluatingMath = true;
1928 // begin|end of unknown env, discard
1929 // First handle tables
1930 // longtable|tabular
1931 bool discardComment;
1933 found.keytype = KeyInfo::doRemove;
1934 if ((sub.str(7).compare("longtable") == 0) ||
1935 (sub.str(7).compare("tabular") == 0)) {
1936 discardComment = true; /* '%' */
1939 discardComment = false;
1940 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1942 string token = sub.str(7);
1943 if (regex_match(token, sub2, removeArgs)) {
1944 found.keytype = KeyInfo::removeWithArg;
1947 // discard spaces before pos(2)
1948 int pos = sub.position(size_t(2));
1950 for (count = 0; pos - count > 0; count++) {
1951 char c = interval_.par[pos-count-1];
1952 if (discardComment) {
1953 if ((c != ' ') && (c != '%'))
1959 found._tokenstart = pos - count;
1960 if (sub.str(3).compare(0, 5, "begin") == 0) {
1961 size_t pos1 = pos + sub.str(2).length();
1962 if (sub.str(7).compare("cjk") == 0) {
1963 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1964 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1966 found.keytype = KeyInfo::isMain;
1967 found._dataStart = pos1;
1968 found._dataEnd = interval_.par.length();
1969 found.disabled = keys["foreignlanguage"].disabled;
1970 found.used = keys["foreignlanguage"].used;
1971 found._tokensize = pos1 - found._tokenstart;
1972 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1975 // Swallow possible optional params
1976 while (interval_.par[pos1] == '[') {
1977 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1979 // Swallow also the eventual parameter
1980 if (interval_.par[pos1] == '{') {
1981 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1984 found._dataEnd = pos1;
1986 found._dataStart = found._dataEnd;
1987 found._tokensize = count + found._dataEnd - pos;
1988 found.parenthesiscount = 0;
1989 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1990 found.disabled = true;
1994 // Handle "\end{...}"
1995 found._dataStart = pos + sub.str(2).length();
1996 found._dataEnd = found._dataStart;
1997 found._tokensize = count + found._dataEnd - pos;
1998 found.parenthesiscount = 0;
1999 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2000 found.disabled = true;
2004 else if (found.keytype != KeyInfo::isRegex) {
2005 found._tokenstart = sub.position(size_t(2));
2006 if (found.parenthesiscount == 0) {
2007 // Probably to be discarded
2008 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2009 char following = interval_.par[following_pos];
2010 if (following == ' ')
2011 found.head = "\\" + sub.str(5) + " ";
2012 else if (following == '=') {
2013 // like \uldepth=1000pt
2014 found.head = sub.str(2);
2017 found.head = "\\" + key;
2018 found._tokensize = found.head.length();
2019 found._dataEnd = found._tokenstart + found._tokensize;
2020 found._dataStart = found._dataEnd;
2023 int params = found._tokenstart + key.length() + 1;
2024 if (evaluatingOptional) {
2025 if (size_t(found._tokenstart) > optionalEnd) {
2026 evaluatingOptional = false;
2029 found.disabled = true;
2032 int optend = params;
2033 while (interval_.par[optend] == '[') {
2034 // discard optional parameters
2035 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2037 if (optend > params) {
2038 key += interval_.par.substr(params, optend-params);
2039 evaluatingOptional = true;
2040 optionalEnd = optend;
2041 if (found.keytype == KeyInfo::isSectioning) {
2042 // Remove optional values (but still keep in header)
2043 interval_.addIntervall(params, optend);
2046 string token = sub.str(7);
2048 if (interval_.par[optend] != '{') {
2050 found.parenthesiscount = 0;
2051 found.head = "\\" + key;
2054 closings = found.parenthesiscount;
2055 if (found.parenthesiscount == 1) {
2056 found.head = "\\" + key + "{";
2058 else if (found.parenthesiscount > 1) {
2060 found.head = sub.str(2) + "{";
2061 closings = found.parenthesiscount - 1;
2064 found.head = "\\" + key + "{";
2067 found._tokensize = found.head.length();
2068 found._dataStart = found._tokenstart + found.head.length();
2069 if (found.keytype == KeyInfo::doRemove) {
2071 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2072 if (endpar >= interval_.par.length())
2073 found._dataStart = interval_.par.length();
2075 found._dataStart = endpar;
2076 found._tokensize = found._dataStart - found._tokenstart;
2079 found._dataStart = found._tokenstart + found._tokensize;
2083 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2084 found._dataStart += 15;
2088 endpos = found._dataStart - 1;
2090 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2091 if (found.keytype == KeyInfo::isList) {
2092 // Check if it really is list env
2093 static regex const listre("^([a-z]+)$");
2095 if (!regex_match(token, sub2, listre)) {
2096 // Change the key of this entry. It is not in a list/item environment
2097 found.keytype = KeyInfo::endArguments;
2100 if (found.keytype == KeyInfo::noMain) {
2101 evaluatingCode = true;
2103 codeStart = found._dataStart;
2105 else if (evaluatingCode) {
2106 if (size_t(found._dataStart) > codeEnd)
2107 evaluatingCode = false;
2108 else if (found.keytype == KeyInfo::isMain) {
2109 // Disable this key, treate it as standard
2110 found.keytype = KeyInfo::isStandard;
2111 found.disabled = true;
2112 if ((codeEnd +1 >= interval_.par.length()) &&
2113 (found._tokenstart == codeStart)) {
2114 // trickery, because the code inset starts
2115 // with \selectlanguage ...
2117 if (entries_.size() > 1) {
2118 entries_[entries_.size()-1]._dataEnd = codeEnd;
2123 if ((endpos == interval_.par.length()) &&
2124 (found.keytype == KeyInfo::doRemove)) {
2125 // Missing closing => error in latex-input?
2126 // therefore do not delete remaining data
2127 found._dataStart -= 1;
2128 found._dataEnd = found._dataStart;
2131 found._dataEnd = endpos;
2133 if (isPatternString) {
2134 keys[key].used = true;
2137 entries_.push_back(found);
2141 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2143 stringstream s(keysstring);
2145 const char delim = '|';
2146 while (getline(s, key, delim)) {
2147 KeyInfo keyII(keyI);
2148 if (isPatternString) {
2151 else if ( !keys[key].used)
2152 keyII.disabled = true;
2157 void LatexInfo::buildKeys(bool isPatternString)
2160 static bool keysBuilt = false;
2161 if (keysBuilt && !isPatternString) return;
2163 // Keys to ignore in any case
2164 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2165 // Known standard keys with 1 parameter.
2166 // Split is done, if not at start of region
2167 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2168 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2169 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2170 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2171 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2172 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2174 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2175 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2176 makeKey("section*|subsection*|subsubsection*|paragraph*",
2177 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2178 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2179 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2181 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2183 // Split is done, if not at start of region
2184 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2185 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2187 // Split is done always.
2188 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2192 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2193 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2194 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2195 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2197 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2198 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2199 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2200 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2202 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2203 // Custom space/skip, remove the content (== length value)
2204 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2205 // Found in fr/UserGuide.lyx
2206 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2208 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2209 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2210 // Known macros to remove (including their parameter)
2212 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2213 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2214 // handle like standard keys with 1 parameter.
2215 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2217 // Ignore deleted text
2218 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2219 // but preserve added text
2220 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2222 // Macros to remove, but let the parameter survive
2224 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2226 // Remove language spec from content of these insets
2227 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2229 // Same effect as previous, parameter will survive (because there is no one anyway)
2231 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2232 // Remove table decorations
2233 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2234 // Discard shape-header.
2235 // For footnote or shortcut too, because of lang settings
2236 // and wrong handling if used 'KeyInfo::noMain'
2237 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2238 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2239 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2240 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2241 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2242 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2243 // like ('tiny{}' or '\tiny ' ... )
2244 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2246 // Survives, like known character
2247 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2248 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2249 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2251 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2252 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2253 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2255 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2256 // Remove RTL/LTR marker
2257 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2258 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2259 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2260 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2261 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2262 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2263 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2264 if (isPatternString) {
2265 // Allow the first searched string to rebuild the keys too
2269 // no need to rebuild again
2275 * Keep the list of actual opened parentheses actual
2276 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2278 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2281 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2285 if (c == '\\') skip = 1;
2286 else if (c == '{') {
2289 else if (c == '}') {
2290 handleCloseP(i, closingAllowed);
2296 string Intervall::show(int lastpos)
2298 int idx = 0; /* int intervalls */
2301 for (idx = 0; idx <= ignoreidx; idx++) {
2302 while (i < lastpos) {
2304 if (i <= borders[idx].low) {
2305 if (borders[idx].low > lastpos)
2306 printsize = lastpos - i;
2308 printsize = borders[idx].low - i;
2309 s += par.substr(i, printsize);
2311 if (i >= borders[idx].low)
2312 i = borders[idx].upper;
2315 i = borders[idx].upper;
2321 s += par.substr(i, lastpos-i);
2327 void Intervall::output(ostringstream &os, int lastpos)
2329 // get number of chars to output
2330 int idx = 0; /* int intervalls */
2333 string startTitle = titleValue;
2334 for (idx = 0; idx <= ignoreidx; idx++) {
2336 if (i <= borders[idx].low) {
2338 if (borders[idx].low > lastpos)
2339 printsize = lastpos - i;
2341 printsize = borders[idx].low - i;
2342 if (printsize > 0) {
2343 os << startTitle << par.substr(i, printsize);
2345 printed += printsize;
2348 handleParentheses(i, false);
2349 if (i >= borders[idx].low)
2350 i = borders[idx].upper;
2353 i = borders[idx].upper;
2360 os << startTitle << par.substr(i, lastpos-i);
2361 printed += lastpos-i;
2363 handleParentheses(lastpos, false);
2365 if (keys["foreignlanguage"].disabled)
2366 startindex = actualdeptindex-langcount;
2368 startindex = actualdeptindex;
2369 for (int i = startindex; i > 0; --i) {
2372 if (hasTitle && (printed > 0))
2374 if (! isPatternString_)
2376 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2379 void LatexInfo::processRegion(int start, int region_end)
2381 while (start < region_end) { /* Let {[} and {]} survive */
2382 int cnt = interval_.isOpeningPar(start);
2384 // Closing is allowed past the region
2385 int closing = interval_.findclosing(start+1, interval_.par.length());
2386 interval_.addIntervall(start, start+1);
2387 interval_.addIntervall(closing, closing+1);
2391 start = interval_.nextNotIgnored(start+1);
2395 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2397 if (actual.parenthesiscount == 0) {
2398 // "{\tiny{} ...}" ==> "{{} ...}"
2399 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2402 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2403 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2404 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2408 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2411 switch (actual.keytype)
2413 case KeyInfo::isTitle: {
2415 nextKeyIdx = getNextKey();
2418 case KeyInfo::cleanToStart: {
2419 actual._dataEnd = actual._dataStart;
2420 nextKeyIdx = getNextKey();
2421 // Search for end of arguments
2422 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2424 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2425 entries_[i].disabled = true;
2427 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2429 while (interval_.par[actual._dataEnd] == ' ')
2431 interval_.addIntervall(0, actual._dataEnd+1);
2432 interval_.actualdeptindex = 0;
2433 interval_.depts[0] = actual._dataEnd+1;
2434 interval_.closes[0] = -1;
2437 case KeyInfo::isText:
2438 interval_.par[actual._tokenstart] = '#';
2439 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2440 nextKeyIdx = getNextKey();
2442 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2443 if (actual.disabled)
2444 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2446 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2449 case KeyInfo::isChar: {
2450 nextKeyIdx = getNextKey();
2453 case KeyInfo::isSize: {
2454 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2455 if (actual.parenthesiscount == 0)
2456 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2458 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2460 nextKeyIdx = getNextKey();
2462 // Here _dataStart points to '{', so correct it
2463 actual._dataStart += 1;
2464 actual._tokensize += 1;
2465 actual.parenthesiscount = 1;
2466 if (interval_.par[actual._dataStart] == '}') {
2467 // Determine the end if used like '{\tiny{}...}'
2468 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2469 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2472 // Determine the end if used like '\tiny{...}'
2473 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2475 // Split on this key if not at start
2476 int start = interval_.nextNotIgnored(previousStart);
2477 if (start < actual._tokenstart) {
2478 interval_.output(os, actual._tokenstart);
2479 interval_.addIntervall(start, actual._tokenstart);
2481 // discard entry if at end of actual
2482 nextKeyIdx = process(os, actual);
2486 case KeyInfo::endArguments: {
2487 // Remove trailing '{}' too
2488 actual._dataStart += 1;
2489 actual._dataEnd += 1;
2490 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2491 nextKeyIdx = getNextKey();
2494 case KeyInfo::noMain:
2496 case KeyInfo::isStandard: {
2497 if (actual.disabled) {
2499 processRegion(actual._dataStart, actual._dataStart+1);
2500 nextKeyIdx = getNextKey();
2502 // Split on this key if not at datastart of calling entry
2503 int start = interval_.nextNotIgnored(previousStart);
2504 if (start < actual._tokenstart) {
2505 interval_.output(os, actual._tokenstart);
2506 interval_.addIntervall(start, actual._tokenstart);
2508 // discard entry if at end of actual
2509 nextKeyIdx = process(os, actual);
2513 case KeyInfo::removeWithArg: {
2514 nextKeyIdx = getNextKey();
2515 // Search for end of arguments
2516 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2518 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2519 entries_[i].disabled = true;
2521 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2523 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2526 case KeyInfo::doRemove: {
2527 // Remove the key with all parameters and following spaces
2530 if (interval_.par[actual._dataEnd-1] == ' ')
2531 start = actual._dataEnd;
2533 start = actual._dataEnd+1;
2534 for (pos = start; pos < interval_.par.length(); pos++) {
2535 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2538 // Remove also enclosing parentheses [] and {}
2541 while (actual._tokenstart > numpars) {
2542 if (pos+numpars >= interval_.par.size())
2544 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2546 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2552 if (interval_.par[pos+numpars] == ' ')
2556 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2557 nextKeyIdx = getNextKey();
2560 case KeyInfo::isList: {
2561 // Discard space before _tokenstart
2563 for (count = 0; count < actual._tokenstart; count++) {
2564 if (interval_.par[actual._tokenstart-count-1] != ' ')
2567 nextKeyIdx = getNextKey();
2568 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2570 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2572 // How else can we catch this one?
2573 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2574 entries_[i].disabled = true;
2576 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2578 else if (nextKeyIdx > 0) {
2579 // Ignore any lang entries inside data region
2580 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2581 if (entries_[i].keytype == KeyInfo::isMain)
2582 entries_[i].disabled = true;
2585 if (actual.disabled) {
2586 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2589 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2591 if (interval_.par[actual._dataEnd+1] == '[') {
2592 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2593 if ((interval_.par[actual._dataEnd+2] == '{') &&
2594 (interval_.par[posdown-1] == '}')) {
2595 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2596 interval_.addIntervall(posdown-1, posdown+1);
2599 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2600 interval_.addIntervall(posdown, posdown+1);
2602 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2603 if (blk > posdown) {
2604 // Discard at most 1 space after empty item
2606 for (count = 0; count < 1; count++) {
2607 if (interval_.par[blk+count] != ' ')
2611 interval_.addIntervall(blk, blk+count);
2616 case KeyInfo::isSectioning: {
2617 // Discard spaces before _tokenstart
2619 int val = actual._tokenstart;
2620 for (count = 0; count < actual._tokenstart;) {
2621 val = interval_.previousNotIgnored(val-1);
2622 if (val < 0 || interval_.par[val] != ' ')
2625 count = actual._tokenstart - val;
2628 if (actual.disabled) {
2629 removeHead(actual, count);
2630 nextKeyIdx = getNextKey();
2632 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2633 nextKeyIdx = process(os, actual);
2637 case KeyInfo::isMath: {
2638 // Same as regex, use the content unchanged
2639 nextKeyIdx = getNextKey();
2642 case KeyInfo::isRegex: {
2643 // DO NOT SPLIT ON REGEX
2645 nextKeyIdx = getNextKey();
2648 case KeyInfo::isIgnored: {
2649 // Treat like a character for now
2650 nextKeyIdx = getNextKey();
2653 case KeyInfo::isMain: {
2654 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2655 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2656 if (actual._tokenstart > 0) {
2657 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2658 if ((prev >= 0) && interval_.par[prev] == '%')
2659 interval_.addIntervall(prev, prev+1);
2661 if (actual.disabled) {
2663 interval_.langcount++;
2664 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2665 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2666 // Discard also the space before math-equation
2667 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2669 nextKeyIdx = getNextKey();
2670 // interval.resetOpenedP(actual._dataStart-1);
2673 if (actual._tokenstart < 26) {
2674 // for the first (and maybe dummy) language
2675 interval_.setForDefaultLang(actual);
2677 interval_.resetOpenedP(actual._dataStart-1);
2681 case KeyInfo::invalid:
2682 case KeyInfo::headRemove:
2683 // These two cases cannot happen, already handled
2686 // LYXERR(Debug::INFO, "Unhandled keytype");
2687 nextKeyIdx = getNextKey();
2694 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2696 int end = interval_.nextNotIgnored(actual._dataEnd);
2697 int oldStart = actual._dataStart;
2698 int nextKeyIdx = getNextKey();
2700 if ((nextKeyIdx < 0) ||
2701 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2702 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2703 if (oldStart <= end) {
2704 processRegion(oldStart, end);
2709 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2711 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2712 (void) dispatch(os, actual._dataStart, nextKey);
2713 end = nextKey._tokenstart;
2716 processRegion(oldStart, nextKey._tokenstart);
2717 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2719 oldStart = nextKey._dataEnd+1;
2721 // now nextKey is either invalid or is outside of actual._dataEnd
2722 // output the remaining and discard myself
2723 if (oldStart <= end) {
2724 processRegion(oldStart, end);
2726 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2728 // This is the normal case.
2729 // But if using the firstlanguage, the closing may be missing
2731 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2733 if (actual._dataEnd < end)
2734 output_end = interval_.nextNotIgnored(actual._dataEnd);
2735 else if (interval_.par.size() > (size_t) end)
2736 output_end = interval_.nextNotIgnored(end);
2738 output_end = interval_.par.size();
2739 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2740 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2742 // Remove possible empty data
2743 int dstart = interval_.nextNotIgnored(actual._dataStart);
2744 while (interval_.isOpeningPar(dstart) == 1) {
2745 interval_.addIntervall(dstart, dstart+1);
2746 int dend = interval_.findclosing(dstart+1, output_end);
2747 interval_.addIntervall(dend, dend+1);
2748 dstart = interval_.nextNotIgnored(dstart+1);
2750 if (dstart < output_end)
2751 interval_.output(os, output_end);
2753 interval_.addIntervall(0, end);
2755 interval_.addIntervall(actual._tokenstart, end);
2759 string splitOnKnownMacros(string par, bool isPatternString)
2762 LatexInfo li(par, isPatternString);
2763 // LYXERR(Debug::INFO, "Berfore split: " << par);
2764 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2766 DummyKey._tokensize = 0;
2767 DummyKey._dataStart = 0;
2768 DummyKey._dataEnd = par.length();
2769 DummyKey.disabled = true;
2770 int firstkeyIdx = li.getFirstKey();
2772 if (firstkeyIdx >= 0) {
2773 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2774 DummyKey._tokenstart = firstKey._tokenstart;
2776 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2777 // Use dummy firstKey
2778 firstKey = DummyKey;
2779 (void) li.setNextKey(firstkeyIdx);
2782 if (par.substr(firstKey._dataStart, 2) == "% ")
2783 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2785 nextkeyIdx = li.process(os, firstKey);
2786 while (nextkeyIdx >= 0) {
2787 // Check for a possible gap between the last
2788 // entry and this one
2789 int datastart = li.nextNotIgnored(firstKey._dataStart);
2790 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2791 if ((nextKey._tokenstart > datastart)) {
2793 firstKey._dataStart = datastart;
2794 firstKey._dataEnd = par.length();
2795 (void) li.setNextKey(nextkeyIdx);
2796 // Fake the last opened parenthesis
2797 li.setForDefaultLang(firstKey);
2798 nextkeyIdx = li.process(os, firstKey);
2801 if (nextKey.keytype != KeyInfo::isMain) {
2802 firstKey._dataStart = datastart;
2803 firstKey._dataEnd = nextKey._dataEnd+1;
2804 (void) li.setNextKey(nextkeyIdx);
2805 li.setForDefaultLang(firstKey);
2806 nextkeyIdx = li.process(os, firstKey);
2809 nextkeyIdx = li.process(os, nextKey);
2813 // Handle the remaining
2814 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2815 firstKey._dataEnd = par.length();
2817 if ((firstKey._dataStart < firstKey._dataEnd) &&
2818 (par[firstKey._dataStart] != '}')) {
2819 li.setForDefaultLang(firstKey);
2820 (void) li.process(os, firstKey);
2824 // return string definitelly impossible to match
2825 s = "\\foreignlanguage{ignore}{ }";
2829 s = par; /* no known macros found */
2830 // LYXERR(Debug::INFO, "After split: " << s);
2835 * Try to unify the language specs in the latexified text.
2836 * Resulting modified string is set to "", if
2837 * the searched tex does not contain all the features in the search pattern
2839 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2841 static Features regex_f;
2842 static int missed = 0;
2843 static bool regex_with_format = false;
2845 int parlen = par.length();
2847 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2850 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2851 // Happens to be there in case of description or labeling environment
2856 // Split the latex input into pieces which
2857 // can be digested by our search engine
2858 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2859 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2860 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2861 string doclang = pbuf->params().language->polyglossia();
2862 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2864 bool toIgnoreLang = true;
2865 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2867 if (sub.str(2) != doclang) {
2868 toIgnoreLang = false;
2872 setIgnoreFormat("language", toIgnoreLang, false);
2875 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2876 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2879 result = par.substr(0, parlen);
2880 if (isPatternString) {
2883 regex_f = identifyFeatures(result);
2884 string features = "";
2885 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2886 string a = it->first;
2887 regex_with_format = true;
2888 features += " " + a;
2889 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2891 LYXERR(Debug::FIND, "Identified Features" << features);
2894 } else if (regex_with_format) {
2895 Features info = identifyFeatures(result);
2896 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2897 string a = it->first;
2898 bool b = it->second;
2899 if (b && ! info[a]) {
2901 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2908 // LYXERR(Debug::INFO, "No regex formats");
2914 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2915 static int identifyClosing(string & t)
2917 int open_braces = 0;
2919 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2920 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2922 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2924 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2926 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2935 static int num_replaced = 0;
2936 static bool previous_single_replace = true;
2938 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2941 // Handle \w properly
2942 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2943 if (! opt.casesensitive) {
2944 popts |= QRegularExpression::CaseInsensitiveOption;
2946 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2947 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2949 if (regexp.isValid() && regexp2.isValid()) {
2950 regexIsValid = true;
2951 // Check '{', '}' pairs inside the regex
2954 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2955 char c = par_as_string[i];
2962 else if (c == '}') {
2969 if (balanced != 0) {
2970 regexIsValid = false;
2971 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2975 regexIsValid = false;
2976 if (!regexp.isValid())
2977 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2979 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2982 if (opt.casesensitive) {
2983 regexp = regex(regexp_str);
2984 regexp2 = regex(regexp2_str);
2987 regexp = regex(regexp_str, std::regex_constants::icase);
2988 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2993 static void modifyRegexForMatchWord(string &t)
2996 regex wordre("(\\\\)*((\\.|\\\\b))");
2999 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3001 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3004 else if (sub.str(2) == "\\\\b")
3006 if (lastpos < (size_t) sub.position(2))
3007 s += t.substr(lastpos, sub.position(2) - lastpos);
3009 lastpos = sub.position(2) + sub.length(2);
3012 s = "\\b" + t + "\\b";
3016 else if (lastpos < t.length())
3017 s += t.substr(lastpos, t.length() - lastpos);
3018 t = "\\b" + s + "\\b";
3021 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3022 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3024 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3025 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3026 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3027 if (opt.replace_all && previous_single_replace) {
3028 previous_single_replace = false;
3031 else if (!opt.replace_all) {
3032 num_replaced = 0; // count number of replaced strings
3033 previous_single_replace = true;
3035 // When using regexp, braces are hacked already by escape_for_regex()
3036 par_as_string = normalize(ds);
3038 close_wildcards = 0;
3040 size_t lead_size = 0;
3041 // correct the language settings
3042 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3043 opt.matchAtStart = false;
3045 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3046 if (opt.ignoreformat) {
3050 lead_size = identifyLeading(par_as_string);
3052 lead_as_string = par_as_string.substr(0, lead_size);
3053 string lead_as_regex_string = string2regex(lead_as_string);
3054 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3055 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3056 /* Handle whole words too in this case
3058 if (opt.matchword) {
3059 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3060 opt.matchword = false;
3062 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3063 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3064 CreateRegexp(opt, regexp_str, regexp2_str);
3066 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3067 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3071 if (!opt.ignoreformat) {
3072 lead_size = identifyLeading(par_as_string);
3073 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3074 lead_as_string = par_as_string.substr(0, lead_size);
3075 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3078 // Here we are using regexp
3079 LASSERT(use_regexp, /**/);
3081 string lead_as_regexp;
3082 if (lead_size > 0) {
3083 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3084 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3085 par_as_string = par_as_string_nolead;
3086 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3087 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3089 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3090 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3091 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3092 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3094 size_t lng = par_as_string.size();
3095 if (!opt.ignoreformat) {
3096 // Remove extra '\}' at end if not part of \{\.\}
3098 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3100 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3109 if (lng < par_as_string.size())
3110 par_as_string = par_as_string.substr(0,lng);
3112 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3113 if ((lng > 0) && (par_as_string[0] == '^')) {
3114 par_as_string = par_as_string.substr(1);
3116 opt.matchAtStart = true;
3118 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3119 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3120 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3122 // If entered regexp must match at begin of searched string buffer
3123 // Kornel: Added parentheses to use $1 for size of the leading string
3127 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3128 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3129 // so the convert has no effect in that case
3130 for (int i = 7; i > 0; --i) {
3131 string orig = "\\\\" + std::to_string(i);
3132 string dest = "\\" + std::to_string(i+2);
3133 while (regex_replace(par_as_string, par_as_string, orig, dest));
3135 if (opt.matchword) {
3136 modifyRegexForMatchWord(par_as_string);
3137 opt.matchword = false;
3139 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3140 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3142 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3143 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3144 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3148 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3152 mres.searched_size = len;
3154 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3157 docstring docstr = stringifyFromForSearch(opt, cur, len);
3159 str = normalize(docstr);
3160 if (!opt.ignoreformat) {
3161 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3162 // remove closing '}' and '\n' to allow for use of '$' in regex
3163 size_t lng = str.size();
3164 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3166 if (lng != str.size()) {
3167 str = str.substr(0, lng);
3171 mres.match_len = -1;
3174 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3176 LASSERT(use_regexp, /**/);
3178 // use_regexp always true
3179 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3181 QString qstr = QString::fromStdString(str);
3182 QRegularExpression const *p_regexp;
3183 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3187 p_regexp = ®exp2;
3189 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3190 if (!match.hasMatch())
3193 regex const *p_regexp;
3194 regex_constants::match_flag_type flags;
3196 flags = regex_constants::match_continuous;
3199 flags = regex_constants::match_default;
3200 p_regexp = ®exp2;
3202 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3203 if (re_it == sregex_iterator())
3205 match_results<string::const_iterator> const & m = *re_it;
3207 // Whole found string, including the leading
3208 // std: m[0].second - m[0].first
3209 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3211 // Size of the leading string
3212 // std: m[1].second - m[1].first
3213 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3214 int leadingsize = 0;
3216 if (match.lastCapturedIndex() > 0) {
3217 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3222 leadingsize = m[1].second - m[1].first;
3226 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3227 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3228 // because of different number of closing at end of string
3229 // we have to 'unify' the length of the post-match.
3230 // Done by ignoring closing parenthesis and linefeeds at string end
3231 int matchend = match.capturedEnd(0);
3232 size_t strsize = qstr.size();
3233 if (!opt.ignoreformat) {
3234 while (mres.match_len > 0) {
3235 QChar c = qstr.at(matchend - 1);
3236 if ((c == '\n') || (c == '}') || (c == '{')) {
3243 while (strsize > (size_t) match.capturedEnd(0)) {
3244 QChar c = qstr.at(strsize-1);
3245 if ((c == '\n') || (c == '}')) {
3252 // LYXERR0(qstr.toStdString());
3253 mres.match2end = strsize - matchend;
3254 mres.pos = match.capturedStart(2);
3256 mres.match_prefix = m[2].second - m[2].first;
3257 mres.match_len = m[0].second - m[2].second;
3258 // ignore closing parenthesis and linefeeds at string end
3259 size_t strend = m[0].second - m[0].first;
3260 int matchend = strend;
3261 size_t strsize = str.size();
3262 if (!opt.ignoreformat) {
3263 while (mres.match_len > 0) {
3264 char c = str.at(matchend - 1);
3265 if ((c == '\n') || (c == '}') || (c == '{')) {
3272 while (strsize > strend) {
3273 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3281 mres.match2end = strsize - matchend;
3282 mres.pos = m[2].first - m[0].first;;
3284 if (mres.match2end < 0)
3286 mres.leadsize = leadingsize;
3288 if (mres.match_len > 0) {
3289 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3290 mres.result.push_back(a0);
3291 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3292 mres.result.push_back(match.captured(i).toStdString());
3296 if (mres.match_len > 0) {
3297 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3298 mres.result.push_back(a0);
3299 for (size_t i = 3; i < m.size(); i++) {
3300 mres.result.push_back(m[i]);
3309 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3311 MatchResult mres = findAux(cur, len, at_begin);
3312 int res = mres.match_len;
3314 "res=" << res << ", at_begin=" << at_begin
3315 << ", matchAtStart=" << opt.matchAtStart
3316 << ", inTexted=" << cur.inTexted());
3317 if (opt.matchAtStart) {
3320 else if (mres.match_prefix > 0)
3329 static bool simple_replace(string &t, string from, string to)
3331 regex repl("(\\\\)*(" + from + ")");
3335 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3337 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3339 if (lastpos < (size_t) sub.position(2))
3340 s += t.substr(lastpos, sub.position(2) - lastpos);
3342 lastpos = sub.position(2) + sub.length(2);
3346 else if (lastpos < t.length())
3347 s += t.substr(lastpos, t.length() - lastpos);
3353 string MatchStringAdv::normalize(docstring const & s) const
3356 t = lyx::to_utf8(s);
3357 // Remove \n at begin
3358 while (!t.empty() && t[0] == '\n')
3361 while (!t.empty() && t[t.size() - 1] == '\n')
3362 t = t.substr(0, t.size() - 1);
3364 // Handle all other '\n'
3365 while ((pos = t.find("\n")) != string::npos) {
3366 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3368 if (isAlnumASCII(t[pos+1])) {
3369 t.replace(pos-2, 3, " ");
3372 t.replace(pos-2, 3, "");
3375 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3376 // '\n' adjacent to non-alpha-numerics, discard
3377 t.replace(pos, 1, "");
3380 // Replace all other \n with spaces
3381 t.replace(pos, 1, " ");
3384 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3385 // Kornel: Added textsl, textsf, textit, texttt and noun
3386 // + allow to seach for colored text too
3387 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3388 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3389 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3390 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3391 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3392 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3398 docstring stringifyFromCursor(DocIterator const & cur, int len)
3400 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3401 if (cur.inTexted()) {
3402 Paragraph const & par = cur.paragraph();
3403 // TODO what about searching beyond/across paragraph breaks ?
3404 // TODO Try adding a AS_STR_INSERTS as last arg
3405 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3406 int(par.size()) : cur.pos() + len;
3407 // OutputParams runparams(&cur.buffer()->params().encoding());
3408 OutputParams runparams(encodings.fromLyXName("utf8"));
3409 runparams.nice = true;
3410 runparams.flavor = Flavor::XeTeX;
3411 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3412 // No side effect of file copying and image conversion
3413 runparams.dryrun = true;
3414 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3415 if (ignoreFormats.getDeleted()) {
3416 option |= AS_STR_SKIPDELETE;
3417 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3420 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3422 LYXERR(Debug::FIND, "Stringifying with cur: "
3423 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3424 return par.asString(cur.pos(), end,
3427 } else if (cur.inMathed()) {
3428 CursorSlice cs = cur.top();
3429 MathData md = cs.cell();
3430 MathData::const_iterator it_end =
3431 (( len == -1 || cs.pos() + len > int(md.size()))
3433 : md.begin() + cs.pos() + len );
3435 for (MathData::const_iterator it = md.begin() + cs.pos();
3438 docstring s = asString(md2);
3439 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3442 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3447 /** Computes the LaTeX export of buf starting from cur and ending len positions
3448 * after cur, if len is positive, or at the paragraph or innermost inset end
3451 docstring latexifyFromCursor(DocIterator const & cur, int len)
3454 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3455 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3456 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3458 Buffer const & buf = *cur.buffer();
3460 odocstringstream ods;
3462 //OutputParams runparams(&buf.params().encoding());
3463 OutputParams runparams(encodings.fromLyXName("utf8"));
3464 runparams.nice = false;
3465 runparams.flavor = Flavor::XeTeX;
3466 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3467 // No side effect of file copying and image conversion
3468 runparams.dryrun = true;
3469 if (ignoreFormats.getDeleted()) {
3470 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3473 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3476 if (cur.inTexted()) {
3477 // @TODO what about searching beyond/across paragraph breaks ?
3478 pos_type endpos = cur.paragraph().size();
3479 if (len != -1 && endpos > cur.pos() + len)
3480 endpos = cur.pos() + len;
3481 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3482 string(), cur.pos(), endpos);
3483 string s = lyx::to_utf8(ods.str());
3484 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3485 return(lyx::from_utf8(s));
3486 } else if (cur.inMathed()) {
3487 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3488 for (int s = cur.depth() - 1; s >= 0; --s) {
3489 CursorSlice const & cs = cur[s];
3490 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3491 TeXMathStream ws(os);
3492 cs.asInsetMath()->asHullInset()->header_write(ws);
3497 CursorSlice const & cs = cur.top();
3498 MathData md = cs.cell();
3499 MathData::const_iterator it_end =
3500 ((len == -1 || cs.pos() + len > int(md.size()))
3502 : md.begin() + cs.pos() + len);
3504 for (MathData::const_iterator it = md.begin() + cs.pos();
3508 ods << asString(md2);
3509 // Retrieve the math environment type, and add '$' or '$]'
3510 // or others (\end{equation}) accordingly
3511 for (int s = cur.depth() - 1; s >= 0; --s) {
3512 CursorSlice const & cs2 = cur[s];
3513 InsetMath * inset = cs2.asInsetMath();
3514 if (inset && inset->asHullInset()) {
3515 TeXMathStream ws(os);
3516 inset->asHullInset()->footer_write(ws);
3520 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3522 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3527 #if defined(ResultsDebug)
3529 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3531 LYXERR0( "from:\t\t\t" << from);
3533 if (mres.pos_len > 0) {
3535 status = "FINALSEARCH";
3538 if (mres.match_len > 0) {
3539 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3540 status = "Good Match";
3542 status = "Matched in";
3545 status = "MissedSearch";
3548 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3549 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3550 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3551 if ((mres.pos > 0) || (mres.match_prefix > 0))
3552 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3553 for (size_t i = 0; i < mres.result.size(); i++)
3554 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3556 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3558 #define displayMres(s, txt, cur)
3561 /** Finalize an advanced find operation, advancing the cursor to the innermost
3562 ** position that matches, plus computing the length of the matching text to
3564 ** Return the cur.pos() difference between start and end of found match
3566 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3568 // Search the foremost position that matches (avoids find of entire math
3569 // inset when match at start of it)
3570 DocIterator old_cur(cur.buffer());
3572 static MatchResult fail = MatchResult();
3573 MatchResult max_match;
3574 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3575 // Happens with e.g. hyperlinks
3576 // either one sees "http://www.bla.bla" or nothing
3577 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3578 // and although we search for only 3 chars, we find the whole hyperlink inset
3579 bool at_begin = (expected.match_prefix == 0);
3580 if (!match.opt.forward && match.opt.ignoreformat) {
3581 if (expected.pos > 0)
3584 LASSERT(at_begin, /**/);
3585 if (expected.match_len > 0 && at_begin) {
3586 // Search for deepest match
3588 max_match = expected;
3590 size_t d = cur.depth();
3594 if (cur.depth() < d)
3596 if (cur.depth() == d)
3599 while (cur && cur.depth() > lastd) {
3600 lastd = cur.depth();
3601 mres = match(cur, -1, at_begin);
3602 displayMres(mres, "Checking innermost", cur);
3603 if (mres.match_len > 0)
3608 if (mres.match_len < expected.match_len)
3616 // (expected.match_len <= 0)
3617 mres = match(cur); /* match valid only if not searching whole words */
3618 displayMres(mres, "Start with negative match", cur);
3621 if (max_match.match_len <= 0) return fail;
3622 LYXERR(Debug::FIND, "Ok");
3624 // Compute the match length
3626 if (cur.pos() + len > cur.lastpos())
3629 LASSERT(match.use_regexp, /**/);
3632 int maxl = cur.lastpos() - cur.pos();
3633 // Greedy behaviour while matching regexps
3634 while (maxl > minl) {
3636 mres2 = match(cur, len, at_begin);
3637 displayMres(mres2, "Finalize loop", cur);
3638 int actual_match_len = mres2.match_len;
3639 if (actual_match_len >= max_match.match_len) {
3640 // actual_match_len > max_match _can_ happen,
3641 // if the search area splits
3642 // some following word so that the regex
3643 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3645 // This means, the len value is too big
3646 actual_match_len = max_match.match_len;
3648 max_match.match_len = actual_match_len;
3650 if (maxl - minl < 4)
3651 len = (int)((maxl + minl)/2);
3653 len = (int)(minl + (maxl - minl + 3)/4);
3656 // (actual_match_len < max_match.match_len)
3658 len = (int)((maxl + minl)/2);
3663 // Search for real start of matched characters
3665 MatchResult actual_match;
3668 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3669 if (cur.depth() < old_cur.depth()) {
3671 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3674 if (cur.pos() != old_cur.pos()) {
3675 // OK, forwarded 1 pos in actual inset
3676 actual_match = match(cur, len-1, at_begin);
3677 if (actual_match.match_len == max_match.match_len) {
3678 // Ha, got it! The shorter selection has the same match length
3681 max_match = actual_match;
3684 // OK, the shorter selection matches less chars, revert to previous value
3690 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3691 actual_match = match(cur, len, at_begin);
3692 if (actual_match.match_len == max_match.match_len) {
3694 max_match = actual_match;
3701 max_match.pos_len = len;
3702 displayMres(max_match, "SEARCH RESULT", cur)
3709 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3713 bool repeat = false;
3714 DocIterator orig_cur; // to be used if repeat not successful
3715 MatchResult orig_mres;
3716 while (!theApp()->longOperationCancelled() && cur) {
3717 //(void) findAdvForwardInnermost(cur);
3718 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3719 MatchResult mres = match(cur, -1, false);
3720 string msg = "Starting";
3723 displayMres(mres, msg + " findForwardAdv", cur)
3724 int match_len = mres.match_len;
3725 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3726 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3729 if (match_len <= 0) {
3730 // This should exit nested insets, if any, or otherwise undefine the currsor.
3731 cur.pos() = cur.lastpos();
3732 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3735 else { // match_len > 0
3736 // Try to find the begin of searched string
3738 int firstInvalid = cur.lastpos() - cur.pos();
3740 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3741 int incrcur = (firstInvalid + 1 )*3/4;
3742 if (incrcur < incrmatch)
3743 increment = incrcur;
3745 increment = incrmatch;
3749 LYXERR(Debug::FIND, "Set increment to " << increment);
3750 while (increment > 0) {
3751 DocIterator old_cur = cur;
3752 if (cur.pos() + increment >= cur.lastpos()) {
3756 cur.pos() = cur.pos() + increment;
3757 MatchResult mres2 = match(cur, -1, false);
3758 displayMres(mres2, "findForwardAdv loop", cur)
3759 switch (interpretMatch(mres, mres2)) {
3760 case MatchResult::newIsTooFar:
3761 // behind the expected match
3762 firstInvalid = increment;
3766 case MatchResult::newIsBetter:
3767 // not reached yet, but cur.pos()+increment is bettert
3769 firstInvalid -= increment;
3770 if (increment > firstInvalid*3/4)
3771 increment = firstInvalid*3/4;
3772 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3773 if (increment >= mres2.match_prefix)
3774 increment = (mres2.match_prefix+1)*3/4;
3779 // Handle not like MatchResult::newIsTooFar
3780 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3782 increment = increment*3/4;
3787 if (mres.match_len > 0) {
3788 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3789 // The match seems to indicate some deeper level
3798 // should never be reached.
3802 // LYXERR0("Leaving first loop");
3803 LYXERR(Debug::FIND, "Finalizing 1");
3804 MatchResult found_match = findAdvFinalize(cur, match, mres);
3805 if (found_match.match_len > 0) {
3806 LASSERT(found_match.pos_len > 0, /**/);
3807 match.FillResults(found_match);
3808 return found_match.pos_len;
3811 // try next possible match
3822 /// Find the most backward consecutive match within same paragraph while searching backwards.
3823 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3825 DocIterator cur_begin = cur;
3826 cur_begin.pos() = 0;
3827 DocIterator tmp_cur = cur;
3828 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3829 Inset & inset = cur.inset();
3830 for (; cur != cur_begin; cur.backwardPos()) {
3831 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3832 DocIterator new_cur = cur;
3833 new_cur.backwardPos();
3834 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3836 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3837 if (new_mr.match_len == mr.match_len)
3841 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3847 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3851 // Backup of original position
3852 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3853 if (cur == cur_begin)
3856 DocIterator cur_orig(cur);
3857 bool pit_changed = false;
3860 MatchResult found_match = match(cur, -1, false);
3862 if (found_match.match_len > 0) {
3864 cur.pos() = cur.lastpos();
3866 cur.pos() = cur_orig.pos();
3867 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3868 DocIterator cur_prev_iter;
3870 found_match = match(cur);
3871 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3872 << (found_match.match_len > 0) << ", cur: " << cur);
3873 if (found_match.match_len > 0) {
3874 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3875 if (found_mr.pos_len > 0) {
3876 match.FillResults(found_mr);
3877 return found_mr.pos_len;
3881 // Stop if begin of document reached
3882 if (cur == cur_begin)
3884 cur_prev_iter = cur;
3888 if (cur == cur_begin)
3895 } while (!theApp()->longOperationCancelled());
3903 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3904 DocIterator const & cur, int len)
3906 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3908 if (!opt.ignoreformat)
3909 return latexifyFromCursor(cur, len);
3911 return stringifyFromCursor(cur, len);
3915 FindAndReplaceOptions::FindAndReplaceOptions(
3916 docstring const & _find_buf_name, bool _casesensitive,
3917 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3918 docstring const & _repl_buf_name, bool _keep_case,
3919 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3920 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3921 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3922 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3930 /** Check if 'len' letters following cursor are all non-lowercase */
3931 static bool allNonLowercase(Cursor const & cur, int len)
3933 pos_type beg_pos = cur.selectionBegin().pos();
3934 pos_type end_pos = cur.selectionBegin().pos() + len;
3935 if (len > cur.lastpos() + 1 - beg_pos) {
3936 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3937 len = cur.lastpos() + 1 - beg_pos;
3938 end_pos = beg_pos + len;
3940 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3941 if (isLowerCase(cur.paragraph().getChar(pos)))
3947 /** Check if first letter is upper case and second one is lower case */
3948 static bool firstUppercase(Cursor const & cur)
3951 pos_type pos = cur.selectionBegin().pos();
3952 if (pos >= cur.lastpos() - 1) {
3953 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3956 ch1 = cur.paragraph().getChar(pos);
3957 ch2 = cur.paragraph().getChar(pos + 1);
3958 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3959 LYXERR(Debug::FIND, "firstUppercase(): "
3960 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3961 << ch2 << "(" << char(ch2) << ")"
3962 << ", result=" << result << ", cur=" << cur);
3967 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3969 ** \fixme What to do with possible further paragraphs in replace buffer ?
3971 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3973 ParagraphList::iterator pit = buffer.paragraphs().begin();
3974 LASSERT(!pit->empty(), /**/);
3975 pos_type right = pos_type(1);
3976 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3977 right = pit->size();
3978 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3982 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3984 // Should replace the string "$" + std::to_string(matchnum) with replacement
3985 // if the char '$' is not prefixed with odd number of char '\\'
3986 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3990 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3992 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3994 int num = stoi(sub.str(3), nullptr, 10);
3995 if (num >= maxmatchnum)
3997 if (lastpos < (size_t) sub.position(2))
3998 s += t.substr(lastpos, sub.position(2) - lastpos);
3999 s += replacements[num];
4000 lastpos = sub.position(2) + sub.length(2);
4004 else if (lastpos < t.length())
4005 s += t.substr(lastpos, t.length() - lastpos);
4011 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4013 Cursor & cur = bv->cursor();
4014 if (opt.repl_buf_name.empty()
4015 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4016 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4019 DocIterator sel_beg = cur.selectionBegin();
4020 DocIterator sel_end = cur.selectionEnd();
4021 if (&sel_beg.inset() != &sel_end.inset()
4022 || sel_beg.pit() != sel_end.pit()
4023 || sel_beg.idx() != sel_end.idx())
4025 int sel_len = sel_end.pos() - sel_beg.pos();
4026 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4027 << ", sel_len: " << sel_len << endl);
4030 LASSERT(sel_len > 0, return 0);
4032 if (!matchAdv(sel_beg, sel_len).match_len)
4035 // Build a copy of the replace buffer, adapted to the KeepCase option
4036 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4038 repl_buffer_orig.write(oss);
4039 string lyx = oss.str();
4040 if (matchAdv.valid_matches > 0) {
4041 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4043 Buffer repl_buffer("", false);
4044 repl_buffer.setUnnamed(true);
4045 LASSERT(repl_buffer.readString(lyx), return 0);
4046 if (opt.keep_case && sel_len >= 2) {
4047 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4048 if (cur.inTexted()) {
4049 if (firstUppercase(cur))
4050 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4051 else if (allNonLowercase(cur, sel_len))
4052 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4055 cap::cutSelection(cur, false);
4056 if (cur.inTexted()) {
4057 repl_buffer.changeLanguage(
4058 repl_buffer.language(),
4059 cur.getFont().language());
4060 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4061 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4062 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4063 repl_buffer.params().documentClassPtr(),
4064 repl_buffer.params().authors(),
4065 bv->buffer().errorList("Paste"));
4066 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4067 sel_len = repl_buffer.paragraphs().begin()->size();
4068 } else if (cur.inMathed()) {
4069 odocstringstream ods;
4071 // OutputParams runparams(&repl_buffer.params().encoding());
4072 OutputParams runparams(encodings.fromLyXName("utf8"));
4073 runparams.nice = false;
4074 runparams.flavor = Flavor::XeTeX;
4075 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4076 runparams.dryrun = true;
4077 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4078 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4079 docstring repl_latex = ods.str();
4080 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4082 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4083 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4084 repl_latex = from_utf8(s);
4085 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4086 MathData ar(cur.buffer());
4087 asArray(repl_latex, ar, Parse::NORMAL);
4089 sel_len = ar.size();
4090 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4092 if (cur.pos() >= sel_len)
4093 cur.pos() -= sel_len;
4096 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4097 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4098 bv->processUpdateFlags(Update::Force);
4103 /// Perform a FindAdv operation.
4104 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4109 // e.g., when invoking word-findadv from mini-buffer wither with
4110 // wrong options syntax or before ever opening advanced F&R pane
4111 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4115 MatchStringAdv matchAdv(bv->buffer(), opt);
4117 if (!matchAdv.regexIsValid) {
4118 bv->message(lyx::from_utf8(matchAdv.regexError));
4122 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4124 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4125 num_replaced += findAdvReplace(bv, opt, matchAdv);
4128 pos_len = findForwardAdv(cur, matchAdv);
4130 pos_len = findBackwardsAdv(cur, matchAdv);
4131 } catch (exception & ex) {
4132 bv->message(from_utf8(ex.what()));
4137 if (num_replaced > 0) {
4138 switch (num_replaced)
4141 bv->message(_("One match has been replaced."));
4144 bv->message(_("Two matches have been replaced."));
4147 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4153 bv->message(_("Match not found."));
4158 if (num_replaced > 0)
4159 bv->message(_("Match has been replaced."));
4161 bv->message(_("Match found."));
4163 if (cur.pos() + pos_len > cur.lastpos()) {
4164 // Prevent crash in bv->putSelectionAt()
4165 // Should never happen, maybe LASSERT() here?
4166 pos_len = cur.lastpos() - cur.pos();
4168 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4169 bv->putSelectionAt(cur, pos_len, !opt.forward);
4175 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4177 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4178 << opt.casesensitive << ' '
4179 << opt.matchword << ' '
4180 << opt.forward << ' '
4181 << opt.expandmacros << ' '
4182 << opt.ignoreformat << ' '
4183 << opt.replace_all << ' '
4184 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4185 << opt.keep_case << ' '
4186 << int(opt.scope) << ' '
4189 LYXERR(Debug::FIND, "built: " << os.str());
4195 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4197 // LYXERR(Debug::FIND, "parsing");
4201 while (line != "EOSS") {
4205 if (is.eof()) // Tolerate malformed request
4209 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4210 opt.find_buf_name = from_utf8(s);
4211 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4212 is.get(); // Waste space before replace string
4215 while (line != "EOSS") {
4219 if (is.eof()) // Tolerate malformed request
4223 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4224 opt.repl_buf_name = from_utf8(s);
4225 is >> opt.keep_case;
4228 opt.scope = FindAndReplaceOptions::SearchScope(i);
4230 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4233 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4234 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4235 << opt.scope << ' ' << opt.restr);