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 docstring const string2find(docstring const & argument,
467 // data is of the form
469 // <casesensitive> <matchword> <forward>"
471 docstring howto = split(argument, search, '\n');
473 casesensitive = parse_bool(howto);
474 matchword = parse_bool(howto);
475 forward = parse_bool(howto);
481 bool lyxfind(BufferView * bv, FuncRequest const & ev)
483 if (!bv || ev.action() != LFUN_WORD_FIND)
486 //lyxerr << "find called, cmd: " << ev << endl;
490 docstring search = string2find(ev.argument(), casesensitive, matchword, forward);
492 return findOne(bv, search, casesensitive, matchword, forward, false, true);
496 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
498 if (!bv || ev.action() != LFUN_WORD_REPLACE)
501 // data is of the form
504 // <casesensitive> <matchword> <all> <forward> <findnext>"
507 docstring howto = split(ev.argument(), rplc, '\n');
508 howto = split(howto, search, '\n');
510 bool casesensitive = parse_bool(howto);
511 bool matchword = parse_bool(howto);
512 bool all = parse_bool(howto);
513 bool forward = parse_bool(howto);
514 bool findnext = howto.empty() ? true : parse_bool(howto);
518 int replace_count = 0;
520 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
521 update = replace_count > 0;
524 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
526 replace_count = rv.second;
529 Buffer const & buf = bv->buffer();
531 // emit message signal.
532 buf.message(_("String not found."));
534 if (replace_count == 0) {
535 buf.message(_("String found."));
536 } else if (replace_count == 1) {
537 buf.message(_("String has been replaced."));
539 docstring const str =
540 bformat(_("%1$d strings have been replaced."), replace_count);
548 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
550 for (; cur; cur.forwardPos())
551 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
555 DocIterator cur_orig(bv->cursor());
556 docstring q = _("End of file reached while searching forward.\n"
557 "Continue searching from the beginning?");
558 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
559 q, 0, 1, _("&Yes"), _("&No"));
560 if (wrap_answer == 0) {
561 bv->cursor().clear();
562 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
563 bv->clearSelection();
564 cur.setCursor(bv->cursor().selectionBegin());
565 if (findNextChange(bv, cur, false))
568 bv->cursor().setCursor(cur_orig);
575 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
577 for (cur.backwardPos(); cur; cur.backwardPos()) {
578 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
583 DocIterator cur_orig(bv->cursor());
584 docstring q = _("Beginning of file reached while searching backward.\n"
585 "Continue searching from the end?");
586 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
587 q, 0, 1, _("&Yes"), _("&No"));
588 if (wrap_answer == 0) {
589 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
590 bv->cursor().backwardPos();
591 bv->clearSelection();
592 cur.setCursor(bv->cursor().selectionBegin());
593 if (findPreviousChange(bv, cur, false))
596 bv->cursor().setCursor(cur_orig);
603 bool selectChange(Cursor & cur, bool forward)
605 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
607 Change ch = cur.paragraph().lookupChange(cur.pos());
609 CursorSlice tip1 = cur.top();
610 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
611 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
612 if (!ch2.isSimilarTo(ch))
615 CursorSlice tip2 = cur.top();
616 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
618 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
619 if (!ch2.isSimilarTo(ch)) {
620 // take a step forward to correctly set the selection
628 cur.bv().mouseSetCursor(cur, false);
630 cur.bv().mouseSetCursor(cur, true);
638 bool findChange(BufferView * bv, bool forward)
641 cur.setCursor(forward ? bv->cursor().selectionEnd()
642 : bv->cursor().selectionBegin());
643 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
644 return selectChange(cur, forward);
649 bool findNextChange(BufferView * bv)
651 return findChange(bv, true);
655 bool findPreviousChange(BufferView * bv)
657 return findChange(bv, false);
664 typedef vector<pair<string, string> > Escapes;
666 string string2regex(string in)
668 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
669 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
674 while (fl_pos < temp.size()) {
675 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
676 if (fl_pos == string::npos)
679 temp2 += temp.substr(lastpos, fl_pos - lastpos);
685 if (lastpos < temp.size()) {
686 temp2 += temp.substr(lastpos, temp.size() - lastpos);
691 string correctRegex(string t, bool withformat)
693 /* Convert \backslash => \
694 * and \{, \}, \[, \] => {, }, [, ]
697 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
700 bool backslashed = false;
701 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
704 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
708 if (sub.str(4) == "backslash") {
711 // transforms '\backslash \{' into '\{'
713 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
714 if ((next == "\\{") || (next == "\\}")) {
720 else if (sub.str(4) == "mathcircumflex")
722 else if (backslashed) {
724 if (withformat && (sub.str(3) == "{"))
725 replace = accents["braceleft"];
726 else if (withformat && (sub.str(3) == "}"))
727 replace = accents["braceright"];
729 // else part should not exist
734 replace = sub.str(3);
736 if (lastpos < (size_t) sub.position(2))
737 s += t.substr(lastpos, sub.position(2) - lastpos);
739 lastpos = sub.position(2) + sub.length(2);
743 else if (lastpos < t.length())
744 s += t.substr(lastpos, t.length() - lastpos);
748 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
749 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
750 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
751 string escape_for_regex(string s, bool withformat)
755 while (lastpos < s.size()) {
756 size_t regex_pos = s.find("\\regexp{", lastpos);
757 if (regex_pos == string::npos) {
758 regex_pos = s.size();
760 if (regex_pos > lastpos) {
761 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
763 if (lastpos == s.size())
766 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
767 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
768 lastpos = end_pos + 13;
774 /// Wrapper for lyx::regex_replace with simpler interface
775 bool regex_replace(string const & s, string & t, string const & searchstr,
776 string const & replacestr)
778 regex e(searchstr, regex_constants::ECMAScript);
780 ostream_iterator<char, char> it(oss);
781 regex_replace(it, s.begin(), s.end(), e, replacestr);
782 // tolerate t and s be references to the same variable
783 bool rv = (s != oss.str());
802 vector <string> result = vector <string>();
803 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
806 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
808 if (newres.match2end < oldres.match2end)
809 return MatchResult::newIsTooFar;
810 if (newres.match_len < oldres.match_len)
811 return MatchResult::newIsTooFar;
813 if (newres.match_len == oldres.match_len) {
814 if (newres.match2end == oldres.match2end)
815 return MatchResult::newIsBetter;
817 return MatchResult::newIsInvalid;
820 /** The class performing a match between a position in the document and the FindAdvOptions.
823 class MatchStringAdv {
825 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
827 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
828 ** constructor as opt.search, under the opt.* options settings.
831 ** If set, then match is searched only against beginning of text starting at cur.
832 ** If unset, then match is searched anywhere in text starting at cur.
835 ** The length of the matching text, or zero if no match was found.
837 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
846 /// first buffer on which search was started
847 lyx::Buffer * const p_first_buf;
849 FindAndReplaceOptions const & opt;
852 /// Auxiliary find method (does not account for opt.matchword)
853 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
854 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
856 /** Normalize a stringified or latexified LyX paragraph.
860 ** <li>if search is not casesensitive, then lowercase the string;
861 ** <li>remove any newline at begin or end of the string;
862 ** <li>replace any newline in the middle of the string with a simple space;
863 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
866 ** @todo Normalization should also expand macros, if the corresponding
867 ** search option was checked.
869 string normalize(docstring const & s) const;
870 // normalized string to search
871 string par_as_string;
872 // regular expression to use for searching
873 // regexp2 is same as regexp, but prefixed with a ".*?"
875 QRegularExpression regexp;
876 QRegularExpression regexp2;
881 // leading format material as string
882 string lead_as_string;
883 // par_as_string after removal of lead_as_string
884 string par_as_string_nolead;
885 // unmatched open braces in the search string/regexp
887 // number of (.*?) subexpressions added at end of search regexp for closing
888 // environments, math mode, styles, etc...
891 // Are we searching with regular expressions ?
893 static int valid_matches;
894 static vector <string> matches;
895 void FillResults(MatchResult &found_mr);
898 int MatchStringAdv::valid_matches = 0;
899 vector <string> MatchStringAdv::matches = vector <string>(10);
901 void MatchStringAdv::FillResults(MatchResult &found_mr)
903 if (found_mr.match_len > 0) {
904 valid_matches = found_mr.result.size();
905 for (size_t i = 0; i < found_mr.result.size(); i++)
906 matches[i] = found_mr.result[i];
912 static docstring buffer_to_latex(Buffer & buffer)
914 //OutputParams runparams(&buffer.params().encoding());
915 OutputParams runparams(encodings.fromLyXName("utf8"));
916 odocstringstream ods;
918 runparams.nice = true;
919 runparams.flavor = Flavor::XeTeX;
920 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
921 // No side effect of file copying and image conversion
922 runparams.dryrun = true;
923 if (ignoreFormats.getDeleted())
924 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
926 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
927 pit_type const endpit = buffer.paragraphs().size();
928 for (pit_type pit = 0; pit != endpit; ++pit) {
929 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
930 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
936 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
939 if (!opt.ignoreformat) {
940 str = buffer_to_latex(buffer);
942 // OutputParams runparams(&buffer.params().encoding());
943 OutputParams runparams(encodings.fromLyXName("utf8"));
944 runparams.nice = true;
945 runparams.flavor = Flavor::XeTeX;
946 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
947 runparams.dryrun = true;
948 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
949 if (ignoreFormats.getDeleted()) {
950 option |= AS_STR_SKIPDELETE;
951 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
954 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
956 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
957 Paragraph const & par = buffer.paragraphs().at(pit);
958 LYXERR(Debug::FIND, "Adding to search string: '"
959 << par.asString(pos_type(0), par.size(),
963 str += par.asString(pos_type(0), par.size(),
967 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
968 string t = to_utf8(str);
969 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
976 /// Return separation pos between the leading material and the rest
977 static size_t identifyLeading(string const & s)
980 // @TODO Support \item[text]
981 // Kornel: Added textsl, textsf, textit, texttt and noun
982 // + allow to search for colored text too
983 while (regex_replace(t, t, "^\\\\(("
984 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
985 "lyxaddress|lyxrightaddress|"
986 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
987 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
988 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
989 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
990 || regex_replace(t, t, "^\\$", "")
991 || regex_replace(t, t, "^\\\\\\[", "")
992 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
993 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
995 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1000 * Given a latexified string, retrieve some handled features
1001 * The features of the regex will later be compared with the features
1002 * of the searched text. If the regex features are not a
1003 * subset of the analized, then, in not format ignoring search
1004 * we can early stop the search in the relevant inset.
1006 typedef map<string, bool> Features;
1008 static Features identifyFeatures(string const & s)
1010 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1011 static regex const valid("^("
1013 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1014 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1015 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1016 "(u|uu)line|(s|x)out|uwave|"
1017 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1018 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1023 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1026 if (sub.str(1).compare("regexp") == 0) {
1030 string token = sub.str(1);
1032 if (regex_match(token, sub2, valid)) {
1040 if (sub.str(1).compare("endregexp") == 0) {
1050 * defines values features of a key "\\[a-z]+{"
1055 /* Char type with content discarded
1056 * like \hspace{1cm} */
1058 /* Char, like \backslash */
1060 /* replace starting backslash with '#' */
1062 /* \part, \section*, ... */
1064 /* title, author etc */
1066 /* \foreignlanguage{ngerman}, ... */
1069 * to discard language in content */
1072 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1074 /* fonts, colors, markups, ... */
1076 /* footnotesize, ... large, ...
1077 * Ignore all of them */
1080 /* inputencoding, ...
1081 * Discard also content, because they do not help in search */
1084 * like remove, but also all arguments */
1086 /* item, listitem */
1088 /* tex, latex, ... like isChar */
1090 /* like \lettrine[lines=5]{}{} */
1092 // like isStandard, but always remove head
1094 /* End of arguments marker for lettrine,
1095 * so that they can be ignored */
1098 KeyInfo() = default;
1099 KeyInfo(KeyType type, int parcount, bool disable)
1101 parenthesiscount(parcount),
1102 disabled(disable) {}
1103 KeyType keytype = invalid;
1105 int _tokensize = -1;
1106 int _tokenstart = -1;
1107 int _dataStart = -1;
1109 int parenthesiscount = 1;
1110 bool disabled = false;
1111 bool used = false; /* by pattern */
1116 Border(int l=0, int u=0) : low(l), upper(u) {};
1121 #define MAXOPENED 30
1123 bool isPatternString_;
1125 explicit Intervall(bool isPattern, string const & p) :
1126 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1127 hasTitle(false), langcount(0)
1135 static vector<Border> borders;
1136 int depts[MAXOPENED];
1137 int closes[MAXOPENED];
1138 int actualdeptindex;
1139 int previousNotIgnored(int) const;
1140 int nextNotIgnored(int) const;
1141 void handleOpenP(int i);
1142 void handleCloseP(int i, bool closingAllowed);
1143 void resetOpenedP(int openPos);
1144 void addIntervall(int upper);
1145 void addIntervall(int low, int upper); /* if explicit */
1146 void removeAccents();
1147 void setForDefaultLang(KeyInfo const & defLang) const;
1148 int findclosing(int start, int end, char up, char down, int repeat);
1149 void handleParentheses(int lastpos, bool closingAllowed);
1151 int langcount; // Number of disabled language specs up to current position in actual interval
1152 int isOpeningPar(int pos) const;
1154 void output(ostringstream &os, int lastpos);
1155 // string show(int lastpos);
1158 vector<Border> Intervall::borders = vector<Border>(30);
1160 int Intervall::isOpeningPar(int pos) const
1162 if ((pos < 0) || (size_t(pos) >= par.size()))
1164 if (par[pos] != '{')
1166 if (size_t(pos) + 2 >= par.size())
1168 if (par[pos+2] != '}')
1170 if (par[pos+1] == '[' || par[pos+1] == ']')
1175 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1177 // Enable the use of first token again
1178 if (ignoreidx >= 0) {
1179 int value = defLang._tokenstart + defLang._tokensize;
1185 if (borders[borderidx].low < value)
1186 borders[borderidx].low = value;
1187 if (borders[borderidx].upper < value)
1188 borders[borderidx].upper = value;
1193 static void checkDepthIndex(int val)
1195 static int maxdepthidx = MAXOPENED-2;
1196 static int lastmaxdepth = 0;
1197 if (val > lastmaxdepth) {
1198 LYXERR(Debug::INFO, "Depth reached " << val);
1201 if (val > maxdepthidx) {
1203 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1208 // Not needed, because borders are now dynamically expanded
1209 static void checkIgnoreIdx(int val)
1211 static int lastmaxignore = -1;
1212 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1213 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1214 lastmaxignore = val;
1220 * Expand the region of ignored parts of the input latex string
1221 * The region is only relevant in output()
1223 void Intervall::addIntervall(int low, int upper)
1226 if (low == upper) return;
1227 for (idx = ignoreidx+1; idx > 0; --idx) {
1228 if (low > borders[idx-1].upper) {
1232 Border br(low, upper);
1233 if (idx > ignoreidx) {
1234 if (borders.size() <= size_t(idx)) {
1235 borders.push_back(br);
1241 // checkIgnoreIdx(ignoreidx);
1245 // Expand only if one of the new bound is inside the interwall
1246 // We know here that br.low > borders[idx-1].upper
1247 if (br.upper < borders[idx].low) {
1248 // We have to insert at this pos
1249 if (size_t(ignoreidx+1) >= borders.size()) {
1250 borders.push_back(borders[ignoreidx]);
1253 borders[ignoreidx+1] = borders[ignoreidx];
1255 for (int i = ignoreidx; i > idx; --i) {
1256 borders[i] = borders[i-1];
1260 // checkIgnoreIdx(ignoreidx);
1263 // Here we know, that we are overlapping
1264 if (br.low > borders[idx].low)
1265 br.low = borders[idx].low;
1266 // check what has to be concatenated
1268 for (int i = idx; i <= ignoreidx; i++) {
1269 if (br.upper >= borders[i].low) {
1271 if (br.upper < borders[i].upper)
1272 br.upper = borders[i].upper;
1278 // count should be >= 1 here
1281 for (int i = idx + count; i <= ignoreidx; i++) {
1282 borders[i-count+1] = borders[i];
1284 ignoreidx -= count - 1;
1290 static void buildaccent(string n, string param, string values)
1294 const char delim = '|';
1295 while (getline(s, name, delim)) {
1297 for (char c : param) {
1298 string key = name + "{" + c + "}";
1299 // get the corresponding utf8-value
1300 if ((values[start] & 0xc0) != 0xc0) {
1301 // should not happen, utf8 encoding starts at least with 11xxxxxx
1302 // but value for '\dot{i}' is 'i', which is ascii
1303 if ((values[start] & 0x80) == 0) {
1305 accents[key] = values.substr(start, 1);
1306 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1311 for (int j = 1; ;j++) {
1312 if (start + j >= values.size()) {
1313 accents[key] = values.substr(start, j);
1314 start = values.size() - 1;
1317 else if ((values[start+j] & 0xc0) != 0x80) {
1318 // This is the first byte of following utf8 char
1319 accents[key] = values.substr(start, j);
1321 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1330 static string getutf8(unsigned uchar)
1333 string ret = string();
1335 if (uchar <= 0x7f) {
1336 c[maxc-1] = uchar & 0x7f;
1339 unsigned char rest = 0x40;
1340 unsigned char first = 0x80;
1342 for (int i = start; i >=0; --i) {
1344 c[i] = first + uchar;
1347 c[i] = 0x80 | (uchar & 0x3f);
1354 for (int i = 0; i < maxc; i++) {
1355 if (c[i] == 0) continue;
1361 static void buildAccentsMap()
1363 accents["imath"] = "ı";
1365 accents["jmath"] = "ȷ";
1366 accents["cdot"] = "·";
1367 accents["textasciicircum"] = "^";
1368 accents["mathcircumflex"] = "^";
1369 accents["sim"] = "~";
1370 accents["guillemotright"] = "»";
1371 accents["guillemotleft"] = "«";
1372 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1373 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1374 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1375 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1376 accents["negmedspace"] = getutf8(0xf0005);
1377 accents["thickspace"] = getutf8(0xf0006);
1378 accents["negthickspace"] = getutf8(0xf0007);
1379 accents["lyx"] = getutf8(0xf0010); // Used logos
1380 accents["LyX"] = getutf8(0xf0010);
1381 accents["tex"] = getutf8(0xf0011);
1382 accents["TeX"] = getutf8(0xf0011);
1383 accents["latex"] = getutf8(0xf0012);
1384 accents["LaTeX"] = getutf8(0xf0012);
1385 accents["latexe"] = getutf8(0xf0013);
1386 accents["LaTeXe"] = getutf8(0xf0013);
1387 accents["lyxarrow"] = getutf8(0xf0020);
1388 accents["braceleft"] = getutf8(0xf0030);
1389 accents["braceright"] = getutf8(0xf0031);
1390 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1391 accents["backslash LyX"] = getutf8(0xf0010);
1392 accents["backslash tex"] = getutf8(0xf0011);
1393 accents["backslash TeX"] = getutf8(0xf0011);
1394 accents["backslash latex"] = getutf8(0xf0012);
1395 accents["backslash LaTeX"] = getutf8(0xf0012);
1396 accents["backslash latexe"] = getutf8(0xf0013);
1397 accents["backslash LaTeXe"] = getutf8(0xf0013);
1398 accents["backslash lyxarrow"] = getutf8(0xf0020);
1399 accents["ddot{\\imath}"] = "ï";
1400 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1401 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1402 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1403 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1404 accents["acute{\\imath}"] = "í";
1405 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1406 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1407 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1408 buildaccent("mathring|r", "aAuUwy",
1410 accents["check{\\imath}"] = "ǐ";
1411 accents["check{\\jmath}"] = "ǰ";
1412 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1413 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1414 accents["hat{\\imath}"] = "î";
1415 accents["hat{\\jmath}"] = "ĵ";
1416 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1417 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1418 accents["bar{\\imath}"] = "ī";
1419 buildaccent("bar|=", "aAeEiIoOuUyY",
1420 "āĀēĒīĪōŌūŪȳȲ"); // macron
1421 accents["tilde{\\imath}"] = "ĩ";
1422 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1423 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1424 accents["breve{\\imath}"] = "ĭ";
1425 buildaccent("breve|u", "aAeEgGiIoOuU",
1426 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1427 accents["grave{\\imath}"] = "ì";
1428 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1429 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1430 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1431 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1432 buildaccent("ogonek|k", "AaEeIiUuOo",
1433 "ĄąĘęĮįŲųǪǫ"); // ogonek
1434 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1435 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1436 buildaccent("subring|textsubring", "Aa",
1438 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1439 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1440 buildaccent("subtilde|textsubtilde", "EeIiUu",
1441 "ḚḛḬḭṴṵ"); // subtilde
1442 accents["dgrave{\\imath}"] = "ȉ";
1443 accents["textdoublegrave{\\i}"] = "ȉ";
1444 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1445 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1446 accents["rcap{\\imath}"] = "ȉ";
1447 accents["textroundcap{\\i}"] = "ȉ";
1448 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1449 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1450 buildaccent("slashed", "oO",
1455 * Created accents in math or regexp environment
1456 * are macros, but we need the utf8 equivalent
1458 void Intervall::removeAccents()
1460 if (accents.empty())
1462 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1463 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1464 "|((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]))");
1466 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1468 string key = sub.str(1);
1469 AccentsIterator it_ac = accents.find(key);
1470 if (it_ac != accents.end()) {
1471 string val = it_ac->second;
1472 size_t pos = sub.position(size_t(0));
1473 for (size_t i = 0; i < val.size(); i++) {
1474 par[pos+i] = val[i];
1476 // Remove possibly following space too
1477 if (par[pos+sub.str(0).size()] == ' ')
1478 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1480 addIntervall(pos+val.size(), pos + sub.str(0).size());
1481 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1482 // remove traces of any remaining chars
1487 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1492 void Intervall::handleOpenP(int i)
1495 depts[actualdeptindex] = i+1;
1496 closes[actualdeptindex] = -1;
1497 checkDepthIndex(actualdeptindex);
1500 void Intervall::handleCloseP(int i, bool closingAllowed)
1502 if (actualdeptindex <= 0) {
1503 if (! closingAllowed)
1504 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1505 // if we are at the very end
1506 addIntervall(i, i+1);
1509 closes[actualdeptindex] = i+1;
1514 void Intervall::resetOpenedP(int openPos)
1516 // Used as initializer for foreignlanguage entry
1517 actualdeptindex = 1;
1518 depts[1] = openPos+1;
1522 int Intervall::previousNotIgnored(int start) const
1524 int idx = 0; /* int intervalls */
1525 for (idx = ignoreidx; idx >= 0; --idx) {
1526 if (start > borders[idx].upper)
1528 if (start >= borders[idx].low)
1529 start = borders[idx].low-1;
1534 int Intervall::nextNotIgnored(int start) const
1536 int idx = 0; /* int intervalls */
1537 for (idx = 0; idx <= ignoreidx; idx++) {
1538 if (start < borders[idx].low)
1540 if (start < borders[idx].upper)
1541 start = borders[idx].upper;
1546 typedef unordered_map<string, KeyInfo> KeysMap;
1547 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1548 typedef vector< KeyInfo> Entries;
1549 static KeysMap keys = unordered_map<string, KeyInfo>();
1555 Intervall interval_;
1556 void buildKeys(bool);
1557 void buildEntries(bool);
1558 void makeKey(const string &, KeyInfo, bool isPatternString);
1559 void processRegion(int start, int region_end); /* remove {} parts */
1560 void removeHead(KeyInfo const &, int count=0);
1563 LatexInfo(string const & par, bool isPatternString)
1564 : entidx_(-1), interval_(isPatternString, par)
1566 buildKeys(isPatternString);
1567 entries_ = vector<KeyInfo>();
1568 buildEntries(isPatternString);
1572 if (entries_.empty()) {
1575 if (entries_[0].keytype == KeyInfo::isTitle) {
1576 interval_.hasTitle = true;
1577 if (! entries_[0].disabled) {
1578 interval_.titleValue = entries_[0].head;
1581 interval_.titleValue = "";
1583 removeHead(entries_[0]);
1584 if (entries_.size() > 1)
1593 if (int(entries_.size()) > entidx_) {
1600 bool setNextKey(int idx) {
1601 if ((idx == entidx_) && (entidx_ >= 0)) {
1608 int find(int start, KeyInfo::KeyType keytype) const {
1612 while (tmpIdx < int(entries_.size())) {
1613 if (entries_[tmpIdx].keytype == keytype)
1619 int process(ostringstream & os, KeyInfo const & actual);
1620 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1621 // string show(int lastpos) { return interval.show(lastpos);};
1622 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1623 KeyInfo &getKeyInfo(int keyinfo) {
1624 static KeyInfo invalidInfo = KeyInfo();
1625 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1628 return entries_[keyinfo];
1630 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1631 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1635 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1639 for (int i = start; i < end; i += 1 + skip) {
1643 if (c == '\\') skip = 1;
1647 else if (c == down) {
1650 if ((repeat <= 0) || (par[i+1] != up))
1664 size_t mathpostfixsize;
1666 size_t mathprefixsize;
1670 vector<MathEntry> entries_;
1675 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1676 MathEntry m = MathEntry();
1678 m.mathStart = start;
1679 m.mathprefixsize = prefixsize;
1681 m.mathpostfixsize = postfixsize;
1682 m.mathSize = end - start;
1683 entries_.push_back(m);
1685 bool empty() const { return entries_.empty(); };
1686 size_t getEndPos() const {
1687 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1690 return entries_[actualIdx_].mathEnd;
1692 size_t getStartPos() const {
1693 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1694 return 100000; /* definitely enough? */
1696 return entries_[actualIdx_].mathStart;
1698 size_t getPrefixSize() const {
1699 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1702 return entries_[actualIdx_].mathprefixsize;
1704 size_t getPostfixSize() const {
1705 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1708 return entries_[actualIdx_].mathpostfixsize;
1710 size_t getFirstPos() {
1712 return getStartPos();
1714 size_t getSize() const {
1715 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1718 return entries_[actualIdx_].mathSize;
1720 void incrEntry() { actualIdx_++; };
1723 void LatexInfo::buildEntries(bool isPatternString)
1725 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1726 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1727 static bool disableLanguageOverride = false;
1728 smatch sub, submath;
1729 bool evaluatingRegexp = false;
1731 bool evaluatingMath = false;
1732 bool evaluatingCode = false;
1734 bool evaluatingOptional = false;
1735 size_t optionalEnd = 0;
1738 bool math_end_waiting = false;
1739 size_t math_pos = 10000;
1740 size_t math_prefix_size = 1;
1742 static vector<string> usedText = vector<string>();
1743 static bool removeMathHull = false;
1745 interval_.removeAccents();
1747 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1749 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1750 // prefixed by odd count of '\\'
1753 if (math_end_waiting) {
1754 size_t pos = submath.position(size_t(2));
1755 if ((math_end == "$") &&
1756 (submath.str(2) == "$")) {
1757 mi.insert("$", math_pos, 1, pos + 1, 1);
1758 math_end_waiting = false;
1760 else if ((math_end == "\\]") &&
1761 (submath.str(2) == "\\]")) {
1762 mi.insert("\\]", math_pos, 2, pos + 2, 2);
1763 math_end_waiting = false;
1765 else if ((submath.str(3).compare("end") == 0) &&
1766 (submath.str(4).compare(math_end) == 0)) {
1767 mi.insert(math_end, math_pos, math_prefix_size, pos + submath.str(2).length(), submath.str(2).length());
1768 math_end_waiting = false;
1774 if (submath.str(3).compare("begin") == 0) {
1775 math_end_waiting = true;
1776 math_end = submath.str(4);
1777 math_pos = submath.position(size_t(2));
1778 math_prefix_size = submath.str(2).length();
1780 else if (submath.str(2).compare("\\[") == 0) {
1781 math_end_waiting = true;
1783 math_pos = submath.position(size_t(2));
1785 else if (submath.str(2) == "$") {
1786 size_t pos = submath.position(size_t(2));
1787 math_end_waiting = true;
1793 // Ignore language if there is math somewhere in pattern-string
1794 if (isPatternString) {
1795 for (auto s: usedText) {
1796 // Remove entries created in previous search runs
1799 usedText = vector<string>();
1802 keys["foreignlanguage"].disabled = true;
1803 disableLanguageOverride = true;
1804 removeMathHull = false;
1807 removeMathHull = true; // used later if not isPatternString
1808 disableLanguageOverride = false;
1812 if (disableLanguageOverride) {
1813 keys["foreignlanguage"].disabled = true;
1816 math_pos = mi.getFirstPos();
1817 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1819 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1820 // prefixed by odd count of '\\'
1823 string key = sub.str(5);
1825 if (sub.str(2)[0] == '\\')
1826 key = sub.str(2)[1];
1831 KeysIterator it_key = keys.find(key);
1832 if (it_key != keys.end()) {
1833 if (it_key->second.keytype == KeyInfo::headRemove) {
1834 KeyInfo found1 = it_key->second;
1835 found1.disabled = true;
1836 found1.head = "\\" + key + "{";
1837 found1._tokenstart = sub.position(size_t(2));
1838 found1._tokensize = found1.head.length();
1839 found1._dataStart = found1._tokenstart + found1.head.length();
1840 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1841 found1._dataEnd = endpos;
1846 if (evaluatingRegexp) {
1847 if (sub.str(3).compare("endregexp") == 0) {
1848 evaluatingRegexp = false;
1849 // found._tokenstart already set
1850 found._dataEnd = sub.position(size_t(2)) + 13;
1851 found._dataStart = found._dataEnd;
1852 found._tokensize = found._dataEnd - found._tokenstart;
1853 found.parenthesiscount = 0;
1854 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1861 if (evaluatingMath) {
1862 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1864 evaluatingMath = false;
1866 math_pos = mi.getStartPos();
1868 if (it_key == keys.end()) {
1869 found = KeyInfo(KeyInfo::isStandard, 0, true);
1870 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1871 found = KeyInfo(KeyInfo::isText, 0, false);
1872 if (isPatternString) {
1873 found.keytype = KeyInfo::isChar;
1874 found.disabled = false;
1878 usedText.push_back(key);
1882 if (key.compare("regexp") == 0) {
1883 evaluatingRegexp = true;
1884 found._tokenstart = sub.position(size_t(2));
1885 found._tokensize = 0;
1889 // Handle the other params of key
1890 if (found.keytype == KeyInfo::isIgnored)
1892 else if (found.keytype == KeyInfo::isMath) {
1893 if (size_t(sub.position(size_t(2))) == math_pos) {
1895 found._tokenstart = sub.position(size_t(2));
1896 found._tokensize = mi.getSize();
1897 found._dataEnd = found._tokenstart + found._tokensize;
1898 found._dataStart = found._dataEnd;
1899 found.parenthesiscount = 0;
1900 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1901 if (removeMathHull) {
1902 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
1903 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
1905 evaluatingMath = true;
1908 // begin|end of unknown env, discard
1909 // First handle tables
1910 // longtable|tabular
1911 bool discardComment;
1913 found.keytype = KeyInfo::doRemove;
1914 if ((sub.str(7).compare("longtable") == 0) ||
1915 (sub.str(7).compare("tabular") == 0)) {
1916 discardComment = true; /* '%' */
1919 discardComment = false;
1920 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1922 string token = sub.str(7);
1923 if (regex_match(token, sub2, removeArgs)) {
1924 found.keytype = KeyInfo::removeWithArg;
1927 // discard spaces before pos(2)
1928 int pos = sub.position(size_t(2));
1930 for (count = 0; pos - count > 0; count++) {
1931 char c = interval_.par[pos-count-1];
1932 if (discardComment) {
1933 if ((c != ' ') && (c != '%'))
1939 found._tokenstart = pos - count;
1940 if (sub.str(3).compare(0, 5, "begin") == 0) {
1941 size_t pos1 = pos + sub.str(2).length();
1942 if (sub.str(7).compare("cjk") == 0) {
1943 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1944 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1946 found.keytype = KeyInfo::isMain;
1947 found._dataStart = pos1;
1948 found._dataEnd = interval_.par.length();
1949 found.disabled = keys["foreignlanguage"].disabled;
1950 found.used = keys["foreignlanguage"].used;
1951 found._tokensize = pos1 - found._tokenstart;
1952 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1955 // Swallow possible optional params
1956 while (interval_.par[pos1] == '[') {
1957 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1959 // Swallow also the eventual parameter
1960 if (interval_.par[pos1] == '{') {
1961 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1964 found._dataEnd = pos1;
1966 found._dataStart = found._dataEnd;
1967 found._tokensize = count + found._dataEnd - pos;
1968 found.parenthesiscount = 0;
1969 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1970 found.disabled = true;
1974 // Handle "\end{...}"
1975 found._dataStart = pos + sub.str(2).length();
1976 found._dataEnd = found._dataStart;
1977 found._tokensize = count + found._dataEnd - pos;
1978 found.parenthesiscount = 0;
1979 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1980 found.disabled = true;
1984 else if (found.keytype != KeyInfo::isRegex) {
1985 found._tokenstart = sub.position(size_t(2));
1986 if (found.parenthesiscount == 0) {
1987 // Probably to be discarded
1988 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
1989 char following = interval_.par[following_pos];
1990 if (following == ' ')
1991 found.head = "\\" + sub.str(5) + " ";
1992 else if (following == '=') {
1993 // like \uldepth=1000pt
1994 found.head = sub.str(2);
1997 found.head = "\\" + key;
1998 found._tokensize = found.head.length();
1999 found._dataEnd = found._tokenstart + found._tokensize;
2000 found._dataStart = found._dataEnd;
2003 int params = found._tokenstart + key.length() + 1;
2004 if (evaluatingOptional) {
2005 if (size_t(found._tokenstart) > optionalEnd) {
2006 evaluatingOptional = false;
2009 found.disabled = true;
2012 int optend = params;
2013 while (interval_.par[optend] == '[') {
2014 // discard optional parameters
2015 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2017 if (optend > params) {
2018 key += interval_.par.substr(params, optend-params);
2019 evaluatingOptional = true;
2020 optionalEnd = optend;
2021 if (found.keytype == KeyInfo::isSectioning) {
2022 // Remove optional values (but still keep in header)
2023 interval_.addIntervall(params, optend);
2026 string token = sub.str(7);
2028 if (interval_.par[optend] != '{') {
2030 found.parenthesiscount = 0;
2031 found.head = "\\" + key;
2034 closings = found.parenthesiscount;
2035 if (found.parenthesiscount == 1) {
2036 found.head = "\\" + key + "{";
2038 else if (found.parenthesiscount > 1) {
2040 found.head = sub.str(2) + "{";
2041 closings = found.parenthesiscount - 1;
2044 found.head = "\\" + key + "{";
2047 found._tokensize = found.head.length();
2048 found._dataStart = found._tokenstart + found.head.length();
2049 if (found.keytype == KeyInfo::doRemove) {
2051 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2052 if (endpar >= interval_.par.length())
2053 found._dataStart = interval_.par.length();
2055 found._dataStart = endpar;
2056 found._tokensize = found._dataStart - found._tokenstart;
2059 found._dataStart = found._tokenstart + found._tokensize;
2063 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2064 found._dataStart += 15;
2068 endpos = found._dataStart - 1;
2070 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2071 if (found.keytype == KeyInfo::isList) {
2072 // Check if it really is list env
2073 static regex const listre("^([a-z]+)$");
2075 if (!regex_match(token, sub2, listre)) {
2076 // Change the key of this entry. It is not in a list/item environment
2077 found.keytype = KeyInfo::endArguments;
2080 if (found.keytype == KeyInfo::noMain) {
2081 evaluatingCode = true;
2083 codeStart = found._dataStart;
2085 else if (evaluatingCode) {
2086 if (size_t(found._dataStart) > codeEnd)
2087 evaluatingCode = false;
2088 else if (found.keytype == KeyInfo::isMain) {
2089 // Disable this key, treate it as standard
2090 found.keytype = KeyInfo::isStandard;
2091 found.disabled = true;
2092 if ((codeEnd +1 >= interval_.par.length()) &&
2093 (found._tokenstart == codeStart)) {
2094 // trickery, because the code inset starts
2095 // with \selectlanguage ...
2097 if (entries_.size() > 1) {
2098 entries_[entries_.size()-1]._dataEnd = codeEnd;
2103 if ((endpos == interval_.par.length()) &&
2104 (found.keytype == KeyInfo::doRemove)) {
2105 // Missing closing => error in latex-input?
2106 // therefore do not delete remaining data
2107 found._dataStart -= 1;
2108 found._dataEnd = found._dataStart;
2111 found._dataEnd = endpos;
2113 if (isPatternString) {
2114 keys[key].used = true;
2117 entries_.push_back(found);
2121 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2123 stringstream s(keysstring);
2125 const char delim = '|';
2126 while (getline(s, key, delim)) {
2127 KeyInfo keyII(keyI);
2128 if (isPatternString) {
2131 else if ( !keys[key].used)
2132 keyII.disabled = true;
2137 void LatexInfo::buildKeys(bool isPatternString)
2140 static bool keysBuilt = false;
2141 if (keysBuilt && !isPatternString) return;
2143 // Keys to ignore in any case
2144 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2145 // Known standard keys with 1 parameter.
2146 // Split is done, if not at start of region
2147 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2148 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2149 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2150 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2151 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2152 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2154 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2155 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2156 makeKey("section*|subsection*|subsubsection*|paragraph*",
2157 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2158 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2159 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2161 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2163 // Split is done, if not at start of region
2164 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2165 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2167 // Split is done always.
2168 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2172 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2173 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2174 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2175 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2177 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2178 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2179 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2180 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2182 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2183 // Custom space/skip, remove the content (== length value)
2184 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2185 // Found in fr/UserGuide.lyx
2186 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2188 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2189 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2190 // Known macros to remove (including their parameter)
2192 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2193 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2194 // handle like standard keys with 1 parameter.
2195 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2197 // Ignore deleted text
2198 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2199 // but preserve added text
2200 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2202 // Macros to remove, but let the parameter survive
2204 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2206 // Remove language spec from content of these insets
2207 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2209 // Same effect as previous, parameter will survive (because there is no one anyway)
2211 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2212 // Remove table decorations
2213 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2214 // Discard shape-header.
2215 // For footnote or shortcut too, because of lang settings
2216 // and wrong handling if used 'KeyInfo::noMain'
2217 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2218 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2219 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2220 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2221 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2222 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2223 // like ('tiny{}' or '\tiny ' ... )
2224 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2226 // Survives, like known character
2227 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2228 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2229 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2231 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2232 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2233 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2235 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2236 // Remove RTL/LTR marker
2237 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2238 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2239 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2240 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2241 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2242 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2243 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2244 if (isPatternString) {
2245 // Allow the first searched string to rebuild the keys too
2249 // no need to rebuild again
2255 * Keep the list of actual opened parentheses actual
2256 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2258 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2261 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2265 if (c == '\\') skip = 1;
2266 else if (c == '{') {
2269 else if (c == '}') {
2270 handleCloseP(i, closingAllowed);
2276 string Intervall::show(int lastpos)
2278 int idx = 0; /* int intervalls */
2281 for (idx = 0; idx <= ignoreidx; idx++) {
2282 while (i < lastpos) {
2284 if (i <= borders[idx].low) {
2285 if (borders[idx].low > lastpos)
2286 printsize = lastpos - i;
2288 printsize = borders[idx].low - i;
2289 s += par.substr(i, printsize);
2291 if (i >= borders[idx].low)
2292 i = borders[idx].upper;
2295 i = borders[idx].upper;
2301 s += par.substr(i, lastpos-i);
2307 void Intervall::output(ostringstream &os, int lastpos)
2309 // get number of chars to output
2310 int idx = 0; /* int intervalls */
2313 string startTitle = titleValue;
2314 for (idx = 0; idx <= ignoreidx; idx++) {
2316 if (i <= borders[idx].low) {
2318 if (borders[idx].low > lastpos)
2319 printsize = lastpos - i;
2321 printsize = borders[idx].low - i;
2322 if (printsize > 0) {
2323 os << startTitle << par.substr(i, printsize);
2325 printed += printsize;
2328 handleParentheses(i, false);
2329 if (i >= borders[idx].low)
2330 i = borders[idx].upper;
2333 i = borders[idx].upper;
2340 os << startTitle << par.substr(i, lastpos-i);
2341 printed += lastpos-i;
2343 handleParentheses(lastpos, false);
2345 if (keys["foreignlanguage"].disabled)
2346 startindex = actualdeptindex-langcount;
2348 startindex = actualdeptindex;
2349 for (int i = startindex; i > 0; --i) {
2352 if (hasTitle && (printed > 0))
2354 if (! isPatternString_)
2356 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2359 void LatexInfo::processRegion(int start, int region_end)
2361 while (start < region_end) { /* Let {[} and {]} survive */
2362 int cnt = interval_.isOpeningPar(start);
2364 // Closing is allowed past the region
2365 int closing = interval_.findclosing(start+1, interval_.par.length());
2366 interval_.addIntervall(start, start+1);
2367 interval_.addIntervall(closing, closing+1);
2371 start = interval_.nextNotIgnored(start+1);
2375 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2377 if (actual.parenthesiscount == 0) {
2378 // "{\tiny{} ...}" ==> "{{} ...}"
2379 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2382 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2383 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2384 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2388 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2391 switch (actual.keytype)
2393 case KeyInfo::isTitle: {
2395 nextKeyIdx = getNextKey();
2398 case KeyInfo::cleanToStart: {
2399 actual._dataEnd = actual._dataStart;
2400 nextKeyIdx = getNextKey();
2401 // Search for end of arguments
2402 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2404 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2405 entries_[i].disabled = true;
2407 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2409 while (interval_.par[actual._dataEnd] == ' ')
2411 interval_.addIntervall(0, actual._dataEnd+1);
2412 interval_.actualdeptindex = 0;
2413 interval_.depts[0] = actual._dataEnd+1;
2414 interval_.closes[0] = -1;
2417 case KeyInfo::isText:
2418 interval_.par[actual._tokenstart] = '#';
2419 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2420 nextKeyIdx = getNextKey();
2422 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2423 if (actual.disabled)
2424 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2426 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2429 case KeyInfo::isChar: {
2430 nextKeyIdx = getNextKey();
2433 case KeyInfo::isSize: {
2434 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2435 if (actual.parenthesiscount == 0)
2436 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2438 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2440 nextKeyIdx = getNextKey();
2442 // Here _dataStart points to '{', so correct it
2443 actual._dataStart += 1;
2444 actual._tokensize += 1;
2445 actual.parenthesiscount = 1;
2446 if (interval_.par[actual._dataStart] == '}') {
2447 // Determine the end if used like '{\tiny{}...}'
2448 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2449 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2452 // Determine the end if used like '\tiny{...}'
2453 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2455 // Split on this key if not at start
2456 int start = interval_.nextNotIgnored(previousStart);
2457 if (start < actual._tokenstart) {
2458 interval_.output(os, actual._tokenstart);
2459 interval_.addIntervall(start, actual._tokenstart);
2461 // discard entry if at end of actual
2462 nextKeyIdx = process(os, actual);
2466 case KeyInfo::endArguments: {
2467 // Remove trailing '{}' too
2468 actual._dataStart += 1;
2469 actual._dataEnd += 1;
2470 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2471 nextKeyIdx = getNextKey();
2474 case KeyInfo::noMain:
2476 case KeyInfo::isStandard: {
2477 if (actual.disabled) {
2479 processRegion(actual._dataStart, actual._dataStart+1);
2480 nextKeyIdx = getNextKey();
2482 // Split on this key if not at datastart of calling entry
2483 int start = interval_.nextNotIgnored(previousStart);
2484 if (start < actual._tokenstart) {
2485 interval_.output(os, actual._tokenstart);
2486 interval_.addIntervall(start, actual._tokenstart);
2488 // discard entry if at end of actual
2489 nextKeyIdx = process(os, actual);
2493 case KeyInfo::removeWithArg: {
2494 nextKeyIdx = getNextKey();
2495 // Search for end of arguments
2496 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2498 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2499 entries_[i].disabled = true;
2501 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2503 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2506 case KeyInfo::doRemove: {
2507 // Remove the key with all parameters and following spaces
2510 if (interval_.par[actual._dataEnd-1] == ' ')
2511 start = actual._dataEnd;
2513 start = actual._dataEnd+1;
2514 for (pos = start; pos < interval_.par.length(); pos++) {
2515 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2518 // Remove also enclosing parentheses [] and {}
2521 while (actual._tokenstart > numpars) {
2522 if (pos+numpars >= interval_.par.size())
2524 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2526 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2532 if (interval_.par[pos+numpars] == ' ')
2536 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2537 nextKeyIdx = getNextKey();
2540 case KeyInfo::isList: {
2541 // Discard space before _tokenstart
2543 for (count = 0; count < actual._tokenstart; count++) {
2544 if (interval_.par[actual._tokenstart-count-1] != ' ')
2547 nextKeyIdx = getNextKey();
2548 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2550 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2552 // How else can we catch this one?
2553 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2554 entries_[i].disabled = true;
2556 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2558 else if (nextKeyIdx > 0) {
2559 // Ignore any lang entries inside data region
2560 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2561 if (entries_[i].keytype == KeyInfo::isMain)
2562 entries_[i].disabled = true;
2565 if (actual.disabled) {
2566 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2569 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2571 if (interval_.par[actual._dataEnd+1] == '[') {
2572 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2573 if ((interval_.par[actual._dataEnd+2] == '{') &&
2574 (interval_.par[posdown-1] == '}')) {
2575 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2576 interval_.addIntervall(posdown-1, posdown+1);
2579 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2580 interval_.addIntervall(posdown, posdown+1);
2582 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2583 if (blk > posdown) {
2584 // Discard at most 1 space after empty item
2586 for (count = 0; count < 1; count++) {
2587 if (interval_.par[blk+count] != ' ')
2591 interval_.addIntervall(blk, blk+count);
2596 case KeyInfo::isSectioning: {
2597 // Discard spaces before _tokenstart
2599 int val = actual._tokenstart;
2600 for (count = 0; count < actual._tokenstart;) {
2601 val = interval_.previousNotIgnored(val-1);
2602 if (val < 0 || interval_.par[val] != ' ')
2605 count = actual._tokenstart - val;
2608 if (actual.disabled) {
2609 removeHead(actual, count);
2610 nextKeyIdx = getNextKey();
2612 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2613 nextKeyIdx = process(os, actual);
2617 case KeyInfo::isMath: {
2618 // Same as regex, use the content unchanged
2619 nextKeyIdx = getNextKey();
2622 case KeyInfo::isRegex: {
2623 // DO NOT SPLIT ON REGEX
2625 nextKeyIdx = getNextKey();
2628 case KeyInfo::isIgnored: {
2629 // Treat like a character for now
2630 nextKeyIdx = getNextKey();
2633 case KeyInfo::isMain: {
2634 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2635 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2636 if (actual._tokenstart > 0) {
2637 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2638 if ((prev >= 0) && interval_.par[prev] == '%')
2639 interval_.addIntervall(prev, prev+1);
2641 if (actual.disabled) {
2643 interval_.langcount++;
2644 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2645 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2646 // Discard also the space before math-equation
2647 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2649 nextKeyIdx = getNextKey();
2650 // interval.resetOpenedP(actual._dataStart-1);
2653 if (actual._tokenstart < 26) {
2654 // for the first (and maybe dummy) language
2655 interval_.setForDefaultLang(actual);
2657 interval_.resetOpenedP(actual._dataStart-1);
2661 case KeyInfo::invalid:
2662 case KeyInfo::headRemove:
2663 // These two cases cannot happen, already handled
2666 // LYXERR(Debug::INFO, "Unhandled keytype");
2667 nextKeyIdx = getNextKey();
2674 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2676 int end = interval_.nextNotIgnored(actual._dataEnd);
2677 int oldStart = actual._dataStart;
2678 int nextKeyIdx = getNextKey();
2680 if ((nextKeyIdx < 0) ||
2681 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2682 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2683 if (oldStart <= end) {
2684 processRegion(oldStart, end);
2689 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2691 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2692 (void) dispatch(os, actual._dataStart, nextKey);
2693 end = nextKey._tokenstart;
2696 processRegion(oldStart, nextKey._tokenstart);
2697 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2699 oldStart = nextKey._dataEnd+1;
2701 // now nextKey is either invalid or is outside of actual._dataEnd
2702 // output the remaining and discard myself
2703 if (oldStart <= end) {
2704 processRegion(oldStart, end);
2706 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2708 // This is the normal case.
2709 // But if using the firstlanguage, the closing may be missing
2711 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2713 if (actual._dataEnd < end)
2714 output_end = interval_.nextNotIgnored(actual._dataEnd);
2715 else if (interval_.par.size() > (size_t) end)
2716 output_end = interval_.nextNotIgnored(end);
2718 output_end = interval_.par.size();
2719 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2720 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2722 // Remove possible empty data
2723 int dstart = interval_.nextNotIgnored(actual._dataStart);
2724 while (interval_.isOpeningPar(dstart) == 1) {
2725 interval_.addIntervall(dstart, dstart+1);
2726 int dend = interval_.findclosing(dstart+1, output_end);
2727 interval_.addIntervall(dend, dend+1);
2728 dstart = interval_.nextNotIgnored(dstart+1);
2730 if (dstart < output_end)
2731 interval_.output(os, output_end);
2733 interval_.addIntervall(0, end);
2735 interval_.addIntervall(actual._tokenstart, end);
2739 string splitOnKnownMacros(string par, bool isPatternString)
2742 LatexInfo li(par, isPatternString);
2743 // LYXERR(Debug::INFO, "Berfore split: " << par);
2744 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2746 DummyKey._tokensize = 0;
2747 DummyKey._dataStart = 0;
2748 DummyKey._dataEnd = par.length();
2749 DummyKey.disabled = true;
2750 int firstkeyIdx = li.getFirstKey();
2752 if (firstkeyIdx >= 0) {
2753 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2754 DummyKey._tokenstart = firstKey._tokenstart;
2756 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2757 // Use dummy firstKey
2758 firstKey = DummyKey;
2759 (void) li.setNextKey(firstkeyIdx);
2762 if (par.substr(firstKey._dataStart, 2) == "% ")
2763 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2765 nextkeyIdx = li.process(os, firstKey);
2766 while (nextkeyIdx >= 0) {
2767 // Check for a possible gap between the last
2768 // entry and this one
2769 int datastart = li.nextNotIgnored(firstKey._dataStart);
2770 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2771 if ((nextKey._tokenstart > datastart)) {
2773 firstKey._dataStart = datastart;
2774 firstKey._dataEnd = par.length();
2775 (void) li.setNextKey(nextkeyIdx);
2776 // Fake the last opened parenthesis
2777 li.setForDefaultLang(firstKey);
2778 nextkeyIdx = li.process(os, firstKey);
2781 if (nextKey.keytype != KeyInfo::isMain) {
2782 firstKey._dataStart = datastart;
2783 firstKey._dataEnd = nextKey._dataEnd+1;
2784 (void) li.setNextKey(nextkeyIdx);
2785 li.setForDefaultLang(firstKey);
2786 nextkeyIdx = li.process(os, firstKey);
2789 nextkeyIdx = li.process(os, nextKey);
2793 // Handle the remaining
2794 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2795 firstKey._dataEnd = par.length();
2797 if ((firstKey._dataStart < firstKey._dataEnd) &&
2798 (par[firstKey._dataStart] != '}')) {
2799 li.setForDefaultLang(firstKey);
2800 (void) li.process(os, firstKey);
2804 // return string definitelly impossible to match
2805 s = "\\foreignlanguage{ignore}{ }";
2809 s = par; /* no known macros found */
2810 // LYXERR(Debug::INFO, "After split: " << s);
2815 * Try to unify the language specs in the latexified text.
2816 * Resulting modified string is set to "", if
2817 * the searched tex does not contain all the features in the search pattern
2819 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2821 static Features regex_f;
2822 static int missed = 0;
2823 static bool regex_with_format = false;
2825 int parlen = par.length();
2827 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2830 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2831 // Happens to be there in case of description or labeling environment
2836 // Split the latex input into pieces which
2837 // can be digested by our search engine
2838 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2839 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2840 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2841 string doclang = pbuf->params().language->polyglossia();
2842 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2844 bool toIgnoreLang = true;
2845 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2847 if (sub.str(2) != doclang) {
2848 toIgnoreLang = false;
2852 setIgnoreFormat("language", toIgnoreLang);
2855 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2856 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2859 result = par.substr(0, parlen);
2860 if (isPatternString) {
2863 regex_f = identifyFeatures(result);
2864 string features = "";
2865 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2866 string a = it->first;
2867 regex_with_format = true;
2868 features += " " + a;
2869 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2871 LYXERR(Debug::FIND, "Identified Features" << features);
2874 } else if (regex_with_format) {
2875 Features info = identifyFeatures(result);
2876 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2877 string a = it->first;
2878 bool b = it->second;
2879 if (b && ! info[a]) {
2881 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2888 // LYXERR(Debug::INFO, "No regex formats");
2894 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2895 static int identifyClosing(string & t)
2897 int open_braces = 0;
2899 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2900 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2902 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2904 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2906 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2915 static int num_replaced = 0;
2916 static bool previous_single_replace = true;
2918 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
2921 // Handle \w properly
2922 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
2923 if (! opt.casesensitive) {
2924 popts |= QRegularExpression::CaseInsensitiveOption;
2926 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
2927 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
2929 if (regexp.isValid() && regexp2.isValid()) {
2930 regexIsValid = true;
2931 // Check '{', '}' pairs inside the regex
2934 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
2935 char c = par_as_string[i];
2942 else if (c == '}') {
2949 if (balanced != 0) {
2950 regexIsValid = false;
2951 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
2955 regexIsValid = false;
2956 if (!regexp.isValid())
2957 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
2959 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
2962 if (opt.casesensitive) {
2963 regexp = regex(regexp_str);
2964 regexp2 = regex(regexp2_str);
2967 regexp = regex(regexp_str, std::regex_constants::icase);
2968 regexp2 = regex(regexp2_str, std::regex_constants::icase);
2973 static void modifyRegexForMatchWord(string &t)
2976 regex wordre("(\\\\)*((\\.|\\\\b))");
2979 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
2981 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
2984 else if (sub.str(2) == "\\\\b")
2986 if (lastpos < (size_t) sub.position(2))
2987 s += t.substr(lastpos, sub.position(2) - lastpos);
2989 lastpos = sub.position(2) + sub.length(2);
2992 s = "\\b" + t + "\\b";
2996 else if (lastpos < t.length())
2997 s += t.substr(lastpos, t.length() - lastpos);
2998 t = "\\b" + s + "\\b";
3001 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3002 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3004 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3005 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3006 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3007 if (opt.replace_all && previous_single_replace) {
3008 previous_single_replace = false;
3011 else if (!opt.replace_all) {
3012 num_replaced = 0; // count number of replaced strings
3013 previous_single_replace = true;
3015 // When using regexp, braces are hacked already by escape_for_regex()
3016 par_as_string = normalize(ds);
3018 close_wildcards = 0;
3020 size_t lead_size = 0;
3021 // correct the language settings
3022 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3023 opt.matchAtStart = false;
3025 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3026 if (opt.ignoreformat) {
3030 lead_size = identifyLeading(par_as_string);
3032 lead_as_string = par_as_string.substr(0, lead_size);
3033 string lead_as_regex_string = string2regex(lead_as_string);
3034 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3035 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3036 /* Handle whole words too in this case
3038 if (opt.matchword) {
3039 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3040 opt.matchword = false;
3042 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3043 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3044 CreateRegexp(opt, regexp_str, regexp2_str);
3046 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3047 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3051 if (!opt.ignoreformat) {
3052 lead_size = identifyLeading(par_as_string);
3053 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3054 lead_as_string = par_as_string.substr(0, lead_size);
3055 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3058 // Here we are using regexp
3059 LASSERT(use_regexp, /**/);
3061 string lead_as_regexp;
3062 if (lead_size > 0) {
3063 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3064 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3065 par_as_string = par_as_string_nolead;
3066 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3067 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3069 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3070 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3071 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3072 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3074 size_t lng = par_as_string.size();
3075 if (!opt.ignoreformat) {
3076 // Remove extra '\}' at end if not part of \{\.\}
3078 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3080 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3089 if (lng < par_as_string.size())
3090 par_as_string = par_as_string.substr(0,lng);
3092 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3093 if ((lng > 0) && (par_as_string[0] == '^')) {
3094 par_as_string = par_as_string.substr(1);
3096 opt.matchAtStart = true;
3098 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3099 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3100 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3102 // If entered regexp must match at begin of searched string buffer
3103 // Kornel: Added parentheses to use $1 for size of the leading string
3107 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3108 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3109 // so the convert has no effect in that case
3110 for (int i = 7; i > 0; --i) {
3111 string orig = "\\\\" + std::to_string(i);
3112 string dest = "\\" + std::to_string(i+2);
3113 while (regex_replace(par_as_string, par_as_string, orig, dest));
3115 if (opt.matchword) {
3116 modifyRegexForMatchWord(par_as_string);
3117 opt.matchword = false;
3119 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3120 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3122 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3123 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3124 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3128 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3132 mres.searched_size = len;
3134 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3137 docstring docstr = stringifyFromForSearch(opt, cur, len);
3139 str = normalize(docstr);
3140 if (!opt.ignoreformat) {
3141 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3142 // remove closing '}' and '\n' to allow for use of '$' in regex
3143 size_t lng = str.size();
3144 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3146 if (lng != str.size()) {
3147 str = str.substr(0, lng);
3151 mres.match_len = -1;
3154 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3156 LASSERT(use_regexp, /**/);
3158 // use_regexp always true
3159 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3161 QString qstr = QString::fromStdString(str);
3162 QRegularExpression const *p_regexp;
3163 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3167 p_regexp = ®exp2;
3169 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3170 if (!match.hasMatch())
3173 regex const *p_regexp;
3174 regex_constants::match_flag_type flags;
3176 flags = regex_constants::match_continuous;
3179 flags = regex_constants::match_default;
3180 p_regexp = ®exp2;
3182 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3183 if (re_it == sregex_iterator())
3185 match_results<string::const_iterator> const & m = *re_it;
3187 // Whole found string, including the leading
3188 // std: m[0].second - m[0].first
3189 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3191 // Size of the leading string
3192 // std: m[1].second - m[1].first
3193 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3194 int leadingsize = 0;
3196 if (match.lastCapturedIndex() > 0) {
3197 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3202 leadingsize = m[1].second - m[1].first;
3206 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3207 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3208 // because of different number of closing at end of string
3209 // we have to 'unify' the length of the post-match.
3210 // Done by ignoring closing parenthesis and linefeeds at string end
3211 int matchend = match.capturedEnd(0);
3212 size_t strsize = qstr.size();
3213 if (!opt.ignoreformat) {
3214 while (mres.match_len > 0) {
3215 QChar c = qstr.at(matchend - 1);
3216 if ((c == '\n') || (c == '}') || (c == '{')) {
3223 while (strsize > (size_t) match.capturedEnd(0)) {
3224 QChar c = qstr.at(strsize-1);
3225 if ((c == '\n') || (c == '}')) {
3232 // LYXERR0(qstr.toStdString());
3233 mres.match2end = strsize - matchend;
3234 mres.pos = match.capturedStart(2);
3236 mres.match_prefix = m[2].second - m[2].first;
3237 mres.match_len = m[0].second - m[2].second;
3238 // ignore closing parenthesis and linefeeds at string end
3239 size_t strend = m[0].second - m[0].first;
3240 int matchend = strend;
3241 size_t strsize = str.size();
3242 if (!opt.ignoreformat) {
3243 while (mres.match_len > 0) {
3244 char c = str.at(matchend - 1);
3245 if ((c == '\n') || (c == '}') || (c == '{')) {
3252 while (strsize > strend) {
3253 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3261 mres.match2end = strsize - matchend;
3262 mres.pos = m[2].first - m[0].first;;
3264 if (mres.match2end < 0)
3266 mres.leadsize = leadingsize;
3268 if (mres.match_len > 0) {
3269 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3270 mres.result.push_back(a0);
3271 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3272 mres.result.push_back(match.captured(i).toStdString());
3276 if (mres.match_len > 0) {
3277 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3278 mres.result.push_back(a0);
3279 for (size_t i = 3; i < m.size(); i++) {
3280 mres.result.push_back(m[i]);
3289 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3291 MatchResult mres = findAux(cur, len, at_begin);
3292 int res = mres.match_len;
3294 "res=" << res << ", at_begin=" << at_begin
3295 << ", matchAtStart=" << opt.matchAtStart
3296 << ", inTexted=" << cur.inTexted());
3297 if (opt.matchAtStart) {
3300 else if (mres.match_prefix > 0)
3309 static bool simple_replace(string &t, string from, string to)
3311 regex repl("(\\\\)*(" + from + ")");
3315 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3317 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3319 if (lastpos < (size_t) sub.position(2))
3320 s += t.substr(lastpos, sub.position(2) - lastpos);
3322 lastpos = sub.position(2) + sub.length(2);
3326 else if (lastpos < t.length())
3327 s += t.substr(lastpos, t.length() - lastpos);
3333 string MatchStringAdv::normalize(docstring const & s) const
3336 t = lyx::to_utf8(s);
3337 // Remove \n at begin
3338 while (!t.empty() && t[0] == '\n')
3341 while (!t.empty() && t[t.size() - 1] == '\n')
3342 t = t.substr(0, t.size() - 1);
3344 // Handle all other '\n'
3345 while ((pos = t.find("\n")) != string::npos) {
3346 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3348 if (isAlnumASCII(t[pos+1])) {
3349 t.replace(pos-2, 3, " ");
3352 t.replace(pos-2, 3, "");
3355 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3356 // '\n' adjacent to non-alpha-numerics, discard
3357 t.replace(pos, 1, "");
3360 // Replace all other \n with spaces
3361 t.replace(pos, 1, " ");
3364 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3365 // Kornel: Added textsl, textsf, textit, texttt and noun
3366 // + allow to seach for colored text too
3367 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3368 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3369 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3370 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3371 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3372 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3378 docstring stringifyFromCursor(DocIterator const & cur, int len)
3380 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3381 if (cur.inTexted()) {
3382 Paragraph const & par = cur.paragraph();
3383 // TODO what about searching beyond/across paragraph breaks ?
3384 // TODO Try adding a AS_STR_INSERTS as last arg
3385 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3386 int(par.size()) : cur.pos() + len;
3387 // OutputParams runparams(&cur.buffer()->params().encoding());
3388 OutputParams runparams(encodings.fromLyXName("utf8"));
3389 runparams.nice = true;
3390 runparams.flavor = Flavor::XeTeX;
3391 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3392 // No side effect of file copying and image conversion
3393 runparams.dryrun = true;
3394 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3395 if (ignoreFormats.getDeleted()) {
3396 option |= AS_STR_SKIPDELETE;
3397 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3400 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3402 LYXERR(Debug::FIND, "Stringifying with cur: "
3403 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3404 return par.asString(cur.pos(), end,
3407 } else if (cur.inMathed()) {
3408 CursorSlice cs = cur.top();
3409 MathData md = cs.cell();
3410 MathData::const_iterator it_end =
3411 (( len == -1 || cs.pos() + len > int(md.size()))
3413 : md.begin() + cs.pos() + len );
3415 for (MathData::const_iterator it = md.begin() + cs.pos();
3418 docstring s = asString(md2);
3419 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3422 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3427 /** Computes the LaTeX export of buf starting from cur and ending len positions
3428 * after cur, if len is positive, or at the paragraph or innermost inset end
3431 docstring latexifyFromCursor(DocIterator const & cur, int len)
3434 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3435 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3436 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3438 Buffer const & buf = *cur.buffer();
3440 odocstringstream ods;
3442 //OutputParams runparams(&buf.params().encoding());
3443 OutputParams runparams(encodings.fromLyXName("utf8"));
3444 runparams.nice = false;
3445 runparams.flavor = Flavor::XeTeX;
3446 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3447 // No side effect of file copying and image conversion
3448 runparams.dryrun = true;
3449 if (ignoreFormats.getDeleted()) {
3450 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3453 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3456 if (cur.inTexted()) {
3457 // @TODO what about searching beyond/across paragraph breaks ?
3458 pos_type endpos = cur.paragraph().size();
3459 if (len != -1 && endpos > cur.pos() + len)
3460 endpos = cur.pos() + len;
3461 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3462 string(), cur.pos(), endpos);
3463 string s = lyx::to_utf8(ods.str());
3464 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3465 return(lyx::from_utf8(s));
3466 } else if (cur.inMathed()) {
3467 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3468 for (int s = cur.depth() - 1; s >= 0; --s) {
3469 CursorSlice const & cs = cur[s];
3470 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3471 TeXMathStream ws(os);
3472 cs.asInsetMath()->asHullInset()->header_write(ws);
3477 CursorSlice const & cs = cur.top();
3478 MathData md = cs.cell();
3479 MathData::const_iterator it_end =
3480 ((len == -1 || cs.pos() + len > int(md.size()))
3482 : md.begin() + cs.pos() + len);
3484 for (MathData::const_iterator it = md.begin() + cs.pos();
3488 ods << asString(md2);
3489 // Retrieve the math environment type, and add '$' or '$]'
3490 // or others (\end{equation}) accordingly
3491 for (int s = cur.depth() - 1; s >= 0; --s) {
3492 CursorSlice const & cs2 = cur[s];
3493 InsetMath * inset = cs2.asInsetMath();
3494 if (inset && inset->asHullInset()) {
3495 TeXMathStream ws(os);
3496 inset->asHullInset()->footer_write(ws);
3500 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3502 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3507 #if defined(ResultsDebug)
3509 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3511 LYXERR0( "from:\t\t\t" << from);
3513 if (mres.pos_len > 0) {
3515 status = "FINALSEARCH";
3518 if (mres.match_len > 0) {
3519 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3520 status = "Good Match";
3522 status = "Matched in";
3525 status = "MissedSearch";
3528 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3529 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3530 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3531 if ((mres.pos > 0) || (mres.match_prefix > 0))
3532 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3533 for (size_t i = 0; i < mres.result.size(); i++)
3534 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3536 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3538 #define displayMres(s, txt, cur)
3541 /** Finalize an advanced find operation, advancing the cursor to the innermost
3542 ** position that matches, plus computing the length of the matching text to
3544 ** Return the cur.pos() difference between start and end of found match
3546 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3548 // Search the foremost position that matches (avoids find of entire math
3549 // inset when match at start of it)
3550 DocIterator old_cur(cur.buffer());
3552 static MatchResult fail = MatchResult();
3553 MatchResult max_match;
3554 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3555 // Happens with e.g. hyperlinks
3556 // either one sees "http://www.bla.bla" or nothing
3557 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3558 // and although we search for only 3 chars, we find the whole hyperlink inset
3559 bool at_begin = (expected.match_prefix == 0);
3560 if (!match.opt.forward && match.opt.ignoreformat) {
3561 if (expected.pos > 0)
3564 LASSERT(at_begin, /**/);
3565 if (expected.match_len > 0 && at_begin) {
3566 // Search for deepest match
3568 max_match = expected;
3570 size_t d = cur.depth();
3574 if (cur.depth() < d)
3576 if (cur.depth() == d)
3579 while (cur && cur.depth() > lastd) {
3580 lastd = cur.depth();
3581 mres = match(cur, -1, at_begin);
3582 displayMres(mres, "Checking innermost", cur);
3583 if (mres.match_len > 0)
3588 if (mres.match_len < expected.match_len)
3596 // (expected.match_len <= 0)
3597 mres = match(cur); /* match valid only if not searching whole words */
3598 displayMres(mres, "Start with negative match", cur);
3601 if (max_match.match_len <= 0) return fail;
3602 LYXERR(Debug::FIND, "Ok");
3604 // Compute the match length
3606 if (cur.pos() + len > cur.lastpos())
3609 LASSERT(match.use_regexp, /**/);
3612 int maxl = cur.lastpos() - cur.pos();
3613 // Greedy behaviour while matching regexps
3614 while (maxl > minl) {
3616 mres2 = match(cur, len, at_begin);
3617 displayMres(mres2, "Finalize loop", cur);
3618 int actual_match_len = mres2.match_len;
3619 if (actual_match_len >= max_match.match_len) {
3620 // actual_match_len > max_match _can_ happen,
3621 // if the search area splits
3622 // some following word so that the regex
3623 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3625 // This means, the len value is too big
3626 actual_match_len = max_match.match_len;
3628 max_match.match_len = actual_match_len;
3630 if (maxl - minl < 4)
3631 len = (int)((maxl + minl)/2);
3633 len = (int)(minl + (maxl - minl + 3)/4);
3636 // (actual_match_len < max_match.match_len)
3638 len = (int)((maxl + minl)/2);
3643 // Search for real start of matched characters
3645 MatchResult actual_match;
3648 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3649 if (cur.depth() < old_cur.depth()) {
3651 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3654 if (cur.pos() != old_cur.pos()) {
3655 // OK, forwarded 1 pos in actual inset
3656 actual_match = match(cur, len-1, at_begin);
3657 if (actual_match.match_len == max_match.match_len) {
3658 // Ha, got it! The shorter selection has the same match length
3661 max_match = actual_match;
3664 // OK, the shorter selection matches less chars, revert to previous value
3670 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3671 actual_match = match(cur, len, at_begin);
3672 if (actual_match.match_len == max_match.match_len) {
3674 max_match = actual_match;
3681 max_match.pos_len = len;
3682 displayMres(max_match, "SEARCH RESULT", cur)
3689 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3693 bool repeat = false;
3694 DocIterator orig_cur; // to be used if repeat not successful
3695 MatchResult orig_mres;
3696 while (!theApp()->longOperationCancelled() && cur) {
3697 //(void) findAdvForwardInnermost(cur);
3698 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3699 MatchResult mres = match(cur, -1, false);
3700 string msg = "Starting";
3703 displayMres(mres, msg + " findForwardAdv", cur)
3704 int match_len = mres.match_len;
3705 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3706 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3709 if (match_len <= 0) {
3710 // This should exit nested insets, if any, or otherwise undefine the currsor.
3711 cur.pos() = cur.lastpos();
3712 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3715 else { // match_len > 0
3716 // Try to find the begin of searched string
3718 int firstInvalid = cur.lastpos() - cur.pos();
3720 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3721 int incrcur = (firstInvalid + 1 )*3/4;
3722 if (incrcur < incrmatch)
3723 increment = incrcur;
3725 increment = incrmatch;
3729 LYXERR(Debug::FIND, "Set increment to " << increment);
3730 while (increment > 0) {
3731 DocIterator old_cur = cur;
3732 if (cur.pos() + increment >= cur.lastpos()) {
3736 cur.pos() = cur.pos() + increment;
3737 MatchResult mres2 = match(cur, -1, false);
3738 displayMres(mres2, "findForwardAdv loop", cur)
3739 switch (interpretMatch(mres, mres2)) {
3740 case MatchResult::newIsTooFar:
3741 // behind the expected match
3742 firstInvalid = increment;
3746 case MatchResult::newIsBetter:
3747 // not reached yet, but cur.pos()+increment is bettert
3749 firstInvalid -= increment;
3750 if (increment > firstInvalid*3/4)
3751 increment = firstInvalid*3/4;
3752 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3753 if (increment >= mres2.match_prefix)
3754 increment = (mres2.match_prefix+1)*3/4;
3759 // Handle not like MatchResult::newIsTooFar
3760 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3762 increment = increment*3/4;
3767 if (mres.match_len > 0) {
3768 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3769 // The match seems to indicate some deeper level
3778 // should never be reached.
3782 // LYXERR0("Leaving first loop");
3783 LYXERR(Debug::FIND, "Finalizing 1");
3784 MatchResult found_match = findAdvFinalize(cur, match, mres);
3785 if (found_match.match_len > 0) {
3786 LASSERT(found_match.pos_len > 0, /**/);
3787 match.FillResults(found_match);
3788 return found_match.pos_len;
3791 // try next possible match
3802 /// Find the most backward consecutive match within same paragraph while searching backwards.
3803 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3805 DocIterator cur_begin = cur;
3806 cur_begin.pos() = 0;
3807 DocIterator tmp_cur = cur;
3808 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3809 Inset & inset = cur.inset();
3810 for (; cur != cur_begin; cur.backwardPos()) {
3811 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3812 DocIterator new_cur = cur;
3813 new_cur.backwardPos();
3814 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3816 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3817 if (new_mr.match_len == mr.match_len)
3821 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3827 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3831 // Backup of original position
3832 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3833 if (cur == cur_begin)
3836 DocIterator cur_orig(cur);
3837 bool pit_changed = false;
3840 MatchResult found_match = match(cur, -1, false);
3842 if (found_match.match_len > 0) {
3844 cur.pos() = cur.lastpos();
3846 cur.pos() = cur_orig.pos();
3847 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3848 DocIterator cur_prev_iter;
3850 found_match = match(cur);
3851 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3852 << (found_match.match_len > 0) << ", cur: " << cur);
3853 if (found_match.match_len > 0) {
3854 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3855 if (found_mr.pos_len > 0) {
3856 match.FillResults(found_mr);
3857 return found_mr.pos_len;
3861 // Stop if begin of document reached
3862 if (cur == cur_begin)
3864 cur_prev_iter = cur;
3868 if (cur == cur_begin)
3875 } while (!theApp()->longOperationCancelled());
3883 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3884 DocIterator const & cur, int len)
3886 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3888 if (!opt.ignoreformat)
3889 return latexifyFromCursor(cur, len);
3891 return stringifyFromCursor(cur, len);
3895 FindAndReplaceOptions::FindAndReplaceOptions(
3896 docstring const & _find_buf_name, bool _casesensitive,
3897 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3898 docstring const & _repl_buf_name, bool _keep_case,
3899 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3900 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3901 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3902 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3910 /** Check if 'len' letters following cursor are all non-lowercase */
3911 static bool allNonLowercase(Cursor const & cur, int len)
3913 pos_type beg_pos = cur.selectionBegin().pos();
3914 pos_type end_pos = cur.selectionBegin().pos() + len;
3915 if (len > cur.lastpos() + 1 - beg_pos) {
3916 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3917 len = cur.lastpos() + 1 - beg_pos;
3918 end_pos = beg_pos + len;
3920 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3921 if (isLowerCase(cur.paragraph().getChar(pos)))
3927 /** Check if first letter is upper case and second one is lower case */
3928 static bool firstUppercase(Cursor const & cur)
3931 pos_type pos = cur.selectionBegin().pos();
3932 if (pos >= cur.lastpos() - 1) {
3933 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3936 ch1 = cur.paragraph().getChar(pos);
3937 ch2 = cur.paragraph().getChar(pos + 1);
3938 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3939 LYXERR(Debug::FIND, "firstUppercase(): "
3940 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3941 << ch2 << "(" << char(ch2) << ")"
3942 << ", result=" << result << ", cur=" << cur);
3947 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3949 ** \fixme What to do with possible further paragraphs in replace buffer ?
3951 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3953 ParagraphList::iterator pit = buffer.paragraphs().begin();
3954 LASSERT(!pit->empty(), /**/);
3955 pos_type right = pos_type(1);
3956 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3957 right = pit->size();
3958 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3962 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
3964 // Should replace the string "$" + std::to_string(matchnum) with replacement
3965 // if the char '$' is not prefixed with odd number of char '\\'
3966 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
3970 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
3972 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3974 int num = stoi(sub.str(3), nullptr, 10);
3975 if (num >= maxmatchnum)
3977 if (lastpos < (size_t) sub.position(2))
3978 s += t.substr(lastpos, sub.position(2) - lastpos);
3979 s += replacements[num];
3980 lastpos = sub.position(2) + sub.length(2);
3984 else if (lastpos < t.length())
3985 s += t.substr(lastpos, t.length() - lastpos);
3991 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3993 Cursor & cur = bv->cursor();
3994 if (opt.repl_buf_name.empty()
3995 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3996 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3999 DocIterator sel_beg = cur.selectionBegin();
4000 DocIterator sel_end = cur.selectionEnd();
4001 if (&sel_beg.inset() != &sel_end.inset()
4002 || sel_beg.pit() != sel_end.pit()
4003 || sel_beg.idx() != sel_end.idx())
4005 int sel_len = sel_end.pos() - sel_beg.pos();
4006 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4007 << ", sel_len: " << sel_len << endl);
4010 LASSERT(sel_len > 0, return 0);
4012 if (!matchAdv(sel_beg, sel_len).match_len)
4015 // Build a copy of the replace buffer, adapted to the KeepCase option
4016 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4018 repl_buffer_orig.write(oss);
4019 string lyx = oss.str();
4020 if (matchAdv.valid_matches > 0) {
4021 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4023 Buffer repl_buffer("", false);
4024 repl_buffer.setUnnamed(true);
4025 LASSERT(repl_buffer.readString(lyx), return 0);
4026 if (opt.keep_case && sel_len >= 2) {
4027 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4028 if (cur.inTexted()) {
4029 if (firstUppercase(cur))
4030 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4031 else if (allNonLowercase(cur, sel_len))
4032 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4035 cap::cutSelection(cur, false);
4036 if (cur.inTexted()) {
4037 repl_buffer.changeLanguage(
4038 repl_buffer.language(),
4039 cur.getFont().language());
4040 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4041 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4042 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4043 repl_buffer.params().documentClassPtr(),
4044 repl_buffer.params().authors(),
4045 bv->buffer().errorList("Paste"));
4046 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4047 sel_len = repl_buffer.paragraphs().begin()->size();
4048 } else if (cur.inMathed()) {
4049 odocstringstream ods;
4051 // OutputParams runparams(&repl_buffer.params().encoding());
4052 OutputParams runparams(encodings.fromLyXName("utf8"));
4053 runparams.nice = false;
4054 runparams.flavor = Flavor::XeTeX;
4055 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4056 runparams.dryrun = true;
4057 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4058 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4059 docstring repl_latex = ods.str();
4060 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4062 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4063 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4064 repl_latex = from_utf8(s);
4065 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4066 MathData ar(cur.buffer());
4067 asArray(repl_latex, ar, Parse::NORMAL);
4069 sel_len = ar.size();
4070 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4072 if (cur.pos() >= sel_len)
4073 cur.pos() -= sel_len;
4076 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4077 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4078 bv->processUpdateFlags(Update::Force);
4083 /// Perform a FindAdv operation.
4084 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4089 // e.g., when invoking word-findadv from mini-buffer wither with
4090 // wrong options syntax or before ever opening advanced F&R pane
4091 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4095 MatchStringAdv matchAdv(bv->buffer(), opt);
4097 if (!matchAdv.regexIsValid) {
4098 bv->message(lyx::from_utf8(matchAdv.regexError));
4102 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4104 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4105 num_replaced += findAdvReplace(bv, opt, matchAdv);
4108 pos_len = findForwardAdv(cur, matchAdv);
4110 pos_len = findBackwardsAdv(cur, matchAdv);
4111 } catch (exception & ex) {
4112 bv->message(from_utf8(ex.what()));
4117 if (num_replaced > 0) {
4118 switch (num_replaced)
4121 bv->message(_("One match has been replaced."));
4124 bv->message(_("Two matches have been replaced."));
4127 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4133 bv->message(_("Match not found."));
4138 if (num_replaced > 0)
4139 bv->message(_("Match has been replaced."));
4141 bv->message(_("Match found."));
4143 if (cur.pos() + pos_len > cur.lastpos()) {
4144 // Prevent crash in bv->putSelectionAt()
4145 // Should never happen, maybe LASSERT() here?
4146 pos_len = cur.lastpos() - cur.pos();
4148 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4149 bv->putSelectionAt(cur, pos_len, !opt.forward);
4155 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4157 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4158 << opt.casesensitive << ' '
4159 << opt.matchword << ' '
4160 << opt.forward << ' '
4161 << opt.expandmacros << ' '
4162 << opt.ignoreformat << ' '
4163 << opt.replace_all << ' '
4164 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4165 << opt.keep_case << ' '
4166 << int(opt.scope) << ' '
4169 LYXERR(Debug::FIND, "built: " << os.str());
4175 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4177 // LYXERR(Debug::FIND, "parsing");
4181 while (line != "EOSS") {
4185 if (is.eof()) // Tolerate malformed request
4189 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4190 opt.find_buf_name = from_utf8(s);
4191 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4192 is.get(); // Waste space before replace string
4195 while (line != "EOSS") {
4199 if (is.eof()) // Tolerate malformed request
4203 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4204 opt.repl_buf_name = from_utf8(s);
4205 is >> opt.keep_case;
4208 opt.scope = FindAndReplaceOptions::SearchScope(i);
4210 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4213 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4214 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4215 << opt.scope << ' ' << opt.restr);