3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathData.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/FileName.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
53 #include <unordered_map>
56 //#define ResultsDebug
57 #define USE_QT_FOR_SEARCH
58 #if defined(USE_QT_FOR_SEARCH)
59 #include <QtCore> // sets QT_VERSION
60 #if (QT_VERSION >= 0x050000)
61 #include <QRegularExpression>
71 using namespace lyx::support;
75 typedef unordered_map<string, string> AccentsMap;
76 typedef unordered_map<string,string>::const_iterator AccentsIterator;
77 static AccentsMap accents = unordered_map<string, string>();
79 // Helper class for deciding what should be ignored
83 IgnoreFormats() = default;
85 bool getFamily() const { return ignoreFamily_; }
87 bool getSeries() const { return ignoreSeries_; }
89 bool getShape() const { return ignoreShape_; }
91 bool getUnderline() const { return ignoreUnderline_; }
93 bool getMarkUp() const { return ignoreMarkUp_; }
95 bool getStrikeOut() const { return ignoreStrikeOut_; }
97 bool getSectioning() const { return ignoreSectioning_; }
99 bool getFrontMatter() const { return ignoreFrontMatter_; }
101 bool getColor() const { return ignoreColor_; }
103 bool getLanguage() const { return ignoreLanguage_; }
105 bool getDeleted() const { return ignoreDeleted_; }
107 void setIgnoreDeleted(bool value);
109 void setIgnoreFormat(string const & type, bool value);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreUnderline_ = false;
121 bool ignoreMarkUp_ = false;
123 bool ignoreStrikeOut_ = false;
125 bool ignoreSectioning_ = false;
127 bool ignoreFrontMatter_ = false;
129 bool ignoreColor_ = false;
131 bool ignoreLanguage_ = false;
133 bool ignoreDeleted_ = true;
136 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
138 if (type == "color") {
139 ignoreColor_ = value;
141 else if (type == "language") {
142 ignoreLanguage_ = value;
144 else if (type == "sectioning") {
145 ignoreSectioning_ = value;
146 ignoreFrontMatter_ = value;
148 else if (type == "font") {
149 ignoreSeries_ = value;
150 ignoreShape_ = value;
151 ignoreFamily_ = value;
153 else if (type == "series") {
154 ignoreSeries_ = value;
156 else if (type == "shape") {
157 ignoreShape_ = value;
159 else if (type == "family") {
160 ignoreFamily_ = value;
162 else if (type == "markup") {
163 ignoreMarkUp_ = value;
165 else if (type == "underline") {
166 ignoreUnderline_ = value;
168 else if (type == "strike") {
169 ignoreStrikeOut_ = value;
171 else if (type == "deleted") {
172 ignoreDeleted_ = value;
176 // The global variable that can be changed from outside
177 IgnoreFormats ignoreFormats;
180 void setIgnoreFormat(string const & type, bool value)
182 ignoreFormats.setIgnoreFormat(type, value);
188 bool parse_bool(docstring & howto)
193 howto = split(howto, var, ' ');
201 MatchString(docstring const & s, bool cs, bool mw)
202 : str(s), case_sens(cs), whole_words(mw)
205 // returns true if the specified string is at the specified position
206 // del specifies whether deleted strings in ct mode will be considered
207 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
209 return par.find(str, case_sens, whole_words, pos, del);
217 // match whole words only
222 int findForward(DocIterator & cur, MatchString const & match,
223 bool find_del = true)
225 for (; cur; cur.forwardChar())
226 if (cur.inTexted()) {
227 int len = match(cur.paragraph(), cur.pos(), find_del);
235 int findBackwards(DocIterator & cur, MatchString const & match,
236 bool find_del = true)
240 if (cur.inTexted()) {
241 int len = match(cur.paragraph(), cur.pos(), find_del);
250 bool searchAllowed(docstring const & str)
253 frontend::Alert::error(_("Search error"), _("Search string is empty"));
260 bool findOne(BufferView * bv, docstring const & searchstr,
261 bool case_sens, bool whole, bool forward,
262 bool find_del = true, bool check_wrap = false)
264 if (!searchAllowed(searchstr))
267 DocIterator cur = forward
268 ? bv->cursor().selectionEnd()
269 : bv->cursor().selectionBegin();
271 MatchString const match(searchstr, case_sens, whole);
273 int match_len = forward
274 ? findForward(cur, match, find_del)
275 : findBackwards(cur, match, find_del);
278 bv->putSelectionAt(cur, match_len, !forward);
279 else if (check_wrap) {
280 DocIterator cur_orig(bv->cursor());
283 q = _("End of file reached while searching forward.\n"
284 "Continue searching from the beginning?");
286 q = _("Beginning of file reached while searching backward.\n"
287 "Continue searching from the end?");
288 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
289 q, 0, 1, _("&Yes"), _("&No"));
290 if (wrap_answer == 0) {
292 bv->cursor().clear();
293 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
295 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
296 bv->cursor().backwardPos();
298 bv->clearSelection();
299 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
302 bv->cursor().setCursor(cur_orig);
306 return match_len > 0;
310 int replaceAll(BufferView * bv,
311 docstring const & searchstr, docstring const & replacestr,
312 bool case_sens, bool whole)
314 Buffer & buf = bv->buffer();
316 if (!searchAllowed(searchstr) || buf.isReadonly())
319 DocIterator cur_orig(bv->cursor());
321 MatchString const match(searchstr, case_sens, whole);
324 int const rsize = replacestr.size();
325 int const ssize = searchstr.size();
328 cur.setCursor(doc_iterator_begin(&buf));
329 int match_len = findForward(cur, match, false);
330 while (match_len > 0) {
331 // Backup current cursor position and font.
332 pos_type const pos = cur.pos();
333 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
335 int striked = ssize -
336 cur.paragraph().eraseChars(pos, pos + match_len,
337 buf.params().track_changes);
338 cur.paragraph().insert(pos, replacestr, font,
339 Change(buf.params().track_changes
341 : Change::UNCHANGED));
342 for (int i = 0; i < rsize + striked; ++i)
345 match_len = findForward(cur, match, false);
348 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
350 cur_orig.fixIfBroken();
351 bv->setCursor(cur_orig);
357 // the idea here is that we are going to replace the string that
358 // is selected IF it is the search string.
359 // if there is a selection, but it is not the search string, then
360 // we basically ignore it. (FIXME We ought to replace only within
362 // if there is no selection, then:
363 // (i) if some search string has been provided, then we find it.
364 // (think of how the dialog works when you hit "replace" the
366 // (ii) if no search string has been provided, then we treat the
367 // word the cursor is in as the search string. (why? i have no
368 // idea.) but this only works in text?
370 // returns the number of replacements made (one, if any) and
371 // whether anything at all was done.
372 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
373 docstring const & replacestr, bool case_sens,
374 bool whole, bool forward, bool findnext)
376 Cursor & cur = bv->cursor();
377 if (!cur.selection()) {
378 // no selection, non-empty search string: find it
379 if (!searchstr.empty()) {
380 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
381 return make_pair(found, 0);
383 // empty search string
386 return make_pair(false, 0);
387 // select current word and treat it as the search string.
388 // This causes a minor bug as undo will restore this selection,
389 // which the user did not create (#8986).
390 cur.innerText()->selectWord(cur, WHOLE_WORD);
391 searchstr = cur.selectionAsString(false, true);
394 // if we still don't have a search string, report the error
396 if (!searchAllowed(searchstr))
397 return make_pair(false, 0);
399 bool have_selection = cur.selection();
400 docstring const selected = cur.selectionAsString(false, true);
403 ? searchstr == selected
404 : compare_no_case(searchstr, selected) == 0;
406 // no selection or current selection is not search word:
407 // just find the search word
408 if (!have_selection || !match) {
409 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
410 return make_pair(found, 0);
413 // we're now actually ready to replace. if the buffer is
414 // read-only, we can't, though.
415 if (bv->buffer().isReadonly())
416 return make_pair(false, 0);
418 cap::replaceSelectionWithString(cur, replacestr);
420 cur.pos() += replacestr.length();
421 LASSERT(cur.pos() <= cur.lastpos(),
422 cur.pos() = cur.lastpos());
425 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
427 return make_pair(true, 1);
433 docstring const find2string(docstring const & search,
434 bool casesensitive, bool matchword, bool forward)
438 << int(casesensitive) << ' '
439 << int(matchword) << ' '
445 docstring const replace2string(docstring const & replace,
446 docstring const & search,
447 bool casesensitive, bool matchword,
448 bool all, bool forward, bool findnext)
451 ss << replace << '\n'
453 << int(casesensitive) << ' '
454 << int(matchword) << ' '
456 << int(forward) << ' '
462 bool lyxfind(BufferView * bv, FuncRequest const & ev)
464 if (!bv || ev.action() != LFUN_WORD_FIND)
467 //lyxerr << "find called, cmd: " << ev << endl;
469 // data is of the form
471 // <casesensitive> <matchword> <forward>"
473 docstring howto = split(ev.argument(), search, '\n');
475 bool casesensitive = parse_bool(howto);
476 bool matchword = parse_bool(howto);
477 bool forward = parse_bool(howto);
479 return findOne(bv, search, casesensitive, matchword, forward, false, true);
483 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
485 if (!bv || ev.action() != LFUN_WORD_REPLACE)
488 // data is of the form
491 // <casesensitive> <matchword> <all> <forward> <findnext>"
494 docstring howto = split(ev.argument(), rplc, '\n');
495 howto = split(howto, search, '\n');
497 bool casesensitive = parse_bool(howto);
498 bool matchword = parse_bool(howto);
499 bool all = parse_bool(howto);
500 bool forward = parse_bool(howto);
501 bool findnext = howto.empty() ? true : parse_bool(howto);
505 int replace_count = 0;
507 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
508 update = replace_count > 0;
511 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
513 replace_count = rv.second;
516 Buffer const & buf = bv->buffer();
518 // emit message signal.
519 buf.message(_("String not found."));
521 if (replace_count == 0) {
522 buf.message(_("String found."));
523 } else if (replace_count == 1) {
524 buf.message(_("String has been replaced."));
526 docstring const str =
527 bformat(_("%1$d strings have been replaced."), replace_count);
535 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
537 for (; cur; cur.forwardPos())
538 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
542 DocIterator cur_orig(bv->cursor());
543 docstring q = _("End of file reached while searching forward.\n"
544 "Continue searching from the beginning?");
545 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
546 q, 0, 1, _("&Yes"), _("&No"));
547 if (wrap_answer == 0) {
548 bv->cursor().clear();
549 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
550 bv->clearSelection();
551 cur.setCursor(bv->cursor().selectionBegin());
552 if (findNextChange(bv, cur, false))
555 bv->cursor().setCursor(cur_orig);
562 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
564 for (cur.backwardPos(); cur; cur.backwardPos()) {
565 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
570 DocIterator cur_orig(bv->cursor());
571 docstring q = _("Beginning of file reached while searching backward.\n"
572 "Continue searching from the end?");
573 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
574 q, 0, 1, _("&Yes"), _("&No"));
575 if (wrap_answer == 0) {
576 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
577 bv->cursor().backwardPos();
578 bv->clearSelection();
579 cur.setCursor(bv->cursor().selectionBegin());
580 if (findPreviousChange(bv, cur, false))
583 bv->cursor().setCursor(cur_orig);
590 bool selectChange(Cursor & cur, bool forward)
592 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
594 Change ch = cur.paragraph().lookupChange(cur.pos());
596 CursorSlice tip1 = cur.top();
597 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
598 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
599 if (!ch2.isSimilarTo(ch))
602 CursorSlice tip2 = cur.top();
603 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
605 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
606 if (!ch2.isSimilarTo(ch)) {
607 // take a step forward to correctly set the selection
615 cur.bv().mouseSetCursor(cur, false);
617 cur.bv().mouseSetCursor(cur, true);
625 bool findChange(BufferView * bv, bool forward)
628 cur.setCursor(forward ? bv->cursor().selectionEnd()
629 : bv->cursor().selectionBegin());
630 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
631 return selectChange(cur, forward);
636 bool findNextChange(BufferView * bv)
638 return findChange(bv, true);
642 bool findPreviousChange(BufferView * bv)
644 return findChange(bv, false);
651 typedef vector<pair<string, string> > Escapes;
653 string string2regex(string in)
655 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
656 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
661 while (fl_pos < temp.size()) {
662 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
663 if (fl_pos == string::npos)
666 temp2 += temp.substr(lastpos, fl_pos - lastpos);
672 if (lastpos < temp.size()) {
673 temp2 += temp.substr(lastpos, temp.size() - lastpos);
678 string correctRegex(string t, bool withformat)
680 /* Convert \backslash => \
681 * and \{, \}, \[, \] => {, }, [, ]
684 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
687 bool backslashed = false;
688 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
691 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
695 if (sub.str(4) == "backslash") {
698 // transforms '\backslash \{' into '\{'
700 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
701 if ((next == "\\{") || (next == "\\}")) {
707 else if (sub.str(4) == "mathcircumflex")
709 else if (backslashed) {
711 if (withformat && (sub.str(3) == "{"))
712 replace = accents["braceleft"];
713 else if (withformat && (sub.str(3) == "}"))
714 replace = accents["braceright"];
716 // else part should not exist
721 replace = sub.str(3);
723 if (lastpos < (size_t) sub.position(2))
724 s += t.substr(lastpos, sub.position(2) - lastpos);
726 lastpos = sub.position(2) + sub.length(2);
730 else if (lastpos < t.length())
731 s += t.substr(lastpos, t.length() - lastpos);
735 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
736 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
737 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
738 string escape_for_regex(string s, bool withformat)
742 while (lastpos < s.size()) {
743 size_t regex_pos = s.find("\\regexp{", lastpos);
744 if (regex_pos == string::npos) {
745 regex_pos = s.size();
747 if (regex_pos > lastpos) {
748 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
750 if (lastpos == s.size())
753 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
754 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
755 lastpos = end_pos + 13;
761 /// Wrapper for lyx::regex_replace with simpler interface
762 bool regex_replace(string const & s, string & t, string const & searchstr,
763 string const & replacestr)
765 regex e(searchstr, regex_constants::ECMAScript);
767 ostream_iterator<char, char> it(oss);
768 regex_replace(it, s.begin(), s.end(), e, replacestr);
769 // tolerate t and s be references to the same variable
770 bool rv = (s != oss.str());
789 vector <string> result = vector <string>();
790 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
793 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
795 if (newres.match2end < oldres.match2end)
796 return MatchResult::newIsTooFar;
797 if (newres.match_len < oldres.match_len)
798 return MatchResult::newIsTooFar;
800 if (newres.match_len == oldres.match_len) {
801 if (newres.match2end == oldres.match2end)
802 return MatchResult::newIsBetter;
804 return MatchResult::newIsInvalid;
807 /** The class performing a match between a position in the document and the FindAdvOptions.
810 class MatchStringAdv {
812 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
814 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
815 ** constructor as opt.search, under the opt.* options settings.
818 ** If set, then match is searched only against beginning of text starting at cur.
819 ** If unset, then match is searched anywhere in text starting at cur.
822 ** The length of the matching text, or zero if no match was found.
824 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
833 /// first buffer on which search was started
834 lyx::Buffer * const p_first_buf;
836 FindAndReplaceOptions const & opt;
839 /// Auxiliary find method (does not account for opt.matchword)
840 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
841 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
843 /** Normalize a stringified or latexified LyX paragraph.
847 ** <li>if search is not casesensitive, then lowercase the string;
848 ** <li>remove any newline at begin or end of the string;
849 ** <li>replace any newline in the middle of the string with a simple space;
850 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
853 ** @todo Normalization should also expand macros, if the corresponding
854 ** search option was checked.
856 string normalize(docstring const & s) const;
857 // normalized string to search
858 string par_as_string;
859 // regular expression to use for searching
860 // regexp2 is same as regexp, but prefixed with a ".*?"
862 QRegularExpression regexp;
863 QRegularExpression regexp2;
868 // leading format material as string
869 string lead_as_string;
870 // par_as_string after removal of lead_as_string
871 string par_as_string_nolead;
872 // unmatched open braces in the search string/regexp
874 // number of (.*?) subexpressions added at end of search regexp for closing
875 // environments, math mode, styles, etc...
878 // Are we searching with regular expressions ?
880 static int valid_matches;
881 static vector <string> matches;
882 void FillResults(MatchResult &found_mr);
885 int MatchStringAdv::valid_matches = 0;
886 vector <string> MatchStringAdv::matches = vector <string>(10);
888 void MatchStringAdv::FillResults(MatchResult &found_mr)
890 if (found_mr.match_len > 0) {
891 valid_matches = found_mr.result.size();
892 for (size_t i = 0; i < found_mr.result.size(); i++)
893 matches[i] = found_mr.result[i];
899 static docstring buffer_to_latex(Buffer & buffer)
901 //OutputParams runparams(&buffer.params().encoding());
902 OutputParams runparams(encodings.fromLyXName("utf8"));
903 odocstringstream ods;
905 runparams.nice = true;
906 runparams.flavor = Flavor::XeTeX;
907 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
908 // No side effect of file copying and image conversion
909 runparams.dryrun = true;
910 if (ignoreFormats.getDeleted())
911 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
913 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
914 pit_type const endpit = buffer.paragraphs().size();
915 for (pit_type pit = 0; pit != endpit; ++pit) {
916 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
917 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
923 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
926 if (!opt.ignoreformat) {
927 str = buffer_to_latex(buffer);
929 // OutputParams runparams(&buffer.params().encoding());
930 OutputParams runparams(encodings.fromLyXName("utf8"));
931 runparams.nice = true;
932 runparams.flavor = Flavor::XeTeX;
933 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
934 runparams.dryrun = true;
935 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
936 if (ignoreFormats.getDeleted()) {
937 option |= AS_STR_SKIPDELETE;
938 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
941 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
943 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
944 Paragraph const & par = buffer.paragraphs().at(pit);
945 LYXERR(Debug::FIND, "Adding to search string: '"
946 << par.asString(pos_type(0), par.size(),
950 str += par.asString(pos_type(0), par.size(),
954 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
955 string t = to_utf8(str);
956 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
963 /// Return separation pos between the leading material and the rest
964 static size_t identifyLeading(string const & s)
967 // @TODO Support \item[text]
968 // Kornel: Added textsl, textsf, textit, texttt and noun
969 // + allow to search for colored text too
970 while (regex_replace(t, t, "^\\\\(("
971 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
972 "lyxaddress|lyxrightaddress|"
973 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
974 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
975 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
976 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
977 || regex_replace(t, t, "^\\$", "")
978 || regex_replace(t, t, "^\\\\\\[", "")
979 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
980 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
982 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
987 * Given a latexified string, retrieve some handled features
988 * The features of the regex will later be compared with the features
989 * of the searched text. If the regex features are not a
990 * subset of the analized, then, in not format ignoring search
991 * we can early stop the search in the relevant inset.
993 typedef map<string, bool> Features;
995 static Features identifyFeatures(string const & s)
997 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
998 static regex const valid("^("
1000 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1001 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1002 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1003 "(u|uu)line|(s|x)out|uwave|"
1004 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1005 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1010 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1013 if (sub.str(1).compare("regexp") == 0) {
1017 string token = sub.str(1);
1019 if (regex_match(token, sub2, valid)) {
1027 if (sub.str(1).compare("endregexp") == 0) {
1037 * defines values features of a key "\\[a-z]+{"
1042 /* Char type with content discarded
1043 * like \hspace{1cm} */
1045 /* Char, like \backslash */
1047 /* replace starting backslash with '#' */
1049 /* \part, \section*, ... */
1051 /* title, author etc */
1053 /* \foreignlanguage{ngerman}, ... */
1056 * to discard language in content */
1059 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1061 /* fonts, colors, markups, ... */
1063 /* footnotesize, ... large, ...
1064 * Ignore all of them */
1067 /* inputencoding, ...
1068 * Discard also content, because they do not help in search */
1071 * like remove, but also all arguments */
1073 /* item, listitem */
1075 /* tex, latex, ... like isChar */
1077 /* like \lettrine[lines=5]{}{} */
1079 // like isStandard, but always remove head
1081 /* End of arguments marker for lettrine,
1082 * so that they can be ignored */
1085 KeyInfo() = default;
1086 KeyInfo(KeyType type, int parcount, bool disable)
1088 parenthesiscount(parcount),
1089 disabled(disable) {}
1090 KeyType keytype = invalid;
1092 int _tokensize = -1;
1093 int _tokenstart = -1;
1094 int _dataStart = -1;
1096 int parenthesiscount = 1;
1097 bool disabled = false;
1098 bool used = false; /* by pattern */
1103 Border(int l=0, int u=0) : low(l), upper(u) {};
1108 #define MAXOPENED 30
1110 bool isPatternString_;
1112 explicit Intervall(bool isPattern, string const & p) :
1113 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1114 hasTitle(false), langcount(0)
1122 static vector<Border> borders;
1123 int depts[MAXOPENED];
1124 int closes[MAXOPENED];
1125 int actualdeptindex;
1126 int previousNotIgnored(int) const;
1127 int nextNotIgnored(int) const;
1128 void handleOpenP(int i);
1129 void handleCloseP(int i, bool closingAllowed);
1130 void resetOpenedP(int openPos);
1131 void addIntervall(int upper);
1132 void addIntervall(int low, int upper); /* if explicit */
1133 void removeAccents();
1134 void setForDefaultLang(KeyInfo const & defLang) const;
1135 int findclosing(int start, int end, char up, char down, int repeat);
1136 void handleParentheses(int lastpos, bool closingAllowed);
1138 int langcount; // Number of disabled language specs up to current position in actual interval
1139 int isOpeningPar(int pos) const;
1141 void output(ostringstream &os, int lastpos);
1142 // string show(int lastpos);
1145 vector<Border> Intervall::borders = vector<Border>(30);
1147 int Intervall::isOpeningPar(int pos) const
1149 if ((pos < 0) || (size_t(pos) >= par.size()))
1151 if (par[pos] != '{')
1153 if (size_t(pos) + 2 >= par.size())
1155 if (par[pos+2] != '}')
1157 if (par[pos+1] == '[' || par[pos+1] == ']')
1162 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1164 // Enable the use of first token again
1165 if (ignoreidx >= 0) {
1166 int value = defLang._tokenstart + defLang._tokensize;
1172 if (borders[borderidx].low < value)
1173 borders[borderidx].low = value;
1174 if (borders[borderidx].upper < value)
1175 borders[borderidx].upper = value;
1180 static void checkDepthIndex(int val)
1182 static int maxdepthidx = MAXOPENED-2;
1183 static int lastmaxdepth = 0;
1184 if (val > lastmaxdepth) {
1185 LYXERR(Debug::INFO, "Depth reached " << val);
1188 if (val > maxdepthidx) {
1190 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1195 // Not needed, because borders are now dynamically expanded
1196 static void checkIgnoreIdx(int val)
1198 static int lastmaxignore = -1;
1199 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1200 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1201 lastmaxignore = val;
1207 * Expand the region of ignored parts of the input latex string
1208 * The region is only relevant in output()
1210 void Intervall::addIntervall(int low, int upper)
1213 if (low == upper) return;
1214 for (idx = ignoreidx+1; idx > 0; --idx) {
1215 if (low > borders[idx-1].upper) {
1219 Border br(low, upper);
1220 if (idx > ignoreidx) {
1221 if (borders.size() <= size_t(idx)) {
1222 borders.push_back(br);
1228 // checkIgnoreIdx(ignoreidx);
1232 // Expand only if one of the new bound is inside the interwall
1233 // We know here that br.low > borders[idx-1].upper
1234 if (br.upper < borders[idx].low) {
1235 // We have to insert at this pos
1236 if (size_t(ignoreidx+1) >= borders.size()) {
1237 borders.push_back(borders[ignoreidx]);
1240 borders[ignoreidx+1] = borders[ignoreidx];
1242 for (int i = ignoreidx; i > idx; --i) {
1243 borders[i] = borders[i-1];
1247 // checkIgnoreIdx(ignoreidx);
1250 // Here we know, that we are overlapping
1251 if (br.low > borders[idx].low)
1252 br.low = borders[idx].low;
1253 // check what has to be concatenated
1255 for (int i = idx; i <= ignoreidx; i++) {
1256 if (br.upper >= borders[i].low) {
1258 if (br.upper < borders[i].upper)
1259 br.upper = borders[i].upper;
1265 // count should be >= 1 here
1268 for (int i = idx + count; i <= ignoreidx; i++) {
1269 borders[i-count+1] = borders[i];
1271 ignoreidx -= count - 1;
1277 static void buildaccent(string n, string param, string values)
1281 const char delim = '|';
1282 while (getline(s, name, delim)) {
1284 for (char c : param) {
1285 string key = name + "{" + c + "}";
1286 // get the corresponding utf8-value
1287 if ((values[start] & 0xc0) != 0xc0) {
1288 // should not happen, utf8 encoding starts at least with 11xxxxxx
1289 // but value for '\dot{i}' is 'i', which is ascii
1290 if ((values[start] & 0x80) == 0) {
1292 accents[key] = values.substr(start, 1);
1293 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1298 for (int j = 1; ;j++) {
1299 if (start + j >= values.size()) {
1300 accents[key] = values.substr(start, j);
1301 start = values.size() - 1;
1304 else if ((values[start+j] & 0xc0) != 0x80) {
1305 // This is the first byte of following utf8 char
1306 accents[key] = values.substr(start, j);
1308 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1317 static string getutf8(unsigned uchar)
1320 string ret = string();
1322 if (uchar <= 0x7f) {
1323 c[maxc-1] = uchar & 0x7f;
1326 unsigned char rest = 0x40;
1327 unsigned char first = 0x80;
1329 for (int i = start; i >=0; --i) {
1331 c[i] = first + uchar;
1334 c[i] = 0x80 | (uchar & 0x3f);
1341 for (int i = 0; i < maxc; i++) {
1342 if (c[i] == 0) continue;
1348 static void buildAccentsMap()
1350 accents["imath"] = "ı";
1352 accents["jmath"] = "ȷ";
1353 accents["cdot"] = "·";
1354 accents["textasciicircum"] = "^";
1355 accents["mathcircumflex"] = "^";
1356 accents["sim"] = "~";
1357 accents["guillemotright"] = "»";
1358 accents["guillemotleft"] = "«";
1359 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1360 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1361 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1362 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1363 accents["negmedspace"] = getutf8(0xf0005);
1364 accents["thickspace"] = getutf8(0xf0006);
1365 accents["negthickspace"] = getutf8(0xf0007);
1366 accents["lyx"] = getutf8(0xf0010); // Used logos
1367 accents["LyX"] = getutf8(0xf0010);
1368 accents["tex"] = getutf8(0xf0011);
1369 accents["TeX"] = getutf8(0xf0011);
1370 accents["latex"] = getutf8(0xf0012);
1371 accents["LaTeX"] = getutf8(0xf0012);
1372 accents["latexe"] = getutf8(0xf0013);
1373 accents["LaTeXe"] = getutf8(0xf0013);
1374 accents["lyxarrow"] = getutf8(0xf0020);
1375 accents["braceleft"] = getutf8(0xf0030);
1376 accents["braceright"] = getutf8(0xf0031);
1377 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1378 accents["backslash LyX"] = getutf8(0xf0010);
1379 accents["backslash tex"] = getutf8(0xf0011);
1380 accents["backslash TeX"] = getutf8(0xf0011);
1381 accents["backslash latex"] = getutf8(0xf0012);
1382 accents["backslash LaTeX"] = getutf8(0xf0012);
1383 accents["backslash latexe"] = getutf8(0xf0013);
1384 accents["backslash LaTeXe"] = getutf8(0xf0013);
1385 accents["backslash lyxarrow"] = getutf8(0xf0020);
1386 accents["ddot{\\imath}"] = "ï";
1387 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1388 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1389 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1390 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1391 accents["acute{\\imath}"] = "í";
1392 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1393 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1394 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1395 buildaccent("mathring|r", "aAuUwy",
1397 accents["check{\\imath}"] = "ǐ";
1398 accents["check{\\jmath}"] = "ǰ";
1399 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1400 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1401 accents["hat{\\imath}"] = "î";
1402 accents["hat{\\jmath}"] = "ĵ";
1403 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1404 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1405 accents["bar{\\imath}"] = "ī";
1406 buildaccent("bar|=", "aAeEiIoOuUyY",
1407 "āĀēĒīĪōŌūŪȳȲ"); // macron
1408 accents["tilde{\\imath}"] = "ĩ";
1409 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1410 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1411 accents["breve{\\imath}"] = "ĭ";
1412 buildaccent("breve|u", "aAeEgGiIoOuU",
1413 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1414 accents["grave{\\imath}"] = "ì";
1415 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1416 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1417 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1418 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1419 buildaccent("ogonek|k", "AaEeIiUuOo",
1420 "ĄąĘęĮįŲųǪǫ"); // ogonek
1421 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1422 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1423 buildaccent("subring|textsubring", "Aa",
1425 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1426 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1427 buildaccent("subtilde|textsubtilde", "EeIiUu",
1428 "ḚḛḬḭṴṵ"); // subtilde
1429 accents["dgrave{\\imath}"] = "ȉ";
1430 accents["textdoublegrave{\\i}"] = "ȉ";
1431 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1432 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1433 accents["rcap{\\imath}"] = "ȉ";
1434 accents["textroundcap{\\i}"] = "ȉ";
1435 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1436 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1437 buildaccent("slashed", "oO",
1442 * Created accents in math or regexp environment
1443 * are macros, but we need the utf8 equivalent
1445 void Intervall::removeAccents()
1447 if (accents.empty())
1449 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1450 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1451 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|(brace|guillemot)(left|right)|textasciicircum|mathcircumflex|sim)(?![a-zA-Z]))");
1453 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1455 string key = sub.str(1);
1456 AccentsIterator it_ac = accents.find(key);
1457 if (it_ac != accents.end()) {
1458 string val = it_ac->second;
1459 size_t pos = sub.position(size_t(0));
1460 for (size_t i = 0; i < val.size(); i++) {
1461 par[pos+i] = val[i];
1463 // Remove possibly following space too
1464 if (par[pos+sub.str(0).size()] == ' ')
1465 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1467 addIntervall(pos+val.size(), pos + sub.str(0).size());
1468 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1469 // remove traces of any remaining chars
1474 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1479 void Intervall::handleOpenP(int i)
1482 depts[actualdeptindex] = i+1;
1483 closes[actualdeptindex] = -1;
1484 checkDepthIndex(actualdeptindex);
1487 void Intervall::handleCloseP(int i, bool closingAllowed)
1489 if (actualdeptindex <= 0) {
1490 if (! closingAllowed)
1491 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1492 // if we are at the very end
1493 addIntervall(i, i+1);
1496 closes[actualdeptindex] = i+1;
1501 void Intervall::resetOpenedP(int openPos)
1503 // Used as initializer for foreignlanguage entry
1504 actualdeptindex = 1;
1505 depts[1] = openPos+1;
1509 int Intervall::previousNotIgnored(int start) const
1511 int idx = 0; /* int intervalls */
1512 for (idx = ignoreidx; idx >= 0; --idx) {
1513 if (start > borders[idx].upper)
1515 if (start >= borders[idx].low)
1516 start = borders[idx].low-1;
1521 int Intervall::nextNotIgnored(int start) const
1523 int idx = 0; /* int intervalls */
1524 for (idx = 0; idx <= ignoreidx; idx++) {
1525 if (start < borders[idx].low)
1527 if (start < borders[idx].upper)
1528 start = borders[idx].upper;
1533 typedef unordered_map<string, KeyInfo> KeysMap;
1534 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1535 typedef vector< KeyInfo> Entries;
1536 static KeysMap keys = unordered_map<string, KeyInfo>();
1542 Intervall interval_;
1543 void buildKeys(bool);
1544 void buildEntries(bool);
1545 void makeKey(const string &, KeyInfo, bool isPatternString);
1546 void processRegion(int start, int region_end); /* remove {} parts */
1547 void removeHead(KeyInfo const &, int count=0);
1550 LatexInfo(string const & par, bool isPatternString)
1551 : entidx_(-1), interval_(isPatternString, par)
1553 buildKeys(isPatternString);
1554 entries_ = vector<KeyInfo>();
1555 buildEntries(isPatternString);
1559 if (entries_.empty()) {
1562 if (entries_[0].keytype == KeyInfo::isTitle) {
1563 interval_.hasTitle = true;
1564 if (! entries_[0].disabled) {
1565 interval_.titleValue = entries_[0].head;
1568 interval_.titleValue = "";
1570 removeHead(entries_[0]);
1571 if (entries_.size() > 1)
1580 if (int(entries_.size()) > entidx_) {
1587 bool setNextKey(int idx) {
1588 if ((idx == entidx_) && (entidx_ >= 0)) {
1595 int find(int start, KeyInfo::KeyType keytype) const {
1599 while (tmpIdx < int(entries_.size())) {
1600 if (entries_[tmpIdx].keytype == keytype)
1606 int process(ostringstream & os, KeyInfo const & actual);
1607 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1608 // string show(int lastpos) { return interval.show(lastpos);};
1609 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1610 KeyInfo &getKeyInfo(int keyinfo) {
1611 static KeyInfo invalidInfo = KeyInfo();
1612 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1615 return entries_[keyinfo];
1617 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1618 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1622 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1626 for (int i = start; i < end; i += 1 + skip) {
1630 if (c == '\\') skip = 1;
1634 else if (c == down) {
1637 if ((repeat <= 0) || (par[i+1] != up))
1655 vector<MathEntry> entries_;
1660 void insert(string const & wait, size_t start, size_t end) {
1661 MathEntry m = MathEntry();
1663 m.mathStart = start;
1665 m.mathSize = end - start;
1666 entries_.push_back(m);
1668 bool empty() const { return entries_.empty(); };
1669 size_t getEndPos() const {
1670 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1673 return entries_[actualIdx_].mathEnd;
1675 size_t getStartPos() const {
1676 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1677 return 100000; /* definitely enough? */
1679 return entries_[actualIdx_].mathStart;
1681 size_t getFirstPos() {
1683 return getStartPos();
1685 size_t getSize() const {
1686 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1689 return entries_[actualIdx_].mathSize;
1691 void incrEntry() { actualIdx_++; };
1694 void LatexInfo::buildEntries(bool isPatternString)
1696 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1697 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1698 static bool disableLanguageOverride = false;
1699 smatch sub, submath;
1700 bool evaluatingRegexp = false;
1702 bool evaluatingMath = false;
1703 bool evaluatingCode = false;
1705 bool evaluatingOptional = false;
1706 size_t optionalEnd = 0;
1709 bool math_end_waiting = false;
1710 size_t math_pos = 10000;
1712 static vector<string> usedText = vector<string>();
1714 interval_.removeAccents();
1716 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1718 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1719 // prefixed by odd count of '\\'
1722 if (math_end_waiting) {
1723 size_t pos = submath.position(size_t(2));
1724 if ((math_end == "$") &&
1725 (submath.str(2) == "$")) {
1726 mi.insert("$", math_pos, pos + 1);
1727 math_end_waiting = false;
1729 else if ((math_end == "\\]") &&
1730 (submath.str(2) == "\\]")) {
1731 mi.insert("\\]", math_pos, pos + 2);
1732 math_end_waiting = false;
1734 else if ((submath.str(3).compare("end") == 0) &&
1735 (submath.str(4).compare(math_end) == 0)) {
1736 mi.insert(math_end, math_pos, pos + submath.str(2).length());
1737 math_end_waiting = false;
1743 if (submath.str(3).compare("begin") == 0) {
1744 math_end_waiting = true;
1745 math_end = submath.str(4);
1746 math_pos = submath.position(size_t(2));
1748 else if (submath.str(2).compare("\\[") == 0) {
1749 math_end_waiting = true;
1751 math_pos = submath.position(size_t(2));
1753 else if (submath.str(2) == "$") {
1754 size_t pos = submath.position(size_t(2));
1755 math_end_waiting = true;
1761 // Ignore language if there is math somewhere in pattern-string
1762 if (isPatternString) {
1763 for (auto s: usedText) {
1764 // Remove entries created in previous search runs
1767 usedText = vector<string>();
1770 keys["foreignlanguage"].disabled = true;
1771 disableLanguageOverride = true;
1774 disableLanguageOverride = false;
1777 if (disableLanguageOverride) {
1778 keys["foreignlanguage"].disabled = true;
1781 math_pos = mi.getFirstPos();
1782 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1784 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1785 // prefixed by odd count of '\\'
1788 string key = sub.str(5);
1790 if (sub.str(2)[0] == '\\')
1791 key = sub.str(2)[1];
1796 KeysIterator it_key = keys.find(key);
1797 if (it_key != keys.end()) {
1798 if (it_key->second.keytype == KeyInfo::headRemove) {
1799 KeyInfo found1 = it_key->second;
1800 found1.disabled = true;
1801 found1.head = "\\" + key + "{";
1802 found1._tokenstart = sub.position(size_t(2));
1803 found1._tokensize = found1.head.length();
1804 found1._dataStart = found1._tokenstart + found1.head.length();
1805 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1806 found1._dataEnd = endpos;
1811 if (evaluatingRegexp) {
1812 if (sub.str(3).compare("endregexp") == 0) {
1813 evaluatingRegexp = false;
1814 // found._tokenstart already set
1815 found._dataEnd = sub.position(size_t(2)) + 13;
1816 found._dataStart = found._dataEnd;
1817 found._tokensize = found._dataEnd - found._tokenstart;
1818 found.parenthesiscount = 0;
1819 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1826 if (evaluatingMath) {
1827 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1829 evaluatingMath = false;
1831 math_pos = mi.getStartPos();
1833 if (it_key == keys.end()) {
1834 found = KeyInfo(KeyInfo::isStandard, 0, true);
1835 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1836 found = KeyInfo(KeyInfo::isText, 0, false);
1837 if (isPatternString) {
1838 found.keytype = KeyInfo::isChar;
1839 found.disabled = false;
1843 usedText.push_back(key);
1847 if (key.compare("regexp") == 0) {
1848 evaluatingRegexp = true;
1849 found._tokenstart = sub.position(size_t(2));
1850 found._tokensize = 0;
1854 // Handle the other params of key
1855 if (found.keytype == KeyInfo::isIgnored)
1857 else if (found.keytype == KeyInfo::isMath) {
1858 if (size_t(sub.position(size_t(2))) == math_pos) {
1860 found._tokenstart = sub.position(size_t(2));
1861 found._tokensize = mi.getSize();
1862 found._dataEnd = found._tokenstart + found._tokensize;
1863 found._dataStart = found._dataEnd;
1864 found.parenthesiscount = 0;
1865 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1866 evaluatingMath = true;
1869 // begin|end of unknown env, discard
1870 // First handle tables
1871 // longtable|tabular
1872 bool discardComment;
1874 found.keytype = KeyInfo::doRemove;
1875 if ((sub.str(7).compare("longtable") == 0) ||
1876 (sub.str(7).compare("tabular") == 0)) {
1877 discardComment = true; /* '%' */
1880 discardComment = false;
1881 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1883 string token = sub.str(7);
1884 if (regex_match(token, sub2, removeArgs)) {
1885 found.keytype = KeyInfo::removeWithArg;
1888 // discard spaces before pos(2)
1889 int pos = sub.position(size_t(2));
1891 for (count = 0; pos - count > 0; count++) {
1892 char c = interval_.par[pos-count-1];
1893 if (discardComment) {
1894 if ((c != ' ') && (c != '%'))
1900 found._tokenstart = pos - count;
1901 if (sub.str(3).compare(0, 5, "begin") == 0) {
1902 size_t pos1 = pos + sub.str(2).length();
1903 if (sub.str(7).compare("cjk") == 0) {
1904 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1905 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1907 found.keytype = KeyInfo::isMain;
1908 found._dataStart = pos1;
1909 found._dataEnd = interval_.par.length();
1910 found.disabled = keys["foreignlanguage"].disabled;
1911 found.used = keys["foreignlanguage"].used;
1912 found._tokensize = pos1 - found._tokenstart;
1913 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1916 // Swallow possible optional params
1917 while (interval_.par[pos1] == '[') {
1918 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1920 // Swallow also the eventual parameter
1921 if (interval_.par[pos1] == '{') {
1922 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1925 found._dataEnd = pos1;
1927 found._dataStart = found._dataEnd;
1928 found._tokensize = count + found._dataEnd - pos;
1929 found.parenthesiscount = 0;
1930 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1931 found.disabled = true;
1935 // Handle "\end{...}"
1936 found._dataStart = pos + sub.str(2).length();
1937 found._dataEnd = found._dataStart;
1938 found._tokensize = count + found._dataEnd - pos;
1939 found.parenthesiscount = 0;
1940 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1941 found.disabled = true;
1945 else if (found.keytype != KeyInfo::isRegex) {
1946 found._tokenstart = sub.position(size_t(2));
1947 if (found.parenthesiscount == 0) {
1948 // Probably to be discarded
1949 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1950 char following = interval_.par[following_pos];
1951 if (following == ' ')
1952 found.head = "\\" + sub.str(5) + " ";
1953 else if (following == '=') {
1954 // like \uldepth=1000pt
1955 found.head = sub.str(2);
1958 found.head = "\\" + key;
1959 found._tokensize = found.head.length();
1960 found._dataEnd = found._tokenstart + found._tokensize;
1961 found._dataStart = found._dataEnd;
1964 int params = found._tokenstart + key.length() + 1;
1965 if (evaluatingOptional) {
1966 if (size_t(found._tokenstart) > optionalEnd) {
1967 evaluatingOptional = false;
1970 found.disabled = true;
1973 int optend = params;
1974 while (interval_.par[optend] == '[') {
1975 // discard optional parameters
1976 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
1978 if (optend > params) {
1979 key += interval_.par.substr(params, optend-params);
1980 evaluatingOptional = true;
1981 optionalEnd = optend;
1982 if (found.keytype == KeyInfo::isSectioning) {
1983 // Remove optional values (but still keep in header)
1984 interval_.addIntervall(params, optend);
1987 string token = sub.str(7);
1989 if (interval_.par[optend] != '{') {
1991 found.parenthesiscount = 0;
1992 found.head = "\\" + key;
1995 closings = found.parenthesiscount;
1996 if (found.parenthesiscount == 1) {
1997 found.head = "\\" + key + "{";
1999 else if (found.parenthesiscount > 1) {
2001 found.head = sub.str(2) + "{";
2002 closings = found.parenthesiscount - 1;
2005 found.head = "\\" + key + "{";
2008 found._tokensize = found.head.length();
2009 found._dataStart = found._tokenstart + found.head.length();
2010 if (found.keytype == KeyInfo::doRemove) {
2012 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2013 if (endpar >= interval_.par.length())
2014 found._dataStart = interval_.par.length();
2016 found._dataStart = endpar;
2017 found._tokensize = found._dataStart - found._tokenstart;
2020 found._dataStart = found._tokenstart + found._tokensize;
2024 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2025 found._dataStart += 15;
2029 endpos = found._dataStart - 1;
2031 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2032 if (found.keytype == KeyInfo::isList) {
2033 // Check if it really is list env
2034 static regex const listre("^([a-z]+)$");
2036 if (!regex_match(token, sub2, listre)) {
2037 // Change the key of this entry. It is not in a list/item environment
2038 found.keytype = KeyInfo::endArguments;
2041 if (found.keytype == KeyInfo::noMain) {
2042 evaluatingCode = true;
2044 codeStart = found._dataStart;
2046 else if (evaluatingCode) {
2047 if (size_t(found._dataStart) > codeEnd)
2048 evaluatingCode = false;
2049 else if (found.keytype == KeyInfo::isMain) {
2050 // Disable this key, treate it as standard
2051 found.keytype = KeyInfo::isStandard;
2052 found.disabled = true;
2053 if ((codeEnd +1 >= interval_.par.length()) &&
2054 (found._tokenstart == codeStart)) {
2055 // trickery, because the code inset starts
2056 // with \selectlanguage ...
2058 if (entries_.size() > 1) {
2059 entries_[entries_.size()-1]._dataEnd = codeEnd;
2064 if ((endpos == interval_.par.length()) &&
2065 (found.keytype == KeyInfo::doRemove)) {
2066 // Missing closing => error in latex-input?
2067 // therefore do not delete remaining data
2068 found._dataStart -= 1;
2069 found._dataEnd = found._dataStart;
2072 found._dataEnd = endpos;
2074 if (isPatternString) {
2075 keys[key].used = true;
2078 entries_.push_back(found);
2082 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2084 stringstream s(keysstring);
2086 const char delim = '|';
2087 while (getline(s, key, delim)) {
2088 KeyInfo keyII(keyI);
2089 if (isPatternString) {
2092 else if ( !keys[key].used)
2093 keyII.disabled = true;
2098 void LatexInfo::buildKeys(bool isPatternString)
2101 static bool keysBuilt = false;
2102 if (keysBuilt && !isPatternString) return;
2104 // Keys to ignore in any case
2105 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2106 // Known standard keys with 1 parameter.
2107 // Split is done, if not at start of region
2108 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2109 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2110 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2111 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2112 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2113 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2115 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2116 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2117 makeKey("section*|subsection*|subsubsection*|paragraph*",
2118 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2119 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2120 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2122 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2124 // Split is done, if not at start of region
2125 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2126 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2128 // Split is done always.
2129 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2133 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2134 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2135 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2136 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2138 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2139 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2140 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2141 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2143 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2144 // Custom space/skip, remove the content (== length value)
2145 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2146 // Found in fr/UserGuide.lyx
2147 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2149 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2150 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2151 // Known macros to remove (including their parameter)
2153 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2154 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2155 // handle like standard keys with 1 parameter.
2156 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2158 // Ignore deleted text
2159 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2160 // but preserve added text
2161 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2163 // Macros to remove, but let the parameter survive
2165 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2167 // Remove language spec from content of these insets
2168 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2170 // Same effect as previous, parameter will survive (because there is no one anyway)
2172 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2173 // Remove table decorations
2174 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2175 // Discard shape-header.
2176 // For footnote or shortcut too, because of lang settings
2177 // and wrong handling if used 'KeyInfo::noMain'
2178 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2179 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2180 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2181 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2182 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2183 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2184 // like ('tiny{}' or '\tiny ' ... )
2185 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2187 // Survives, like known character
2188 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2189 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2190 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2192 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2193 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2194 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2196 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2197 // Remove RTL/LTR marker
2198 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2199 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2200 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2201 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2202 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2203 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2204 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2205 if (isPatternString) {
2206 // Allow the first searched string to rebuild the keys too
2210 // no need to rebuild again
2216 * Keep the list of actual opened parentheses actual
2217 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2219 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2222 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2226 if (c == '\\') skip = 1;
2227 else if (c == '{') {
2230 else if (c == '}') {
2231 handleCloseP(i, closingAllowed);
2237 string Intervall::show(int lastpos)
2239 int idx = 0; /* int intervalls */
2242 for (idx = 0; idx <= ignoreidx; idx++) {
2243 while (i < lastpos) {
2245 if (i <= borders[idx].low) {
2246 if (borders[idx].low > lastpos)
2247 printsize = lastpos - i;
2249 printsize = borders[idx].low - i;
2250 s += par.substr(i, printsize);
2252 if (i >= borders[idx].low)
2253 i = borders[idx].upper;
2256 i = borders[idx].upper;
2262 s += par.substr(i, lastpos-i);
2268 void Intervall::output(ostringstream &os, int lastpos)
2270 // get number of chars to output
2271 int idx = 0; /* int intervalls */
2274 string startTitle = titleValue;
2275 for (idx = 0; idx <= ignoreidx; idx++) {
2277 if (i <= borders[idx].low) {
2279 if (borders[idx].low > lastpos)
2280 printsize = lastpos - i;
2282 printsize = borders[idx].low - i;
2283 if (printsize > 0) {
2284 os << startTitle << par.substr(i, printsize);
2286 printed += printsize;
2289 handleParentheses(i, false);
2290 if (i >= borders[idx].low)
2291 i = borders[idx].upper;
2294 i = borders[idx].upper;
2301 os << startTitle << par.substr(i, lastpos-i);
2302 printed += lastpos-i;
2304 handleParentheses(lastpos, false);
2306 if (keys["foreignlanguage"].disabled)
2307 startindex = actualdeptindex-langcount;
2309 startindex = actualdeptindex;
2310 for (int i = startindex; i > 0; --i) {
2313 if (hasTitle && (printed > 0))
2315 if (! isPatternString_)
2317 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2320 void LatexInfo::processRegion(int start, int region_end)
2322 while (start < region_end) { /* Let {[} and {]} survive */
2323 int cnt = interval_.isOpeningPar(start);
2325 // Closing is allowed past the region
2326 int closing = interval_.findclosing(start+1, interval_.par.length());
2327 interval_.addIntervall(start, start+1);
2328 interval_.addIntervall(closing, closing+1);
2332 start = interval_.nextNotIgnored(start+1);
2336 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2338 if (actual.parenthesiscount == 0) {
2339 // "{\tiny{} ...}" ==> "{{} ...}"
2340 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2343 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2344 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2345 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2349 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2352 switch (actual.keytype)
2354 case KeyInfo::isTitle: {
2356 nextKeyIdx = getNextKey();
2359 case KeyInfo::cleanToStart: {
2360 actual._dataEnd = actual._dataStart;
2361 nextKeyIdx = getNextKey();
2362 // Search for end of arguments
2363 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2365 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2366 entries_[i].disabled = true;
2368 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2370 while (interval_.par[actual._dataEnd] == ' ')
2372 interval_.addIntervall(0, actual._dataEnd+1);
2373 interval_.actualdeptindex = 0;
2374 interval_.depts[0] = actual._dataEnd+1;
2375 interval_.closes[0] = -1;
2378 case KeyInfo::isText:
2379 interval_.par[actual._tokenstart] = '#';
2380 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2381 nextKeyIdx = getNextKey();
2383 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2384 if (actual.disabled)
2385 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2387 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2390 case KeyInfo::isChar: {
2391 nextKeyIdx = getNextKey();
2394 case KeyInfo::isSize: {
2395 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2396 if (actual.parenthesiscount == 0)
2397 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2399 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2401 nextKeyIdx = getNextKey();
2403 // Here _dataStart points to '{', so correct it
2404 actual._dataStart += 1;
2405 actual._tokensize += 1;
2406 actual.parenthesiscount = 1;
2407 if (interval_.par[actual._dataStart] == '}') {
2408 // Determine the end if used like '{\tiny{}...}'
2409 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2410 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2413 // Determine the end if used like '\tiny{...}'
2414 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2416 // Split on this key if not at start
2417 int start = interval_.nextNotIgnored(previousStart);
2418 if (start < actual._tokenstart) {
2419 interval_.output(os, actual._tokenstart);
2420 interval_.addIntervall(start, actual._tokenstart);
2422 // discard entry if at end of actual
2423 nextKeyIdx = process(os, actual);
2427 case KeyInfo::endArguments: {
2428 // Remove trailing '{}' too
2429 actual._dataStart += 1;
2430 actual._dataEnd += 1;
2431 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2432 nextKeyIdx = getNextKey();
2435 case KeyInfo::noMain:
2437 case KeyInfo::isStandard: {
2438 if (actual.disabled) {
2440 processRegion(actual._dataStart, actual._dataStart+1);
2441 nextKeyIdx = getNextKey();
2443 // Split on this key if not at datastart of calling entry
2444 int start = interval_.nextNotIgnored(previousStart);
2445 if (start < actual._tokenstart) {
2446 interval_.output(os, actual._tokenstart);
2447 interval_.addIntervall(start, actual._tokenstart);
2449 // discard entry if at end of actual
2450 nextKeyIdx = process(os, actual);
2454 case KeyInfo::removeWithArg: {
2455 nextKeyIdx = getNextKey();
2456 // Search for end of arguments
2457 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2459 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2460 entries_[i].disabled = true;
2462 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2464 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2467 case KeyInfo::doRemove: {
2468 // Remove the key with all parameters and following spaces
2471 if (interval_.par[actual._dataEnd-1] == ' ')
2472 start = actual._dataEnd;
2474 start = actual._dataEnd+1;
2475 for (pos = start; pos < interval_.par.length(); pos++) {
2476 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2479 // Remove also enclosing parentheses [] and {}
2482 while (actual._tokenstart > numpars) {
2483 if (pos+numpars >= interval_.par.size())
2485 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2487 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2493 if (interval_.par[pos+numpars] == ' ')
2497 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2498 nextKeyIdx = getNextKey();
2501 case KeyInfo::isList: {
2502 // Discard space before _tokenstart
2504 for (count = 0; count < actual._tokenstart; count++) {
2505 if (interval_.par[actual._tokenstart-count-1] != ' ')
2508 nextKeyIdx = getNextKey();
2509 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2511 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2513 // How else can we catch this one?
2514 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2515 entries_[i].disabled = true;
2517 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2519 else if (nextKeyIdx > 0) {
2520 // Ignore any lang entries inside data region
2521 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2522 if (entries_[i].keytype == KeyInfo::isMain)
2523 entries_[i].disabled = true;
2526 if (actual.disabled) {
2527 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2530 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2532 if (interval_.par[actual._dataEnd+1] == '[') {
2533 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2534 if ((interval_.par[actual._dataEnd+2] == '{') &&
2535 (interval_.par[posdown-1] == '}')) {
2536 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2537 interval_.addIntervall(posdown-1, posdown+1);
2540 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2541 interval_.addIntervall(posdown, posdown+1);
2543 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2544 if (blk > posdown) {
2545 // Discard at most 1 space after empty item
2547 for (count = 0; count < 1; count++) {
2548 if (interval_.par[blk+count] != ' ')
2552 interval_.addIntervall(blk, blk+count);
2557 case KeyInfo::isSectioning: {
2558 // Discard spaces before _tokenstart
2560 int val = actual._tokenstart;
2561 for (count = 0; count < actual._tokenstart;) {
2562 val = interval_.previousNotIgnored(val-1);
2563 if (val < 0 || interval_.par[val] != ' ')
2566 count = actual._tokenstart - val;
2569 if (actual.disabled) {
2570 removeHead(actual, count);
2571 nextKeyIdx = getNextKey();
2573 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2574 nextKeyIdx = process(os, actual);
2578 case KeyInfo::isMath: {
2579 // Same as regex, use the content unchanged
2580 nextKeyIdx = getNextKey();
2583 case KeyInfo::isRegex: {
2584 // DO NOT SPLIT ON REGEX
2586 nextKeyIdx = getNextKey();
2589 case KeyInfo::isIgnored: {
2590 // Treat like a character for now
2591 nextKeyIdx = getNextKey();
2594 case KeyInfo::isMain: {
2595 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2596 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2597 if (actual._tokenstart > 0) {
2598 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2599 if ((prev >= 0) && interval_.par[prev] == '%')
2600 interval_.addIntervall(prev, prev+1);
2602 if (actual.disabled) {
2604 interval_.langcount++;
2605 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2606 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2607 // Discard also the space before math-equation
2608 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2610 nextKeyIdx = getNextKey();
2611 // interval.resetOpenedP(actual._dataStart-1);
2614 if (actual._tokenstart < 26) {
2615 // for the first (and maybe dummy) language
2616 interval_.setForDefaultLang(actual);
2618 interval_.resetOpenedP(actual._dataStart-1);
2622 case KeyInfo::invalid:
2623 case KeyInfo::headRemove:
2624 // These two cases cannot happen, already handled
2627 // LYXERR(Debug::INFO, "Unhandled keytype");
2628 nextKeyIdx = getNextKey();
2635 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2637 int end = interval_.nextNotIgnored(actual._dataEnd);
2638 int oldStart = actual._dataStart;
2639 int nextKeyIdx = getNextKey();
2641 if ((nextKeyIdx < 0) ||
2642 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2643 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2644 if (oldStart <= end) {
2645 processRegion(oldStart, end);
2650 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2652 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2653 (void) dispatch(os, actual._dataStart, nextKey);
2654 end = nextKey._tokenstart;
2657 processRegion(oldStart, nextKey._tokenstart);
2658 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2660 oldStart = nextKey._dataEnd+1;
2662 // now nextKey is either invalid or is outside of actual._dataEnd
2663 // output the remaining and discard myself
2664 if (oldStart <= end) {
2665 processRegion(oldStart, end);
2667 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2669 // This is the normal case.
2670 // But if using the firstlanguage, the closing may be missing
2672 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2674 if (actual._dataEnd < end)
2675 output_end = interval_.nextNotIgnored(actual._dataEnd);
2676 else if (interval_.par.size() > (size_t) end)
2677 output_end = interval_.nextNotIgnored(end);
2679 output_end = interval_.par.size();
2680 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2681 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2683 // Remove possible empty data
2684 int dstart = interval_.nextNotIgnored(actual._dataStart);
2685 while (interval_.isOpeningPar(dstart) == 1) {
2686 interval_.addIntervall(dstart, dstart+1);
2687 int dend = interval_.findclosing(dstart+1, output_end);
2688 interval_.addIntervall(dend, dend+1);
2689 dstart = interval_.nextNotIgnored(dstart+1);
2691 if (dstart < output_end)
2692 interval_.output(os, output_end);
2693 interval_.addIntervall(actual._tokenstart, end);
2697 string splitOnKnownMacros(string par, bool isPatternString)
2700 LatexInfo li(par, isPatternString);
2701 // LYXERR(Debug::INFO, "Berfore split: " << par);
2702 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2704 DummyKey._tokensize = 0;
2705 DummyKey._dataStart = 0;
2706 DummyKey._dataEnd = par.length();
2707 DummyKey.disabled = true;
2708 int firstkeyIdx = li.getFirstKey();
2710 if (firstkeyIdx >= 0) {
2711 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2712 DummyKey._tokenstart = firstKey._tokenstart;
2714 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2715 // Use dummy firstKey
2716 firstKey = DummyKey;
2717 (void) li.setNextKey(firstkeyIdx);
2720 if (par.substr(firstKey._dataStart, 2) == "% ")
2721 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2723 nextkeyIdx = li.process(os, firstKey);
2724 while (nextkeyIdx >= 0) {
2725 // Check for a possible gap between the last
2726 // entry and this one
2727 int datastart = li.nextNotIgnored(firstKey._dataStart);
2728 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2729 if ((nextKey._tokenstart > datastart)) {
2731 firstKey._dataStart = datastart;
2732 firstKey._dataEnd = par.length();
2733 (void) li.setNextKey(nextkeyIdx);
2734 // Fake the last opened parenthesis
2735 li.setForDefaultLang(firstKey);
2736 nextkeyIdx = li.process(os, firstKey);
2739 if (nextKey.keytype != KeyInfo::isMain) {
2740 firstKey._dataStart = datastart;
2741 firstKey._dataEnd = nextKey._dataEnd+1;
2742 (void) li.setNextKey(nextkeyIdx);
2743 li.setForDefaultLang(firstKey);
2744 nextkeyIdx = li.process(os, firstKey);
2747 nextkeyIdx = li.process(os, nextKey);
2751 // Handle the remaining
2752 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2753 firstKey._dataEnd = par.length();
2755 if ((firstKey._dataStart < firstKey._dataEnd) &&
2756 (par[firstKey._dataStart] != '}')) {
2757 li.setForDefaultLang(firstKey);
2758 (void) li.process(os, firstKey);
2762 // return string definitelly impossible to match
2763 s = "\\foreignlanguage{ignore}{ }";
2767 s = par; /* no known macros found */
2768 // LYXERR(Debug::INFO, "After split: " << s);
2773 * Try to unify the language specs in the latexified text.
2774 * Resulting modified string is set to "", if
2775 * the searched tex does not contain all the features in the search pattern
2777 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2779 static Features regex_f;
2780 static int missed = 0;
2781 static bool regex_with_format = false;
2783 int parlen = par.length();
2785 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2788 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2789 // Happens to be there in case of description or labeling environment
2794 // Split the latex input into pieces which
2795 // can be digested by our search engine
2796 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2797 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2798 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2799 string doclang = pbuf->params().language->polyglossia();
2800 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2802 bool toIgnoreLang = true;
2803 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2805 if (sub.str(2) != doclang) {
2806 toIgnoreLang = false;
2810 setIgnoreFormat("language", toIgnoreLang);
2813 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2814 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2817 result = par.substr(0, parlen);
2818 if (isPatternString) {
2821 regex_f = identifyFeatures(result);
2822 string features = "";
2823 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2824 string a = it->first;
2825 regex_with_format = true;
2826 features += " " + a;
2827 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2829 LYXERR(Debug::FIND, "Identified Features" << features);
2832 } else if (regex_with_format) {
2833 Features info = identifyFeatures(result);
2834 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2835 string a = it->first;
2836 bool b = it->second;
2837 if (b && ! info[a]) {
2839 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2846 // LYXERR(Debug::INFO, "No regex formats");
2852 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2853 static int identifyClosing(string & t)
2855 int open_braces = 0;
2857 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2858 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2860 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2862 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2864 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2873 static int num_replaced = 0;
2874 static bool previous_single_replace = true;
2876 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2879 // Handle \w properly
2880 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2881 if (! opt.casesensitive) {
2882 popts |= QRegularExpression::CaseInsensitiveOption;
2884 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2885 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2887 if (regexp.isValid() && regexp2.isValid()) {
2888 regexIsValid = true;
2889 // Check '{', '}' pairs inside the regex
2892 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2893 char c = par_as_string[i];
2900 else if (c == '}') {
2907 if (balanced != 0) {
2908 regexIsValid = false;
2909 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2913 regexIsValid = false;
2914 if (!regexp.isValid())
2915 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2917 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2920 if (opt.casesensitive) {
2921 regexp = regex(regexp_str);
2922 regexp2 = regex(regexp2_str);
2925 regexp = regex(regexp_str, std::regex_constants::icase);
2926 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2931 static void modifyRegexForMatchWord(string &t)
2934 regex wordre("(\\\\)*((\\.|\\\\b))");
2937 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2939 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2942 else if (sub.str(2) == "\\\\b")
2944 if (lastpos < (size_t) sub.position(2))
2945 s += t.substr(lastpos, sub.position(2) - lastpos);
2947 lastpos = sub.position(2) + sub.length(2);
2950 s = "\\b" + t + "\\b";
2954 else if (lastpos < t.length())
2955 s += t.substr(lastpos, t.length() - lastpos);
2956 t = "\\b" + s + "\\b";
2959 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
2960 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2962 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2963 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2964 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2965 if (opt.replace_all && previous_single_replace) {
2966 previous_single_replace = false;
2969 else if (!opt.replace_all) {
2970 num_replaced = 0; // count number of replaced strings
2971 previous_single_replace = true;
2973 // When using regexp, braces are hacked already by escape_for_regex()
2974 par_as_string = normalize(ds);
2976 close_wildcards = 0;
2978 size_t lead_size = 0;
2979 // correct the language settings
2980 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
2981 opt.matchAtStart = false;
2983 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
2984 if (opt.ignoreformat) {
2988 lead_size = identifyLeading(par_as_string);
2990 lead_as_string = par_as_string.substr(0, lead_size);
2991 string lead_as_regex_string = string2regex(lead_as_string);
2992 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2993 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
2994 /* Handle whole words too in this case
2996 if (opt.matchword) {
2997 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
2998 opt.matchword = false;
3000 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3001 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3002 CreateRegexp(opt, regexp_str, regexp2_str);
3004 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3005 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3009 if (!opt.ignoreformat) {
3010 lead_size = identifyLeading(par_as_string);
3011 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3012 lead_as_string = par_as_string.substr(0, lead_size);
3013 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3016 // Here we are using regexp
3017 LASSERT(use_regexp, /**/);
3019 string lead_as_regexp;
3020 if (lead_size > 0) {
3021 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3022 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3023 par_as_string = par_as_string_nolead;
3024 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3025 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3027 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3028 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3029 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3030 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3032 size_t lng = par_as_string.size();
3033 if (!opt.ignoreformat) {
3034 // Remove extra '\}' at end if not part of \{\.\}
3036 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3038 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3047 if (lng < par_as_string.size())
3048 par_as_string = par_as_string.substr(0,lng);
3050 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3051 if ((lng > 0) && (par_as_string[0] == '^')) {
3052 par_as_string = par_as_string.substr(1);
3054 opt.matchAtStart = true;
3056 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3057 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3058 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3060 // If entered regexp must match at begin of searched string buffer
3061 // Kornel: Added parentheses to use $1 for size of the leading string
3065 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3066 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3067 // so the convert has no effect in that case
3068 for (int i = 7; i > 0; --i) {
3069 string orig = "\\\\" + std::to_string(i);
3070 string dest = "\\" + std::to_string(i+2);
3071 while (regex_replace(par_as_string, par_as_string, orig, dest));
3073 if (opt.matchword) {
3074 modifyRegexForMatchWord(par_as_string);
3075 opt.matchword = false;
3077 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3078 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3080 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3081 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3082 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3086 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3090 mres.searched_size = len;
3092 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3095 docstring docstr = stringifyFromForSearch(opt, cur, len);
3097 str = normalize(docstr);
3098 if (!opt.ignoreformat) {
3099 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3100 // remove closing '}' and '\n' to allow for use of '$' in regex
3101 size_t lng = str.size();
3102 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3104 if (lng != str.size()) {
3105 str = str.substr(0, lng);
3109 mres.match_len = -1;
3112 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3114 LASSERT(use_regexp, /**/);
3116 // use_regexp always true
3117 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3119 QString qstr = QString::fromStdString(str);
3120 QRegularExpression const *p_regexp;
3121 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3125 p_regexp = ®exp2;
3127 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3128 if (!match.hasMatch())
3131 regex const *p_regexp;
3132 regex_constants::match_flag_type flags;
3134 flags = regex_constants::match_continuous;
3137 flags = regex_constants::match_default;
3138 p_regexp = ®exp2;
3140 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3141 if (re_it == sregex_iterator())
3143 match_results<string::const_iterator> const & m = *re_it;
3145 // Whole found string, including the leading
3146 // std: m[0].second - m[0].first
3147 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3149 // Size of the leading string
3150 // std: m[1].second - m[1].first
3151 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3152 int leadingsize = 0;
3154 if (match.lastCapturedIndex() > 0) {
3155 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3160 leadingsize = m[1].second - m[1].first;
3164 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3165 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3166 // because of different number of closing at end of string
3167 // we have to 'unify' the length of the post-match.
3168 // Done by ignoring closing parenthesis and linefeeds at string end
3169 int matchend = match.capturedEnd(0);
3170 size_t strsize = qstr.size();
3171 if (!opt.ignoreformat) {
3172 while (mres.match_len > 0) {
3173 QChar c = qstr.at(matchend - 1);
3174 if ((c == '\n') || (c == '}') || (c == '{')) {
3181 while (strsize > (size_t) match.capturedEnd(0)) {
3182 QChar c = qstr.at(strsize-1);
3183 if ((c == '\n') || (c == '}')) {
3190 // LYXERR0(qstr.toStdString());
3191 mres.match2end = strsize - matchend;
3192 mres.pos = match.capturedStart(2);
3194 mres.match_prefix = m[2].second - m[2].first;
3195 mres.match_len = m[0].second - m[2].second;
3196 // ignore closing parenthesis and linefeeds at string end
3197 size_t strend = m[0].second - m[0].first;
3198 int matchend = strend;
3199 size_t strsize = str.size();
3200 if (!opt.ignoreformat) {
3201 while (mres.match_len > 0) {
3202 char c = str.at(matchend - 1);
3203 if ((c == '\n') || (c == '}') || (c == '{')) {
3210 while (strsize > strend) {
3211 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3219 mres.match2end = strsize - matchend;
3220 mres.pos = m[2].first - m[0].first;;
3222 if (mres.match2end < 0)
3224 mres.leadsize = leadingsize;
3226 if (mres.match_len > 0) {
3227 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3228 mres.result.push_back(a0);
3229 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3230 mres.result.push_back(match.captured(i).toStdString());
3234 if (mres.match_len > 0) {
3235 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3236 mres.result.push_back(a0);
3237 for (size_t i = 3; i < m.size(); i++) {
3238 mres.result.push_back(m[i]);
3247 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3249 MatchResult mres = findAux(cur, len, at_begin);
3250 int res = mres.match_len;
3252 "res=" << res << ", at_begin=" << at_begin
3253 << ", matchAtStart=" << opt.matchAtStart
3254 << ", inTexted=" << cur.inTexted());
3255 if (opt.matchAtStart) {
3258 else if (mres.match_prefix > 0)
3267 static bool simple_replace(string &t, string from, string to)
3269 regex repl("(\\\\)*(" + from + ")");
3273 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3275 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3277 if (lastpos < (size_t) sub.position(2))
3278 s += t.substr(lastpos, sub.position(2) - lastpos);
3280 lastpos = sub.position(2) + sub.length(2);
3284 else if (lastpos < t.length())
3285 s += t.substr(lastpos, t.length() - lastpos);
3291 string MatchStringAdv::normalize(docstring const & s) const
3294 t = lyx::to_utf8(s);
3295 // Remove \n at begin
3296 while (!t.empty() && t[0] == '\n')
3299 while (!t.empty() && t[t.size() - 1] == '\n')
3300 t = t.substr(0, t.size() - 1);
3302 // Handle all other '\n'
3303 while ((pos = t.find("\n")) != string::npos) {
3304 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3306 if (isAlnumASCII(t[pos+1])) {
3307 t.replace(pos-2, 3, " ");
3310 t.replace(pos-2, 3, "");
3313 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3314 // '\n' adjacent to non-alpha-numerics, discard
3315 t.replace(pos, 1, "");
3318 // Replace all other \n with spaces
3319 t.replace(pos, 1, " ");
3322 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3323 // Kornel: Added textsl, textsf, textit, texttt and noun
3324 // + allow to seach for colored text too
3325 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3326 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3327 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3328 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3329 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3330 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3336 docstring stringifyFromCursor(DocIterator const & cur, int len)
3338 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3339 if (cur.inTexted()) {
3340 Paragraph const & par = cur.paragraph();
3341 // TODO what about searching beyond/across paragraph breaks ?
3342 // TODO Try adding a AS_STR_INSERTS as last arg
3343 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3344 int(par.size()) : cur.pos() + len;
3345 // OutputParams runparams(&cur.buffer()->params().encoding());
3346 OutputParams runparams(encodings.fromLyXName("utf8"));
3347 runparams.nice = true;
3348 runparams.flavor = Flavor::XeTeX;
3349 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3350 // No side effect of file copying and image conversion
3351 runparams.dryrun = true;
3352 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3353 if (ignoreFormats.getDeleted()) {
3354 option |= AS_STR_SKIPDELETE;
3355 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3358 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3360 LYXERR(Debug::FIND, "Stringifying with cur: "
3361 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3362 return par.asString(cur.pos(), end,
3365 } else if (cur.inMathed()) {
3366 CursorSlice cs = cur.top();
3367 MathData md = cs.cell();
3368 MathData::const_iterator it_end =
3369 (( len == -1 || cs.pos() + len > int(md.size()))
3371 : md.begin() + cs.pos() + len );
3373 for (MathData::const_iterator it = md.begin() + cs.pos();
3376 docstring s = asString(md2);
3377 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3380 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3385 /** Computes the LaTeX export of buf starting from cur and ending len positions
3386 * after cur, if len is positive, or at the paragraph or innermost inset end
3389 docstring latexifyFromCursor(DocIterator const & cur, int len)
3392 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3393 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3394 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3396 Buffer const & buf = *cur.buffer();
3398 odocstringstream ods;
3400 //OutputParams runparams(&buf.params().encoding());
3401 OutputParams runparams(encodings.fromLyXName("utf8"));
3402 runparams.nice = false;
3403 runparams.flavor = Flavor::XeTeX;
3404 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3405 // No side effect of file copying and image conversion
3406 runparams.dryrun = true;
3407 if (ignoreFormats.getDeleted()) {
3408 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3411 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3414 if (cur.inTexted()) {
3415 // @TODO what about searching beyond/across paragraph breaks ?
3416 pos_type endpos = cur.paragraph().size();
3417 if (len != -1 && endpos > cur.pos() + len)
3418 endpos = cur.pos() + len;
3419 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3420 string(), cur.pos(), endpos);
3421 string s = lyx::to_utf8(ods.str());
3422 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3423 return(lyx::from_utf8(s));
3424 } else if (cur.inMathed()) {
3425 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3426 for (int s = cur.depth() - 1; s >= 0; --s) {
3427 CursorSlice const & cs = cur[s];
3428 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3429 TeXMathStream ws(os);
3430 cs.asInsetMath()->asHullInset()->header_write(ws);
3435 CursorSlice const & cs = cur.top();
3436 MathData md = cs.cell();
3437 MathData::const_iterator it_end =
3438 ((len == -1 || cs.pos() + len > int(md.size()))
3440 : md.begin() + cs.pos() + len);
3442 for (MathData::const_iterator it = md.begin() + cs.pos();
3446 ods << asString(md2);
3447 // Retrieve the math environment type, and add '$' or '$]'
3448 // or others (\end{equation}) accordingly
3449 for (int s = cur.depth() - 1; s >= 0; --s) {
3450 CursorSlice const & cs2 = cur[s];
3451 InsetMath * inset = cs2.asInsetMath();
3452 if (inset && inset->asHullInset()) {
3453 TeXMathStream ws(os);
3454 inset->asHullInset()->footer_write(ws);
3458 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3460 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3465 #if defined(ResultsDebug)
3467 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3469 LYXERR0( "from:\t\t\t" << from);
3471 if (mres.pos_len > 0) {
3473 status = "FINALSEARCH";
3476 if (mres.match_len > 0) {
3477 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3478 status = "Good Match";
3480 status = "Matched in";
3483 status = "MissedSearch";
3486 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3487 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3488 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3489 if ((mres.pos > 0) || (mres.match_prefix > 0))
3490 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3491 for (size_t i = 0; i < mres.result.size(); i++)
3492 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3494 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3496 #define displayMres(s, txt, cur)
3499 /** Finalize an advanced find operation, advancing the cursor to the innermost
3500 ** position that matches, plus computing the length of the matching text to
3502 ** Return the cur.pos() difference between start and end of found match
3504 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3506 // Search the foremost position that matches (avoids find of entire math
3507 // inset when match at start of it)
3508 DocIterator old_cur(cur.buffer());
3510 static MatchResult fail = MatchResult();
3511 MatchResult max_match;
3512 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3513 // Happens with e.g. hyperlinks
3514 // either one sees "http://www.bla.bla" or nothing
3515 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3516 // and although we search for only 3 chars, we find the whole hyperlink inset
3517 bool at_begin = (expected.match_prefix == 0);
3518 if (!match.opt.forward && match.opt.ignoreformat) {
3519 if (expected.pos > 0)
3522 LASSERT(at_begin, /**/);
3523 if (expected.match_len > 0 && at_begin) {
3524 // Search for deepest match
3526 max_match = expected;
3528 size_t d = cur.depth();
3532 if (cur.depth() < d)
3534 if (cur.depth() == d)
3537 while (cur && cur.depth() > lastd) {
3538 lastd = cur.depth();
3539 mres = match(cur, -1, at_begin);
3540 displayMres(mres, "Checking innermost", cur);
3541 if (mres.match_len > 0)
3546 if (mres.match_len < expected.match_len)
3554 // (expected.match_len <= 0)
3555 mres = match(cur); /* match valid only if not searching whole words */
3556 displayMres(mres, "Start with negative match", cur);
3559 if (max_match.match_len <= 0) return fail;
3560 LYXERR(Debug::FIND, "Ok");
3562 // Compute the match length
3564 if (cur.pos() + len > cur.lastpos())
3567 LASSERT(match.use_regexp, /**/);
3570 int maxl = cur.lastpos() - cur.pos();
3571 // Greedy behaviour while matching regexps
3572 while (maxl > minl) {
3574 mres2 = match(cur, len, at_begin);
3575 displayMres(mres2, "Finalize loop", cur);
3576 int actual_match_len = mres2.match_len;
3577 if (actual_match_len >= max_match.match_len) {
3578 // actual_match_len > max_match _can_ happen,
3579 // if the search area splits
3580 // some following word so that the regex
3581 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3583 // This means, the len value is too big
3584 actual_match_len = max_match.match_len;
3586 max_match.match_len = actual_match_len;
3588 if (maxl - minl < 4)
3589 len = (int)((maxl + minl)/2);
3591 len = (int)(minl + (maxl - minl + 3)/4);
3594 // (actual_match_len < max_match.match_len)
3596 len = (int)((maxl + minl)/2);
3601 // Search for real start of matched characters
3603 MatchResult actual_match;
3606 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3607 if (cur.depth() < old_cur.depth()) {
3609 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3612 if (cur.pos() != old_cur.pos()) {
3613 // OK, forwarded 1 pos in actual inset
3614 actual_match = match(cur, len-1, at_begin);
3615 if (actual_match.match_len == max_match.match_len) {
3616 // Ha, got it! The shorter selection has the same match length
3619 max_match = actual_match;
3622 // OK, the shorter selection matches less chars, revert to previous value
3628 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3629 actual_match = match(cur, len, at_begin);
3630 if (actual_match.match_len == max_match.match_len) {
3632 max_match = actual_match;
3639 max_match.pos_len = len;
3640 displayMres(max_match, "SEARCH RESULT", cur)
3647 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3651 bool repeat = false;
3652 DocIterator orig_cur; // to be used if repeat not successful
3653 MatchResult orig_mres;
3654 while (!theApp()->longOperationCancelled() && cur) {
3655 //(void) findAdvForwardInnermost(cur);
3656 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3657 MatchResult mres = match(cur, -1, false);
3658 string msg = "Starting";
3661 displayMres(mres, msg + " findForwardAdv", cur)
3662 int match_len = mres.match_len;
3663 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3664 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3667 if (match_len <= 0) {
3668 // This should exit nested insets, if any, or otherwise undefine the currsor.
3669 cur.pos() = cur.lastpos();
3670 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3673 else { // match_len > 0
3674 // Try to find the begin of searched string
3676 int firstInvalid = cur.lastpos() - cur.pos();
3678 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3679 int incrcur = (firstInvalid + 1 )*3/4;
3680 if (incrcur < incrmatch)
3681 increment = incrcur;
3683 increment = incrmatch;
3687 LYXERR(Debug::FIND, "Set increment to " << increment);
3688 while (increment > 0) {
3689 DocIterator old_cur = cur;
3690 if (cur.pos() + increment >= cur.lastpos()) {
3694 cur.pos() = cur.pos() + increment;
3695 MatchResult mres2 = match(cur, -1, false);
3696 displayMres(mres2, "findForwardAdv loop", cur)
3697 switch (interpretMatch(mres, mres2)) {
3698 case MatchResult::newIsTooFar:
3699 // behind the expected match
3700 firstInvalid = increment;
3704 case MatchResult::newIsBetter:
3705 // not reached yet, but cur.pos()+increment is bettert
3707 firstInvalid -= increment;
3708 if (increment > firstInvalid*3/4)
3709 increment = firstInvalid*3/4;
3710 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3711 if (increment >= mres2.match_prefix)
3712 increment = (mres2.match_prefix+1)*3/4;
3717 // Handle not like MatchResult::newIsTooFar
3718 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3720 increment = increment*3/4;
3725 if (mres.match_len > 0) {
3726 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3727 // The match seems to indicate some deeper level
3736 // should never be reached.
3740 // LYXERR0("Leaving first loop");
3741 LYXERR(Debug::FIND, "Finalizing 1");
3742 MatchResult found_match = findAdvFinalize(cur, match, mres);
3743 if (found_match.match_len > 0) {
3744 LASSERT(found_match.pos_len > 0, /**/);
3745 match.FillResults(found_match);
3746 return found_match.pos_len;
3749 // try next possible match
3760 /// Find the most backward consecutive match within same paragraph while searching backwards.
3761 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3763 DocIterator cur_begin = cur;
3764 cur_begin.pos() = 0;
3765 DocIterator tmp_cur = cur;
3766 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3767 Inset & inset = cur.inset();
3768 for (; cur != cur_begin; cur.backwardPos()) {
3769 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3770 DocIterator new_cur = cur;
3771 new_cur.backwardPos();
3772 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3774 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3775 if (new_mr.match_len == mr.match_len)
3779 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3785 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3789 // Backup of original position
3790 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3791 if (cur == cur_begin)
3794 DocIterator cur_orig(cur);
3795 bool pit_changed = false;
3798 MatchResult found_match = match(cur, -1, false);
3800 if (found_match.match_len > 0) {
3802 cur.pos() = cur.lastpos();
3804 cur.pos() = cur_orig.pos();
3805 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3806 DocIterator cur_prev_iter;
3808 found_match = match(cur);
3809 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3810 << (found_match.match_len > 0) << ", cur: " << cur);
3811 if (found_match.match_len > 0) {
3812 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3813 if (found_mr.pos_len > 0) {
3814 match.FillResults(found_mr);
3815 return found_mr.pos_len;
3819 // Stop if begin of document reached
3820 if (cur == cur_begin)
3822 cur_prev_iter = cur;
3826 if (cur == cur_begin)
3833 } while (!theApp()->longOperationCancelled());
3841 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3842 DocIterator const & cur, int len)
3844 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3846 if (!opt.ignoreformat)
3847 return latexifyFromCursor(cur, len);
3849 return stringifyFromCursor(cur, len);
3853 FindAndReplaceOptions::FindAndReplaceOptions(
3854 docstring const & _find_buf_name, bool _casesensitive,
3855 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3856 docstring const & _repl_buf_name, bool _keep_case,
3857 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3858 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3859 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3860 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3868 /** Check if 'len' letters following cursor are all non-lowercase */
3869 static bool allNonLowercase(Cursor const & cur, int len)
3871 pos_type beg_pos = cur.selectionBegin().pos();
3872 pos_type end_pos = cur.selectionBegin().pos() + len;
3873 if (len > cur.lastpos() + 1 - beg_pos) {
3874 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3875 len = cur.lastpos() + 1 - beg_pos;
3876 end_pos = beg_pos + len;
3878 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3879 if (isLowerCase(cur.paragraph().getChar(pos)))
3885 /** Check if first letter is upper case and second one is lower case */
3886 static bool firstUppercase(Cursor const & cur)
3889 pos_type pos = cur.selectionBegin().pos();
3890 if (pos >= cur.lastpos() - 1) {
3891 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3894 ch1 = cur.paragraph().getChar(pos);
3895 ch2 = cur.paragraph().getChar(pos + 1);
3896 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3897 LYXERR(Debug::FIND, "firstUppercase(): "
3898 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3899 << ch2 << "(" << char(ch2) << ")"
3900 << ", result=" << result << ", cur=" << cur);
3905 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3907 ** \fixme What to do with possible further paragraphs in replace buffer ?
3909 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3911 ParagraphList::iterator pit = buffer.paragraphs().begin();
3912 LASSERT(!pit->empty(), /**/);
3913 pos_type right = pos_type(1);
3914 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3915 right = pit->size();
3916 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3920 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3922 // Should replace the string "$" + std::to_string(matchnum) with replacement
3923 // if the char '$' is not prefixed with odd number of char '\\'
3924 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3928 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3930 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3932 int num = stoi(sub.str(3), nullptr, 10);
3933 if (num >= maxmatchnum)
3935 if (lastpos < (size_t) sub.position(2))
3936 s += t.substr(lastpos, sub.position(2) - lastpos);
3937 s += replacements[num];
3938 lastpos = sub.position(2) + sub.length(2);
3942 else if (lastpos < t.length())
3943 s += t.substr(lastpos, t.length() - lastpos);
3949 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3951 Cursor & cur = bv->cursor();
3952 if (opt.repl_buf_name.empty()
3953 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3954 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3957 DocIterator sel_beg = cur.selectionBegin();
3958 DocIterator sel_end = cur.selectionEnd();
3959 if (&sel_beg.inset() != &sel_end.inset()
3960 || sel_beg.pit() != sel_end.pit()
3961 || sel_beg.idx() != sel_end.idx())
3963 int sel_len = sel_end.pos() - sel_beg.pos();
3964 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3965 << ", sel_len: " << sel_len << endl);
3968 LASSERT(sel_len > 0, return 0);
3970 if (!matchAdv(sel_beg, sel_len).match_len)
3973 // Build a copy of the replace buffer, adapted to the KeepCase option
3974 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
3976 repl_buffer_orig.write(oss);
3977 string lyx = oss.str();
3978 if (matchAdv.valid_matches > 0) {
3979 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
3981 Buffer repl_buffer("", false);
3982 repl_buffer.setUnnamed(true);
3983 LASSERT(repl_buffer.readString(lyx), return 0);
3984 if (opt.keep_case && sel_len >= 2) {
3985 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
3986 if (cur.inTexted()) {
3987 if (firstUppercase(cur))
3988 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
3989 else if (allNonLowercase(cur, sel_len))
3990 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
3993 cap::cutSelection(cur, false);
3994 if (cur.inTexted()) {
3995 repl_buffer.changeLanguage(
3996 repl_buffer.language(),
3997 cur.getFont().language());
3998 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
3999 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4000 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4001 repl_buffer.params().documentClassPtr(),
4002 bv->buffer().errorList("Paste"));
4003 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4004 sel_len = repl_buffer.paragraphs().begin()->size();
4005 } else if (cur.inMathed()) {
4006 odocstringstream ods;
4008 // OutputParams runparams(&repl_buffer.params().encoding());
4009 OutputParams runparams(encodings.fromLyXName("utf8"));
4010 runparams.nice = false;
4011 runparams.flavor = Flavor::XeTeX;
4012 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4013 runparams.dryrun = true;
4014 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4015 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4016 docstring repl_latex = ods.str();
4017 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4019 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4020 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4021 repl_latex = from_utf8(s);
4022 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4023 MathData ar(cur.buffer());
4024 asArray(repl_latex, ar, Parse::NORMAL);
4026 sel_len = ar.size();
4027 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4029 if (cur.pos() >= sel_len)
4030 cur.pos() -= sel_len;
4033 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4034 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4035 bv->processUpdateFlags(Update::Force);
4040 /// Perform a FindAdv operation.
4041 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4046 // e.g., when invoking word-findadv from mini-buffer wither with
4047 // wrong options syntax or before ever opening advanced F&R pane
4048 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4052 MatchStringAdv matchAdv(bv->buffer(), opt);
4054 if (!matchAdv.regexIsValid) {
4055 bv->message(lyx::from_utf8(matchAdv.regexError));
4059 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4061 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4062 num_replaced += findAdvReplace(bv, opt, matchAdv);
4065 pos_len = findForwardAdv(cur, matchAdv);
4067 pos_len = findBackwardsAdv(cur, matchAdv);
4068 } catch (exception & ex) {
4069 bv->message(from_utf8(ex.what()));
4074 if (num_replaced > 0) {
4075 switch (num_replaced)
4078 bv->message(_("One match has been replaced."));
4081 bv->message(_("Two matches have been replaced."));
4084 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4090 bv->message(_("Match not found."));
4095 if (num_replaced > 0)
4096 bv->message(_("Match has been replaced."));
4098 bv->message(_("Match found."));
4100 if (cur.pos() + pos_len > cur.lastpos()) {
4101 // Prevent crash in bv->putSelectionAt()
4102 // Should never happen, maybe LASSERT() here?
4103 pos_len = cur.lastpos() - cur.pos();
4105 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4106 bv->putSelectionAt(cur, pos_len, !opt.forward);
4112 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4114 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4115 << opt.casesensitive << ' '
4116 << opt.matchword << ' '
4117 << opt.forward << ' '
4118 << opt.expandmacros << ' '
4119 << opt.ignoreformat << ' '
4120 << opt.replace_all << ' '
4121 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4122 << opt.keep_case << ' '
4123 << int(opt.scope) << ' '
4126 LYXERR(Debug::FIND, "built: " << os.str());
4132 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4134 // LYXERR(Debug::FIND, "parsing");
4138 while (line != "EOSS") {
4142 if (is.eof()) // Tolerate malformed request
4146 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4147 opt.find_buf_name = from_utf8(s);
4148 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4149 is.get(); // Waste space before replace string
4152 while (line != "EOSS") {
4156 if (is.eof()) // Tolerate malformed request
4160 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4161 opt.repl_buf_name = from_utf8(s);
4162 is >> opt.keep_case;
4165 opt.scope = FindAndReplaceOptions::SearchScope(i);
4167 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4170 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4171 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4172 << opt.scope << ' ' << opt.restr);