3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathData.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
45 #include "support/debug.h"
46 #include "support/docstream.h"
47 #include "support/FileName.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
53 #include <unordered_map>
56 //#define ResultsDebug
57 #define USE_QT_FOR_SEARCH
58 #if defined(USE_QT_FOR_SEARCH)
59 #include <QtCore> // sets QT_VERSION
60 #if (QT_VERSION >= 0x050000)
61 #include <QRegularExpression>
71 using namespace lyx::support;
75 typedef unordered_map<string, string> AccentsMap;
76 typedef unordered_map<string,string>::const_iterator AccentsIterator;
77 static AccentsMap accents = unordered_map<string, string>();
79 // Helper class for deciding what should be ignored
83 IgnoreFormats() = default;
85 bool getFamily() const { return ignoreFamily_; }
87 bool getSeries() const { return ignoreSeries_; }
89 bool getShape() const { return ignoreShape_; }
91 bool getUnderline() const { return ignoreUnderline_; }
93 bool getMarkUp() const { return ignoreMarkUp_; }
95 bool getStrikeOut() const { return ignoreStrikeOut_; }
97 bool getSectioning() const { return ignoreSectioning_; }
99 bool getFrontMatter() const { return ignoreFrontMatter_; }
101 bool getColor() const { return ignoreColor_; }
103 bool getLanguage() const { return ignoreLanguage_; }
105 bool getDeleted() const { return ignoreDeleted_; }
107 void setIgnoreDeleted(bool value);
109 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreUnderline_ = false;
121 bool ignoreMarkUp_ = false;
123 bool ignoreStrikeOut_ = false;
125 bool ignoreSectioning_ = false;
127 bool ignoreFrontMatter_ = false;
129 bool ignoreColor_ = false;
131 bool ignoreLanguage_ = false;
132 bool userSelectedIgnoreLanguage_ = false;
134 bool ignoreDeleted_ = true;
137 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
139 if (type == "color") {
140 ignoreColor_ = value;
142 else if (type == "language") {
144 userSelectedIgnoreLanguage_ = value;
145 ignoreLanguage_ = value;
148 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
150 else if (type == "sectioning") {
151 ignoreSectioning_ = value;
152 ignoreFrontMatter_ = value;
154 else if (type == "font") {
155 ignoreSeries_ = value;
156 ignoreShape_ = value;
157 ignoreFamily_ = value;
159 else if (type == "series") {
160 ignoreSeries_ = value;
162 else if (type == "shape") {
163 ignoreShape_ = value;
165 else if (type == "family") {
166 ignoreFamily_ = value;
168 else if (type == "markup") {
169 ignoreMarkUp_ = value;
171 else if (type == "underline") {
172 ignoreUnderline_ = value;
174 else if (type == "strike") {
175 ignoreStrikeOut_ = value;
177 else if (type == "deleted") {
178 ignoreDeleted_ = value;
182 // The global variable that can be changed from outside
183 IgnoreFormats ignoreFormats;
186 void setIgnoreFormat(string const & type, bool value, bool fromUser)
188 ignoreFormats.setIgnoreFormat(type, value, fromUser);
194 bool parse_bool(docstring & howto, bool const defvalue = false)
199 howto = split(howto, var, ' ');
207 MatchString(docstring const & s, bool cs, bool mw)
208 : str(s), case_sens(cs), whole_words(mw)
211 // returns true if the specified string is at the specified position
212 // del specifies whether deleted strings in ct mode will be considered
213 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
215 return par.find(str, case_sens, whole_words, pos, del);
223 // match whole words only
228 int findForward(DocIterator & cur, DocIterator const endcur,
229 MatchString const & match,
230 bool find_del = true, bool onlysel = false)
232 for (; cur; cur.forwardChar()) {
233 if (onlysel && endcur.pit() == cur.pit()
234 && endcur.idx() == cur.idx() && endcur.pos() < cur.pos())
236 if (cur.inTexted()) {
237 int len = match(cur.paragraph(), cur.pos(), find_del);
246 int findBackwards(DocIterator & cur, DocIterator const endcur,
247 MatchString const & match,
248 bool find_del = true, bool onlysel = false)
252 if (onlysel && endcur.pit() == cur.pit()
253 && endcur.idx() == cur.idx() && endcur.pos() > cur.pos())
255 if (cur.inTexted()) {
256 int len = match(cur.paragraph(), cur.pos(), find_del);
265 bool searchAllowed(docstring const & str)
268 frontend::Alert::error(_("Search error"), _("Search string is empty"));
277 bool findOne(BufferView * bv, docstring const & searchstr,
278 bool case_sens, bool whole, bool forward,
279 bool find_del, bool check_wrap, bool auto_wrap,
280 bool instant, bool onlysel)
282 if (!searchAllowed(searchstr))
285 DocIterator const endcur = forward ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin();
287 if (onlysel && bv->cursor().selection()) {
288 docstring const matchstring = bv->cursor().selectionAsString(false);
289 docstring const lcmatchsting = support::lowercase(matchstring);
290 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
291 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
292 "Continue search outside?");
293 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
294 q, 0, 1, _("&Yes"), _("&No"));
295 if (search_answer == 0) {
296 bv->clearSelection();
297 if (findOne(bv, searchstr, case_sens, whole, forward,
298 find_del, check_wrap, auto_wrap, false, false))
305 DocIterator cur = forward
306 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
307 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
309 MatchString const match(searchstr, case_sens, whole);
311 int match_len = forward
312 ? findForward(cur, endcur, match, find_del, onlysel)
313 : findBackwards(cur, endcur, match, find_del, onlysel);
316 bv->putSelectionAt(cur, match_len, !forward);
318 docstring q = _("The search string was not found within the selection.\n"
319 "Continue search outside?");
320 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
321 q, 0, 1, _("&Yes"), _("&No"));
322 if (search_answer == 0) {
323 bv->clearSelection();
324 if (findOne(bv, searchstr, case_sens, whole, forward,
325 find_del, check_wrap, auto_wrap, false, false))
330 else if (check_wrap) {
331 DocIterator cur_orig(bv->cursor());
335 q = _("End of file reached while searching forward.\n"
336 "Continue searching from the beginning?");
338 q = _("Beginning of file reached while searching backward.\n"
339 "Continue searching from the end?");
340 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
341 q, 0, 1, _("&Yes"), _("&No"));
342 auto_wrap = wrap_answer == 0;
346 bv->cursor().clear();
347 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
349 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
350 bv->cursor().backwardPos();
352 bv->clearSelection();
353 if (findOne(bv, searchstr, case_sens, whole, forward,
354 find_del, false, false, false, false))
357 bv->cursor().setCursor(cur_orig);
361 return match_len > 0;
367 int replaceAll(BufferView * bv,
368 docstring const & searchstr, docstring const & replacestr,
369 bool case_sens, bool whole, bool onlysel)
371 Buffer & buf = bv->buffer();
373 if (!searchAllowed(searchstr) || buf.isReadonly())
376 DocIterator startcur = bv->cursor().selectionBegin();
377 DocIterator endcur = bv->cursor().selectionEnd();
378 bool const had_selection = bv->cursor().selection();
380 MatchString const match(searchstr, case_sens, whole);
383 int const rsize = replacestr.size();
384 int const ssize = searchstr.size();
387 cur.setCursor(doc_iterator_begin(&buf));
388 int match_len = findForward(cur, endcur, match, false, onlysel);
389 while (match_len > 0) {
390 // Backup current cursor position and font.
391 pos_type const pos = cur.pos();
392 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
394 int ct_deleted_text = ssize -
395 cur.paragraph().eraseChars(pos, pos + match_len,
396 buf.params().track_changes);
397 cur.paragraph().insert(pos, replacestr, font,
398 Change(buf.params().track_changes
400 : Change::UNCHANGED));
401 for (int i = 0; i < rsize + ct_deleted_text
402 && cur.pos() < cur.lastpos(); ++i)
404 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
405 // Adjust end of selection for replace-all in selection
407 int const offset = rsize - ssize;
408 for (int i = 0; i < offset + ct_deleted_text
409 && endcur.pos() < endcur.lastpos(); ++i)
412 int const offset = ssize - rsize;
413 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
414 endcur.backwardPos();
415 for (int i = 0; i < ct_deleted_text
416 && endcur.pos() < endcur.lastpos(); ++i)
421 match_len = findForward(cur, endcur, match, false, onlysel);
424 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
426 startcur.fixIfBroken();
427 bv->setCursor(startcur);
429 // Reset selection, accounting for changes in selection
431 endcur.fixIfBroken();
432 bv->cursor().resetAnchor();
433 bv->setCursorSelectionTo(endcur);
440 // the idea here is that we are going to replace the string that
441 // is selected IF it is the search string.
442 // if there is a selection, but it is not the search string, then
443 // we basically ignore it. (FIXME We ought to replace only within
445 // if there is no selection, then:
446 // (i) if some search string has been provided, then we find it.
447 // (think of how the dialog works when you hit "replace" the
449 // (ii) if no search string has been provided, then we treat the
450 // word the cursor is in as the search string. (why? i have no
451 // idea.) but this only works in text?
453 // returns the number of replacements made (one, if any) and
454 // whether anything at all was done.
455 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
456 docstring const & replacestr, bool case_sens,
457 bool whole, bool forward, bool findnext, bool wrap,
460 Cursor & cur = bv->cursor();
461 if (!cur.selection() || onlysel) {
462 // no selection, non-empty search string: find it
463 if (!searchstr.empty()) {
464 bool const found = findOne(bv, searchstr, case_sens, whole,
465 forward, true, findnext, wrap, false, onlysel);
466 return make_pair(found, 0);
468 // empty search string
471 return make_pair(false, 0);
472 // select current word and treat it as the search string.
473 // This causes a minor bug as undo will restore this selection,
474 // which the user did not create (#8986).
475 cur.innerText()->selectWord(cur, WHOLE_WORD);
476 searchstr = cur.selectionAsString(false, true);
479 // if we still don't have a search string, report the error
481 if (!searchAllowed(searchstr))
482 return make_pair(false, 0);
484 bool have_selection = cur.selection();
485 docstring const selected = cur.selectionAsString(false, true);
488 ? searchstr == selected
489 : compare_no_case(searchstr, selected) == 0;
491 // no selection or current selection is not search word:
492 // just find the search word
493 if (!have_selection || !match) {
494 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
495 true, findnext, wrap, false, onlysel);
496 return make_pair(found, 0);
499 // we're now actually ready to replace. if the buffer is
500 // read-only, we can't, though.
501 if (bv->buffer().isReadonly())
502 return make_pair(false, 0);
504 cap::replaceSelectionWithString(cur, replacestr);
506 cur.pos() += replacestr.length();
507 LASSERT(cur.pos() <= cur.lastpos(),
508 cur.pos() = cur.lastpos());
511 findOne(bv, searchstr, case_sens, whole,
512 forward, false, findnext, wrap, false, onlysel);
514 return make_pair(true, 1);
520 docstring const find2string(docstring const & search,
521 bool casesensitive, bool matchword,
522 bool forward, bool wrap, bool instant,
527 << int(casesensitive) << ' '
528 << int(matchword) << ' '
529 << int(forward) << ' '
531 << int(instant) << ' '
537 docstring const replace2string(docstring const & replace,
538 docstring const & search,
539 bool casesensitive, bool matchword,
540 bool all, bool forward, bool findnext,
541 bool wrap, bool onlysel)
544 ss << replace << '\n'
546 << int(casesensitive) << ' '
547 << int(matchword) << ' '
549 << int(forward) << ' '
550 << int(findnext) << ' '
557 docstring const string2find(docstring const & argument,
565 // data is of the form
567 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
569 docstring howto = split(argument, search, '\n');
571 casesensitive = parse_bool(howto);
572 matchword = parse_bool(howto);
573 forward = parse_bool(howto, true);
574 wrap = parse_bool(howto);
575 instant = parse_bool(howto);
576 onlysel = parse_bool(howto);
582 bool lyxfind(BufferView * bv, FuncRequest const & ev)
584 if (!bv || ev.action() != LFUN_WORD_FIND)
587 //lyxerr << "find called, cmd: " << ev << endl;
595 docstring search = string2find(ev.argument(), casesensitive,
596 matchword, forward, wrap, instant, onlysel);
598 return findOne(bv, search, casesensitive, matchword, forward,
599 false, true, wrap, instant, onlysel);
603 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
605 if (!bv || ev.action() != LFUN_WORD_REPLACE)
608 // data is of the form
611 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
614 docstring howto = split(ev.argument(), rplc, '\n');
615 howto = split(howto, search, '\n');
617 bool casesensitive = parse_bool(howto);
618 bool matchword = parse_bool(howto);
619 bool all = parse_bool(howto);
620 bool forward = parse_bool(howto, true);
621 bool findnext = parse_bool(howto, true);
622 bool wrap = parse_bool(howto);
623 bool onlysel = parse_bool(howto);
625 if (!bv->cursor().selection())
626 // only selection only makes sense with selection
631 int replace_count = 0;
633 replace_count = replaceAll(bv, search, rplc, casesensitive,
635 update = replace_count > 0;
638 replaceOne(bv, search, rplc, casesensitive, matchword,
639 forward, findnext, wrap, onlysel);
641 replace_count = rv.second;
644 Buffer const & buf = bv->buffer();
646 // emit message signal.
648 buf.message(_("String not found in selection."));
650 buf.message(_("String not found."));
652 if (replace_count == 0) {
653 buf.message(_("String found."));
654 } else if (replace_count == 1) {
655 buf.message(_("String has been replaced."));
657 docstring const str = onlysel
658 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
659 : bformat(_("%1$d strings have been replaced."), replace_count);
667 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
669 for (; cur; cur.forwardPos())
670 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
674 DocIterator cur_orig(bv->cursor());
675 docstring q = _("End of file reached while searching forward.\n"
676 "Continue searching from the beginning?");
677 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
678 q, 0, 1, _("&Yes"), _("&No"));
679 if (wrap_answer == 0) {
680 bv->cursor().clear();
681 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
682 bv->clearSelection();
683 cur.setCursor(bv->cursor().selectionBegin());
684 if (findNextChange(bv, cur, false))
687 bv->cursor().setCursor(cur_orig);
694 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
696 for (cur.backwardPos(); cur; cur.backwardPos()) {
697 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
702 DocIterator cur_orig(bv->cursor());
703 docstring q = _("Beginning of file reached while searching backward.\n"
704 "Continue searching from the end?");
705 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
706 q, 0, 1, _("&Yes"), _("&No"));
707 if (wrap_answer == 0) {
708 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
709 bv->cursor().backwardPos();
710 bv->clearSelection();
711 cur.setCursor(bv->cursor().selectionBegin());
712 if (findPreviousChange(bv, cur, false))
715 bv->cursor().setCursor(cur_orig);
722 bool selectChange(Cursor & cur, bool forward)
724 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
726 Change ch = cur.paragraph().lookupChange(cur.pos());
728 CursorSlice tip1 = cur.top();
729 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
730 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
731 if (!ch2.isSimilarTo(ch))
734 CursorSlice tip2 = cur.top();
735 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
737 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
738 if (!ch2.isSimilarTo(ch)) {
739 // take a step forward to correctly set the selection
747 cur.bv().mouseSetCursor(cur, false);
749 cur.bv().mouseSetCursor(cur, true);
757 bool findChange(BufferView * bv, bool forward)
760 cur.setCursor(forward ? bv->cursor().selectionEnd()
761 : bv->cursor().selectionBegin());
762 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
763 return selectChange(cur, forward);
768 bool findNextChange(BufferView * bv)
770 return findChange(bv, true);
774 bool findPreviousChange(BufferView * bv)
776 return findChange(bv, false);
783 typedef vector<pair<string, string> > Escapes;
785 string string2regex(string in)
787 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\$\\])" };
788 string temp = std::regex_replace(in, specialChars, R"(\$&)" );
793 while (fl_pos < temp.size()) {
794 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
795 if (fl_pos == string::npos)
798 temp2 += temp.substr(lastpos, fl_pos - lastpos);
804 if (lastpos < temp.size()) {
805 temp2 += temp.substr(lastpos, temp.size() - lastpos);
810 string correctRegex(string t, bool withformat)
812 /* Convert \backslash => \
813 * and \{, \}, \[, \] => {, }, [, ]
816 regex wordre("(\\\\)*(\\\\((backslash|mathcircumflex) ?|[\\[\\]\\{\\}]))");
819 bool backslashed = false;
820 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
823 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
827 if (sub.str(4) == "backslash") {
830 // transforms '\backslash \{' into '\{'
832 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
833 if ((next == "\\{") || (next == "\\}")) {
839 else if (sub.str(4) == "mathcircumflex")
841 else if (backslashed) {
843 if (withformat && (sub.str(3) == "{"))
844 replace = accents["braceleft"];
845 else if (withformat && (sub.str(3) == "}"))
846 replace = accents["braceright"];
848 // else part should not exist
853 replace = sub.str(3);
855 if (lastpos < (size_t) sub.position(2))
856 s += t.substr(lastpos, sub.position(2) - lastpos);
858 lastpos = sub.position(2) + sub.length(2);
862 else if (lastpos < t.length())
863 s += t.substr(lastpos, t.length() - lastpos);
867 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
868 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
869 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
870 string escape_for_regex(string s, bool withformat)
874 while (lastpos < s.size()) {
875 size_t regex_pos = s.find("\\regexp{", lastpos);
876 if (regex_pos == string::npos) {
877 regex_pos = s.size();
879 if (regex_pos > lastpos) {
880 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
882 if (lastpos == s.size())
885 size_t end_pos = s.find("\\endregexp{}}", regex_pos + 8);
886 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
887 lastpos = end_pos + 13;
893 /// Wrapper for lyx::regex_replace with simpler interface
894 bool regex_replace(string const & s, string & t, string const & searchstr,
895 string const & replacestr)
897 regex e(searchstr, regex_constants::ECMAScript);
899 ostream_iterator<char, char> it(oss);
900 regex_replace(it, s.begin(), s.end(), e, replacestr);
901 // tolerate t and s be references to the same variable
902 bool rv = (s != oss.str());
921 vector <string> result = vector <string>();
922 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {};
925 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
927 if (newres.match2end < oldres.match2end)
928 return MatchResult::newIsTooFar;
929 if (newres.match_len < oldres.match_len)
930 return MatchResult::newIsTooFar;
932 if (newres.match_len == oldres.match_len) {
933 if (newres.match2end == oldres.match2end)
934 return MatchResult::newIsBetter;
936 return MatchResult::newIsInvalid;
939 /** The class performing a match between a position in the document and the FindAdvOptions.
942 class MatchStringAdv {
944 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
946 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
947 ** constructor as opt.search, under the opt.* options settings.
950 ** If set, then match is searched only against beginning of text starting at cur.
951 ** If unset, then match is searched anywhere in text starting at cur.
954 ** The length of the matching text, or zero if no match was found.
956 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
965 /// first buffer on which search was started
966 lyx::Buffer * const p_first_buf;
968 FindAndReplaceOptions const & opt;
971 /// Auxiliary find method (does not account for opt.matchword)
972 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
973 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
975 /** Normalize a stringified or latexified LyX paragraph.
979 ** <li>if search is not casesensitive, then lowercase the string;
980 ** <li>remove any newline at begin or end of the string;
981 ** <li>replace any newline in the middle of the string with a simple space;
982 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
985 ** @todo Normalization should also expand macros, if the corresponding
986 ** search option was checked.
988 string normalize(docstring const & s) const;
989 // normalized string to search
990 string par_as_string;
991 // regular expression to use for searching
992 // regexp2 is same as regexp, but prefixed with a ".*?"
994 QRegularExpression regexp;
995 QRegularExpression regexp2;
1000 // leading format material as string
1001 string lead_as_string;
1002 // par_as_string after removal of lead_as_string
1003 string par_as_string_nolead;
1004 // unmatched open braces in the search string/regexp
1006 // number of (.*?) subexpressions added at end of search regexp for closing
1007 // environments, math mode, styles, etc...
1008 int close_wildcards;
1010 // Are we searching with regular expressions ?
1012 static int valid_matches;
1013 static vector <string> matches;
1014 void FillResults(MatchResult &found_mr);
1017 int MatchStringAdv::valid_matches = 0;
1018 vector <string> MatchStringAdv::matches = vector <string>(10);
1020 void MatchStringAdv::FillResults(MatchResult &found_mr)
1022 if (found_mr.match_len > 0) {
1023 valid_matches = found_mr.result.size();
1024 for (size_t i = 0; i < found_mr.result.size(); i++)
1025 matches[i] = found_mr.result[i];
1031 static docstring buffer_to_latex(Buffer & buffer)
1033 //OutputParams runparams(&buffer.params().encoding());
1034 OutputParams runparams(encodings.fromLyXName("utf8"));
1035 odocstringstream ods;
1037 runparams.nice = true;
1038 runparams.flavor = Flavor::XeTeX;
1039 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1040 // No side effect of file copying and image conversion
1041 runparams.dryrun = true;
1042 if (ignoreFormats.getDeleted())
1043 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
1045 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
1046 pit_type const endpit = buffer.paragraphs().size();
1047 for (pit_type pit = 0; pit != endpit; ++pit) {
1048 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
1049 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
1055 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1058 if (!opt.ignoreformat) {
1059 str = buffer_to_latex(buffer);
1061 // OutputParams runparams(&buffer.params().encoding());
1062 OutputParams runparams(encodings.fromLyXName("utf8"));
1063 runparams.nice = true;
1064 runparams.flavor = Flavor::XeTeX;
1065 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1066 runparams.dryrun = true;
1067 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1068 if (ignoreFormats.getDeleted()) {
1069 option |= AS_STR_SKIPDELETE;
1070 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
1073 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
1075 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1076 Paragraph const & par = buffer.paragraphs().at(pit);
1077 LYXERR(Debug::FIND, "Adding to search string: '"
1078 << par.asString(pos_type(0), par.size(),
1082 str += par.asString(pos_type(0), par.size(),
1086 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1087 string t = to_utf8(str);
1088 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1095 /// Return separation pos between the leading material and the rest
1096 static size_t identifyLeading(string const & s)
1099 // @TODO Support \item[text]
1100 // Kornel: Added textsl, textsf, textit, texttt and noun
1101 // + allow to search for colored text too
1102 while (regex_replace(t, t, "^\\\\(("
1103 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1104 "lyxaddress|lyxrightaddress|"
1105 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1106 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1107 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1108 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1109 || regex_replace(t, t, "^\\$", "")
1110 || regex_replace(t, t, "^\\\\\\[", "")
1111 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1112 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1114 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1119 * Given a latexified string, retrieve some handled features
1120 * The features of the regex will later be compared with the features
1121 * of the searched text. If the regex features are not a
1122 * subset of the analized, then, in not format ignoring search
1123 * we can early stop the search in the relevant inset.
1125 typedef map<string, bool> Features;
1127 static Features identifyFeatures(string const & s)
1129 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1130 static regex const valid("^("
1132 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1133 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1134 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1135 "(u|uu)line|(s|x)out|uwave|"
1136 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1137 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1142 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1145 if (sub.str(1).compare("regexp") == 0) {
1149 string token = sub.str(1);
1151 if (regex_match(token, sub2, valid)) {
1159 if (sub.str(1).compare("endregexp") == 0) {
1169 * defines values features of a key "\\[a-z]+{"
1174 /* Char type with content discarded
1175 * like \hspace{1cm} */
1177 /* Char, like \backslash */
1179 /* replace starting backslash with '#' */
1181 /* \part, \section*, ... */
1183 /* title, author etc */
1185 /* \foreignlanguage{ngerman}, ... */
1188 * to discard language in content */
1191 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1193 /* fonts, colors, markups, ... */
1195 /* footnotesize, ... large, ...
1196 * Ignore all of them */
1199 /* inputencoding, ...
1200 * Discard also content, because they do not help in search */
1203 * like remove, but also all arguments */
1205 /* item, listitem */
1207 /* tex, latex, ... like isChar */
1209 /* like \lettrine[lines=5]{}{} */
1211 // like isStandard, but always remove head
1213 /* End of arguments marker for lettrine,
1214 * so that they can be ignored */
1217 KeyInfo() = default;
1218 KeyInfo(KeyType type, int parcount, bool disable)
1220 parenthesiscount(parcount),
1221 disabled(disable) {}
1222 KeyType keytype = invalid;
1224 int _tokensize = -1;
1225 int _tokenstart = -1;
1226 int _dataStart = -1;
1228 int parenthesiscount = 1;
1229 bool disabled = false;
1230 bool used = false; /* by pattern */
1235 Border(int l=0, int u=0) : low(l), upper(u) {};
1240 #define MAXOPENED 30
1242 bool isPatternString_;
1244 explicit Intervall(bool isPattern, string const & p) :
1245 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1246 hasTitle(false), langcount(0)
1254 static vector<Border> borders;
1255 int depts[MAXOPENED];
1256 int closes[MAXOPENED];
1257 int actualdeptindex;
1258 int previousNotIgnored(int) const;
1259 int nextNotIgnored(int) const;
1260 void handleOpenP(int i);
1261 void handleCloseP(int i, bool closingAllowed);
1262 void resetOpenedP(int openPos);
1263 void addIntervall(int upper);
1264 void addIntervall(int low, int upper); /* if explicit */
1265 void removeAccents();
1266 void setForDefaultLang(KeyInfo const & defLang) const;
1267 int findclosing(int start, int end, char up, char down, int repeat);
1268 void handleParentheses(int lastpos, bool closingAllowed);
1270 int langcount; // Number of disabled language specs up to current position in actual interval
1271 int isOpeningPar(int pos) const;
1273 void output(ostringstream &os, int lastpos);
1274 // string show(int lastpos);
1277 vector<Border> Intervall::borders = vector<Border>(30);
1279 int Intervall::isOpeningPar(int pos) const
1281 if ((pos < 0) || (size_t(pos) >= par.size()))
1283 if (par[pos] != '{')
1285 if (size_t(pos) + 2 >= par.size())
1287 if (par[pos+2] != '}')
1289 if (par[pos+1] == '[' || par[pos+1] == ']')
1294 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1296 // Enable the use of first token again
1297 if (ignoreidx >= 0) {
1298 int value = defLang._tokenstart + defLang._tokensize;
1304 if (borders[borderidx].low < value)
1305 borders[borderidx].low = value;
1306 if (borders[borderidx].upper < value)
1307 borders[borderidx].upper = value;
1312 static void checkDepthIndex(int val)
1314 static int maxdepthidx = MAXOPENED-2;
1315 static int lastmaxdepth = 0;
1316 if (val > lastmaxdepth) {
1317 LYXERR(Debug::INFO, "Depth reached " << val);
1320 if (val > maxdepthidx) {
1322 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1327 // Not needed, because borders are now dynamically expanded
1328 static void checkIgnoreIdx(int val)
1330 static int lastmaxignore = -1;
1331 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1332 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1333 lastmaxignore = val;
1339 * Expand the region of ignored parts of the input latex string
1340 * The region is only relevant in output()
1342 void Intervall::addIntervall(int low, int upper)
1345 if (low == upper) return;
1346 for (idx = ignoreidx+1; idx > 0; --idx) {
1347 if (low > borders[idx-1].upper) {
1351 Border br(low, upper);
1352 if (idx > ignoreidx) {
1353 if (borders.size() <= size_t(idx)) {
1354 borders.push_back(br);
1360 // checkIgnoreIdx(ignoreidx);
1364 // Expand only if one of the new bound is inside the interwall
1365 // We know here that br.low > borders[idx-1].upper
1366 if (br.upper < borders[idx].low) {
1367 // We have to insert at this pos
1368 if (size_t(ignoreidx+1) >= borders.size()) {
1369 borders.push_back(borders[ignoreidx]);
1372 borders[ignoreidx+1] = borders[ignoreidx];
1374 for (int i = ignoreidx; i > idx; --i) {
1375 borders[i] = borders[i-1];
1379 // checkIgnoreIdx(ignoreidx);
1382 // Here we know, that we are overlapping
1383 if (br.low > borders[idx].low)
1384 br.low = borders[idx].low;
1385 // check what has to be concatenated
1387 for (int i = idx; i <= ignoreidx; i++) {
1388 if (br.upper >= borders[i].low) {
1390 if (br.upper < borders[i].upper)
1391 br.upper = borders[i].upper;
1397 // count should be >= 1 here
1400 for (int i = idx + count; i <= ignoreidx; i++) {
1401 borders[i-count+1] = borders[i];
1403 ignoreidx -= count - 1;
1409 static void buildaccent(string n, string param, string values)
1413 const char delim = '|';
1414 while (getline(s, name, delim)) {
1416 for (char c : param) {
1417 string key = name + "{" + c + "}";
1418 // get the corresponding utf8-value
1419 if ((values[start] & 0xc0) != 0xc0) {
1420 // should not happen, utf8 encoding starts at least with 11xxxxxx
1421 // but value for '\dot{i}' is 'i', which is ascii
1422 if ((values[start] & 0x80) == 0) {
1424 accents[key] = values.substr(start, 1);
1425 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1430 for (int j = 1; ;j++) {
1431 if (start + j >= values.size()) {
1432 accents[key] = values.substr(start, j);
1433 start = values.size() - 1;
1436 else if ((values[start+j] & 0xc0) != 0x80) {
1437 // This is the first byte of following utf8 char
1438 accents[key] = values.substr(start, j);
1440 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1449 static string getutf8(unsigned uchar)
1452 string ret = string();
1454 if (uchar <= 0x7f) {
1455 c[maxc-1] = uchar & 0x7f;
1458 unsigned char rest = 0x40;
1459 unsigned char first = 0x80;
1461 for (int i = start; i >=0; --i) {
1463 c[i] = first + uchar;
1466 c[i] = 0x80 | (uchar & 0x3f);
1473 for (int i = 0; i < maxc; i++) {
1474 if (c[i] == 0) continue;
1480 static void buildAccentsMap()
1482 accents["imath"] = "ı";
1484 accents["jmath"] = "ȷ";
1485 accents["cdot"] = "·";
1486 accents["textasciicircum"] = "^";
1487 accents["mathcircumflex"] = "^";
1488 accents["sim"] = "~";
1489 accents["guillemotright"] = "»";
1490 accents["guillemotleft"] = "«";
1491 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1492 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1493 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1494 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1495 accents["negmedspace"] = getutf8(0xf0005);
1496 accents["thickspace"] = getutf8(0xf0006);
1497 accents["negthickspace"] = getutf8(0xf0007);
1498 accents["lyx"] = getutf8(0xf0010); // Used logos
1499 accents["LyX"] = getutf8(0xf0010);
1500 accents["tex"] = getutf8(0xf0011);
1501 accents["TeX"] = getutf8(0xf0011);
1502 accents["latex"] = getutf8(0xf0012);
1503 accents["LaTeX"] = getutf8(0xf0012);
1504 accents["latexe"] = getutf8(0xf0013);
1505 accents["LaTeXe"] = getutf8(0xf0013);
1506 accents["lyxarrow"] = getutf8(0xf0020);
1507 accents["braceleft"] = getutf8(0xf0030);
1508 accents["braceright"] = getutf8(0xf0031);
1509 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1510 accents["backslash LyX"] = getutf8(0xf0010);
1511 accents["backslash tex"] = getutf8(0xf0011);
1512 accents["backslash TeX"] = getutf8(0xf0011);
1513 accents["backslash latex"] = getutf8(0xf0012);
1514 accents["backslash LaTeX"] = getutf8(0xf0012);
1515 accents["backslash latexe"] = getutf8(0xf0013);
1516 accents["backslash LaTeXe"] = getutf8(0xf0013);
1517 accents["backslash lyxarrow"] = getutf8(0xf0020);
1518 accents["ddot{\\imath}"] = "ï";
1519 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1520 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1521 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1522 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1523 accents["acute{\\imath}"] = "í";
1524 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1525 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1526 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1527 buildaccent("mathring|r", "aAuUwy",
1529 accents["check{\\imath}"] = "ǐ";
1530 accents["check{\\jmath}"] = "ǰ";
1531 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1532 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1533 accents["hat{\\imath}"] = "î";
1534 accents["hat{\\jmath}"] = "ĵ";
1535 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1536 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1537 accents["bar{\\imath}"] = "ī";
1538 buildaccent("bar|=", "aAeEiIoOuUyY",
1539 "āĀēĒīĪōŌūŪȳȲ"); // macron
1540 accents["tilde{\\imath}"] = "ĩ";
1541 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1542 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1543 accents["breve{\\imath}"] = "ĭ";
1544 buildaccent("breve|u", "aAeEgGiIoOuU",
1545 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1546 accents["grave{\\imath}"] = "ì";
1547 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1548 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1549 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1550 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1551 buildaccent("ogonek|k", "AaEeIiUuOo",
1552 "ĄąĘęĮįŲųǪǫ"); // ogonek
1553 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1554 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1555 buildaccent("subring|textsubring", "Aa",
1557 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1558 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1559 buildaccent("subtilde|textsubtilde", "EeIiUu",
1560 "ḚḛḬḭṴṵ"); // subtilde
1561 accents["dgrave{\\imath}"] = "ȉ";
1562 accents["textdoublegrave{\\i}"] = "ȉ";
1563 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1564 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1565 accents["rcap{\\imath}"] = "ȉ";
1566 accents["textroundcap{\\i}"] = "ȉ";
1567 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1568 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1569 buildaccent("slashed", "oO",
1574 * Created accents in math or regexp environment
1575 * are macros, but we need the utf8 equivalent
1577 void Intervall::removeAccents()
1579 if (accents.empty())
1581 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1582 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1583 "|((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]))");
1585 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1587 string key = sub.str(1);
1588 AccentsIterator it_ac = accents.find(key);
1589 if (it_ac != accents.end()) {
1590 string val = it_ac->second;
1591 size_t pos = sub.position(size_t(0));
1592 for (size_t i = 0; i < val.size(); i++) {
1593 par[pos+i] = val[i];
1595 // Remove possibly following space too
1596 if (par[pos+sub.str(0).size()] == ' ')
1597 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1599 addIntervall(pos+val.size(), pos + sub.str(0).size());
1600 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1601 // remove traces of any remaining chars
1606 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1611 void Intervall::handleOpenP(int i)
1614 depts[actualdeptindex] = i+1;
1615 closes[actualdeptindex] = -1;
1616 checkDepthIndex(actualdeptindex);
1619 void Intervall::handleCloseP(int i, bool closingAllowed)
1621 if (actualdeptindex <= 0) {
1622 if (! closingAllowed)
1623 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1624 // if we are at the very end
1625 addIntervall(i, i+1);
1628 closes[actualdeptindex] = i+1;
1633 void Intervall::resetOpenedP(int openPos)
1635 // Used as initializer for foreignlanguage entry
1636 actualdeptindex = 1;
1637 depts[1] = openPos+1;
1641 int Intervall::previousNotIgnored(int start) const
1643 int idx = 0; /* int intervalls */
1644 for (idx = ignoreidx; idx >= 0; --idx) {
1645 if (start > borders[idx].upper)
1647 if (start >= borders[idx].low)
1648 start = borders[idx].low-1;
1653 int Intervall::nextNotIgnored(int start) const
1655 int idx = 0; /* int intervalls */
1656 for (idx = 0; idx <= ignoreidx; idx++) {
1657 if (start < borders[idx].low)
1659 if (start < borders[idx].upper)
1660 start = borders[idx].upper;
1665 typedef unordered_map<string, KeyInfo> KeysMap;
1666 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
1667 typedef vector< KeyInfo> Entries;
1668 static KeysMap keys = unordered_map<string, KeyInfo>();
1674 Intervall interval_;
1675 void buildKeys(bool);
1676 void buildEntries(bool);
1677 void makeKey(const string &, KeyInfo, bool isPatternString);
1678 void processRegion(int start, int region_end); /* remove {} parts */
1679 void removeHead(KeyInfo const &, int count=0);
1682 LatexInfo(string const & par, bool isPatternString)
1683 : entidx_(-1), interval_(isPatternString, par)
1685 buildKeys(isPatternString);
1686 entries_ = vector<KeyInfo>();
1687 buildEntries(isPatternString);
1691 if (entries_.empty()) {
1694 if (entries_[0].keytype == KeyInfo::isTitle) {
1695 interval_.hasTitle = true;
1696 if (! entries_[0].disabled) {
1697 interval_.titleValue = entries_[0].head;
1700 interval_.titleValue = "";
1702 removeHead(entries_[0]);
1703 if (entries_.size() > 1)
1712 if (int(entries_.size()) > entidx_) {
1719 bool setNextKey(int idx) {
1720 if ((idx == entidx_) && (entidx_ >= 0)) {
1727 int find(int start, KeyInfo::KeyType keytype) const {
1731 while (tmpIdx < int(entries_.size())) {
1732 if (entries_[tmpIdx].keytype == keytype)
1738 int process(ostringstream & os, KeyInfo const & actual);
1739 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1740 // string show(int lastpos) { return interval.show(lastpos);};
1741 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1742 KeyInfo &getKeyInfo(int keyinfo) {
1743 static KeyInfo invalidInfo = KeyInfo();
1744 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1747 return entries_[keyinfo];
1749 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1750 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1754 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1758 for (int i = start; i < end; i += 1 + skip) {
1762 if (c == '\\') skip = 1;
1766 else if (c == down) {
1769 if ((repeat <= 0) || (par[i+1] != up))
1783 size_t mathpostfixsize;
1785 size_t mathprefixsize;
1789 vector<MathEntry> entries_;
1794 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
1795 MathEntry m = MathEntry();
1797 m.mathStart = start;
1798 m.mathprefixsize = prefixsize;
1799 m.mathEnd = end + postfixsize;
1800 m.mathpostfixsize = postfixsize;
1801 m.mathSize = m.mathEnd - m.mathStart;
1802 entries_.push_back(m);
1804 bool empty() const { return entries_.empty(); };
1805 size_t getEndPos() const {
1806 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1809 return entries_[actualIdx_].mathEnd;
1811 size_t getStartPos() const {
1812 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1813 return 100000; /* definitely enough? */
1815 return entries_[actualIdx_].mathStart;
1817 size_t getPrefixSize() const {
1818 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1821 return entries_[actualIdx_].mathprefixsize;
1823 size_t getPostfixSize() const {
1824 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1827 return entries_[actualIdx_].mathpostfixsize;
1829 size_t getFirstPos() {
1831 return getStartPos();
1833 size_t getSize() const {
1834 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1837 return entries_[actualIdx_].mathSize;
1839 void incrEntry() { actualIdx_++; };
1842 void LatexInfo::buildEntries(bool isPatternString)
1844 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1845 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1846 static bool disableLanguageOverride = false;
1847 smatch sub, submath;
1848 bool evaluatingRegexp = false;
1850 bool evaluatingMath = false;
1851 bool evaluatingCode = false;
1853 bool evaluatingOptional = false;
1854 size_t optionalEnd = 0;
1857 bool math_end_waiting = false;
1858 size_t math_pos = 10000;
1859 size_t math_prefix_size = 1;
1861 static vector<string> usedText = vector<string>();
1862 static bool removeMathHull = false;
1864 interval_.removeAccents();
1866 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1868 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1869 // prefixed by odd count of '\\'
1872 if (math_end_waiting) {
1873 size_t pos = submath.position(size_t(2));
1874 if ((math_end == "$") &&
1875 (submath.str(2) == "$")) {
1876 mi.insert("$", math_pos, 1, pos, 1);
1877 math_end_waiting = false;
1879 else if ((math_end == "\\]") &&
1880 (submath.str(2) == "\\]")) {
1881 mi.insert("\\]", math_pos, 2, pos, 2);
1882 math_end_waiting = false;
1884 else if ((submath.str(3).compare("end") == 0) &&
1885 (submath.str(4).compare(math_end) == 0)) {
1886 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
1887 math_end_waiting = false;
1893 if (submath.str(3).compare("begin") == 0) {
1894 math_end_waiting = true;
1895 math_end = submath.str(4);
1896 math_pos = submath.position(size_t(2));
1897 math_prefix_size = submath.str(2).length();
1899 else if (submath.str(2).compare("\\[") == 0) {
1900 math_end_waiting = true;
1902 math_pos = submath.position(size_t(2));
1904 else if (submath.str(2) == "$") {
1905 size_t pos = submath.position(size_t(2));
1906 math_end_waiting = true;
1912 // Ignore language if there is math somewhere in pattern-string
1913 if (isPatternString) {
1914 for (auto s: usedText) {
1915 // Remove entries created in previous search runs
1918 usedText = vector<string>();
1921 keys["foreignlanguage"].disabled = true;
1922 disableLanguageOverride = true;
1923 removeMathHull = false;
1926 removeMathHull = true; // used later if not isPatternString
1927 disableLanguageOverride = false;
1931 if (disableLanguageOverride) {
1932 keys["foreignlanguage"].disabled = true;
1935 math_pos = mi.getFirstPos();
1936 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1938 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1939 // prefixed by odd count of '\\'
1942 string key = sub.str(5);
1944 if (sub.str(2)[0] == '\\')
1945 key = sub.str(2)[1];
1950 KeysIterator it_key = keys.find(key);
1951 if (it_key != keys.end()) {
1952 if (it_key->second.keytype == KeyInfo::headRemove) {
1953 KeyInfo found1 = it_key->second;
1954 found1.disabled = true;
1955 found1.head = "\\" + key + "{";
1956 found1._tokenstart = sub.position(size_t(2));
1957 found1._tokensize = found1.head.length();
1958 found1._dataStart = found1._tokenstart + found1.head.length();
1959 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1960 found1._dataEnd = endpos;
1965 if (evaluatingRegexp) {
1966 if (sub.str(3).compare("endregexp") == 0) {
1967 evaluatingRegexp = false;
1968 // found._tokenstart already set
1969 found._dataEnd = sub.position(size_t(2)) + 13;
1970 found._dataStart = found._dataEnd;
1971 found._tokensize = found._dataEnd - found._tokenstart;
1972 found.parenthesiscount = 0;
1973 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1980 if (evaluatingMath) {
1981 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1983 evaluatingMath = false;
1985 math_pos = mi.getStartPos();
1987 if (it_key == keys.end()) {
1988 found = KeyInfo(KeyInfo::isStandard, 0, true);
1989 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1990 found = KeyInfo(KeyInfo::isText, 0, false);
1991 if (isPatternString) {
1992 found.keytype = KeyInfo::isChar;
1993 found.disabled = false;
1997 usedText.push_back(key);
2001 if (key.compare("regexp") == 0) {
2002 evaluatingRegexp = true;
2003 found._tokenstart = sub.position(size_t(2));
2004 found._tokensize = 0;
2008 // Handle the other params of key
2009 if (found.keytype == KeyInfo::isIgnored)
2011 else if (found.keytype == KeyInfo::isMath) {
2012 if (size_t(sub.position(size_t(2))) == math_pos) {
2014 found._tokenstart = sub.position(size_t(2));
2015 found._tokensize = mi.getSize();
2016 found._dataEnd = found._tokenstart + found._tokensize;
2017 found._dataStart = found._dataEnd;
2018 found.parenthesiscount = 0;
2019 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2020 if (removeMathHull) {
2021 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2022 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2024 evaluatingMath = true;
2027 // begin|end of unknown env, discard
2028 // First handle tables
2029 // longtable|tabular
2030 bool discardComment;
2032 found.keytype = KeyInfo::doRemove;
2033 if ((sub.str(7).compare("longtable") == 0) ||
2034 (sub.str(7).compare("tabular") == 0)) {
2035 discardComment = true; /* '%' */
2038 discardComment = false;
2039 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2041 string token = sub.str(7);
2042 if (regex_match(token, sub2, removeArgs)) {
2043 found.keytype = KeyInfo::removeWithArg;
2046 // discard spaces before pos(2)
2047 int pos = sub.position(size_t(2));
2049 for (count = 0; pos - count > 0; count++) {
2050 char c = interval_.par[pos-count-1];
2051 if (discardComment) {
2052 if ((c != ' ') && (c != '%'))
2058 found._tokenstart = pos - count;
2059 if (sub.str(3).compare(0, 5, "begin") == 0) {
2060 size_t pos1 = pos + sub.str(2).length();
2061 if (sub.str(7).compare("cjk") == 0) {
2062 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2063 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2065 found.keytype = KeyInfo::isMain;
2066 found._dataStart = pos1;
2067 found._dataEnd = interval_.par.length();
2068 found.disabled = keys["foreignlanguage"].disabled;
2069 found.used = keys["foreignlanguage"].used;
2070 found._tokensize = pos1 - found._tokenstart;
2071 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2074 // Swallow possible optional params
2075 while (interval_.par[pos1] == '[') {
2076 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2078 // Swallow also the eventual parameter
2079 if (interval_.par[pos1] == '{') {
2080 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2083 found._dataEnd = pos1;
2085 found._dataStart = found._dataEnd;
2086 found._tokensize = count + found._dataEnd - pos;
2087 found.parenthesiscount = 0;
2088 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2089 found.disabled = true;
2093 // Handle "\end{...}"
2094 found._dataStart = pos + sub.str(2).length();
2095 found._dataEnd = found._dataStart;
2096 found._tokensize = count + found._dataEnd - pos;
2097 found.parenthesiscount = 0;
2098 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2099 found.disabled = true;
2103 else if (found.keytype != KeyInfo::isRegex) {
2104 found._tokenstart = sub.position(size_t(2));
2105 if (found.parenthesiscount == 0) {
2106 // Probably to be discarded
2107 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2108 char following = interval_.par[following_pos];
2109 if (following == ' ')
2110 found.head = "\\" + sub.str(5) + " ";
2111 else if (following == '=') {
2112 // like \uldepth=1000pt
2113 found.head = sub.str(2);
2116 found.head = "\\" + key;
2117 found._tokensize = found.head.length();
2118 found._dataEnd = found._tokenstart + found._tokensize;
2119 found._dataStart = found._dataEnd;
2122 int params = found._tokenstart + key.length() + 1;
2123 if (evaluatingOptional) {
2124 if (size_t(found._tokenstart) > optionalEnd) {
2125 evaluatingOptional = false;
2128 found.disabled = true;
2131 int optend = params;
2132 while (interval_.par[optend] == '[') {
2133 // discard optional parameters
2134 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2136 if (optend > params) {
2137 key += interval_.par.substr(params, optend-params);
2138 evaluatingOptional = true;
2139 optionalEnd = optend;
2140 if (found.keytype == KeyInfo::isSectioning) {
2141 // Remove optional values (but still keep in header)
2142 interval_.addIntervall(params, optend);
2145 string token = sub.str(7);
2147 if (interval_.par[optend] != '{') {
2149 found.parenthesiscount = 0;
2150 found.head = "\\" + key;
2153 closings = found.parenthesiscount;
2154 if (found.parenthesiscount == 1) {
2155 found.head = "\\" + key + "{";
2157 else if (found.parenthesiscount > 1) {
2159 found.head = sub.str(2) + "{";
2160 closings = found.parenthesiscount - 1;
2163 found.head = "\\" + key + "{";
2166 found._tokensize = found.head.length();
2167 found._dataStart = found._tokenstart + found.head.length();
2168 if (found.keytype == KeyInfo::doRemove) {
2170 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2171 if (endpar >= interval_.par.length())
2172 found._dataStart = interval_.par.length();
2174 found._dataStart = endpar;
2175 found._tokensize = found._dataStart - found._tokenstart;
2178 found._dataStart = found._tokenstart + found._tokensize;
2182 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2183 found._dataStart += 15;
2187 endpos = found._dataStart - 1;
2189 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2190 if (found.keytype == KeyInfo::isList) {
2191 // Check if it really is list env
2192 static regex const listre("^([a-z]+)$");
2194 if (!regex_match(token, sub2, listre)) {
2195 // Change the key of this entry. It is not in a list/item environment
2196 found.keytype = KeyInfo::endArguments;
2199 if (found.keytype == KeyInfo::noMain) {
2200 evaluatingCode = true;
2202 codeStart = found._dataStart;
2204 else if (evaluatingCode) {
2205 if (size_t(found._dataStart) > codeEnd)
2206 evaluatingCode = false;
2207 else if (found.keytype == KeyInfo::isMain) {
2208 // Disable this key, treate it as standard
2209 found.keytype = KeyInfo::isStandard;
2210 found.disabled = true;
2211 if ((codeEnd +1 >= interval_.par.length()) &&
2212 (found._tokenstart == codeStart)) {
2213 // trickery, because the code inset starts
2214 // with \selectlanguage ...
2216 if (entries_.size() > 1) {
2217 entries_[entries_.size()-1]._dataEnd = codeEnd;
2222 if ((endpos == interval_.par.length()) &&
2223 (found.keytype == KeyInfo::doRemove)) {
2224 // Missing closing => error in latex-input?
2225 // therefore do not delete remaining data
2226 found._dataStart -= 1;
2227 found._dataEnd = found._dataStart;
2230 found._dataEnd = endpos;
2232 if (isPatternString) {
2233 keys[key].used = true;
2236 entries_.push_back(found);
2240 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2242 stringstream s(keysstring);
2244 const char delim = '|';
2245 while (getline(s, key, delim)) {
2246 KeyInfo keyII(keyI);
2247 if (isPatternString) {
2250 else if ( !keys[key].used)
2251 keyII.disabled = true;
2256 void LatexInfo::buildKeys(bool isPatternString)
2259 static bool keysBuilt = false;
2260 if (keysBuilt && !isPatternString) return;
2262 // Keys to ignore in any case
2263 makeKey("text|textcyrillic|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2264 // Known standard keys with 1 parameter.
2265 // Split is done, if not at start of region
2266 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2267 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2268 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2269 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2270 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2271 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2273 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2274 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2275 makeKey("section*|subsection*|subsubsection*|paragraph*",
2276 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2277 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2278 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2280 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2282 // Split is done, if not at start of region
2283 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2284 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2286 // Split is done always.
2287 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2291 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2292 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2293 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2294 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2296 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2297 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2298 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2299 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2301 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2302 // Custom space/skip, remove the content (== length value)
2303 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2304 // Found in fr/UserGuide.lyx
2305 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2307 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2308 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2309 // Known macros to remove (including their parameter)
2311 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2312 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2313 // handle like standard keys with 1 parameter.
2314 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2316 // Ignore deleted text
2317 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2318 // but preserve added text
2319 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2321 // Macros to remove, but let the parameter survive
2323 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2325 // Remove language spec from content of these insets
2326 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2328 // Same effect as previous, parameter will survive (because there is no one anyway)
2330 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2331 // Remove table decorations
2332 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2333 // Discard shape-header.
2334 // For footnote or shortcut too, because of lang settings
2335 // and wrong handling if used 'KeyInfo::noMain'
2336 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2337 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2338 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2339 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2340 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2341 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2342 // like ('tiny{}' or '\tiny ' ... )
2343 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2345 // Survives, like known character
2346 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2347 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2348 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2350 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2351 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2352 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2354 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2355 // Remove RTL/LTR marker
2356 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2357 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2358 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2359 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2360 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2361 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2362 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2363 if (isPatternString) {
2364 // Allow the first searched string to rebuild the keys too
2368 // no need to rebuild again
2374 * Keep the list of actual opened parentheses actual
2375 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2377 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2380 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2384 if (c == '\\') skip = 1;
2385 else if (c == '{') {
2388 else if (c == '}') {
2389 handleCloseP(i, closingAllowed);
2395 string Intervall::show(int lastpos)
2397 int idx = 0; /* int intervalls */
2400 for (idx = 0; idx <= ignoreidx; idx++) {
2401 while (i < lastpos) {
2403 if (i <= borders[idx].low) {
2404 if (borders[idx].low > lastpos)
2405 printsize = lastpos - i;
2407 printsize = borders[idx].low - i;
2408 s += par.substr(i, printsize);
2410 if (i >= borders[idx].low)
2411 i = borders[idx].upper;
2414 i = borders[idx].upper;
2420 s += par.substr(i, lastpos-i);
2426 void Intervall::output(ostringstream &os, int lastpos)
2428 // get number of chars to output
2429 int idx = 0; /* int intervalls */
2432 string startTitle = titleValue;
2433 for (idx = 0; idx <= ignoreidx; idx++) {
2435 if (i <= borders[idx].low) {
2437 if (borders[idx].low > lastpos)
2438 printsize = lastpos - i;
2440 printsize = borders[idx].low - i;
2441 if (printsize > 0) {
2442 os << startTitle << par.substr(i, printsize);
2444 printed += printsize;
2447 handleParentheses(i, false);
2448 if (i >= borders[idx].low)
2449 i = borders[idx].upper;
2452 i = borders[idx].upper;
2459 os << startTitle << par.substr(i, lastpos-i);
2460 printed += lastpos-i;
2462 handleParentheses(lastpos, false);
2464 if (keys["foreignlanguage"].disabled)
2465 startindex = actualdeptindex-langcount;
2467 startindex = actualdeptindex;
2468 for (int i = startindex; i > 0; --i) {
2471 if (hasTitle && (printed > 0))
2473 if (! isPatternString_)
2475 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2478 void LatexInfo::processRegion(int start, int region_end)
2480 while (start < region_end) { /* Let {[} and {]} survive */
2481 int cnt = interval_.isOpeningPar(start);
2483 // Closing is allowed past the region
2484 int closing = interval_.findclosing(start+1, interval_.par.length());
2485 interval_.addIntervall(start, start+1);
2486 interval_.addIntervall(closing, closing+1);
2490 start = interval_.nextNotIgnored(start+1);
2494 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2496 if (actual.parenthesiscount == 0) {
2497 // "{\tiny{} ...}" ==> "{{} ...}"
2498 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2501 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2502 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2503 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2507 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2510 switch (actual.keytype)
2512 case KeyInfo::isTitle: {
2514 nextKeyIdx = getNextKey();
2517 case KeyInfo::cleanToStart: {
2518 actual._dataEnd = actual._dataStart;
2519 nextKeyIdx = getNextKey();
2520 // Search for end of arguments
2521 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2523 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2524 entries_[i].disabled = true;
2526 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2528 while (interval_.par[actual._dataEnd] == ' ')
2530 interval_.addIntervall(0, actual._dataEnd+1);
2531 interval_.actualdeptindex = 0;
2532 interval_.depts[0] = actual._dataEnd+1;
2533 interval_.closes[0] = -1;
2536 case KeyInfo::isText:
2537 interval_.par[actual._tokenstart] = '#';
2538 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2539 nextKeyIdx = getNextKey();
2541 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2542 if (actual.disabled)
2543 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2545 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2548 case KeyInfo::isChar: {
2549 nextKeyIdx = getNextKey();
2552 case KeyInfo::isSize: {
2553 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2554 if (actual.parenthesiscount == 0)
2555 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2557 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2559 nextKeyIdx = getNextKey();
2561 // Here _dataStart points to '{', so correct it
2562 actual._dataStart += 1;
2563 actual._tokensize += 1;
2564 actual.parenthesiscount = 1;
2565 if (interval_.par[actual._dataStart] == '}') {
2566 // Determine the end if used like '{\tiny{}...}'
2567 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2568 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2571 // Determine the end if used like '\tiny{...}'
2572 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2574 // Split on this key if not at start
2575 int start = interval_.nextNotIgnored(previousStart);
2576 if (start < actual._tokenstart) {
2577 interval_.output(os, actual._tokenstart);
2578 interval_.addIntervall(start, actual._tokenstart);
2580 // discard entry if at end of actual
2581 nextKeyIdx = process(os, actual);
2585 case KeyInfo::endArguments: {
2586 // Remove trailing '{}' too
2587 actual._dataStart += 1;
2588 actual._dataEnd += 1;
2589 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2590 nextKeyIdx = getNextKey();
2593 case KeyInfo::noMain:
2595 case KeyInfo::isStandard: {
2596 if (actual.disabled) {
2598 processRegion(actual._dataStart, actual._dataStart+1);
2599 nextKeyIdx = getNextKey();
2601 // Split on this key if not at datastart of calling entry
2602 int start = interval_.nextNotIgnored(previousStart);
2603 if (start < actual._tokenstart) {
2604 interval_.output(os, actual._tokenstart);
2605 interval_.addIntervall(start, actual._tokenstart);
2607 // discard entry if at end of actual
2608 nextKeyIdx = process(os, actual);
2612 case KeyInfo::removeWithArg: {
2613 nextKeyIdx = getNextKey();
2614 // Search for end of arguments
2615 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2617 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2618 entries_[i].disabled = true;
2620 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2622 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2625 case KeyInfo::doRemove: {
2626 // Remove the key with all parameters and following spaces
2629 if (interval_.par[actual._dataEnd-1] == ' ')
2630 start = actual._dataEnd;
2632 start = actual._dataEnd+1;
2633 for (pos = start; pos < interval_.par.length(); pos++) {
2634 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2637 // Remove also enclosing parentheses [] and {}
2640 while (actual._tokenstart > numpars) {
2641 if (pos+numpars >= interval_.par.size())
2643 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2645 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2651 if (interval_.par[pos+numpars] == ' ')
2655 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2656 nextKeyIdx = getNextKey();
2659 case KeyInfo::isList: {
2660 // Discard space before _tokenstart
2662 for (count = 0; count < actual._tokenstart; count++) {
2663 if (interval_.par[actual._tokenstart-count-1] != ' ')
2666 nextKeyIdx = getNextKey();
2667 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2669 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2671 // How else can we catch this one?
2672 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2673 entries_[i].disabled = true;
2675 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2677 else if (nextKeyIdx > 0) {
2678 // Ignore any lang entries inside data region
2679 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2680 if (entries_[i].keytype == KeyInfo::isMain)
2681 entries_[i].disabled = true;
2684 if (actual.disabled) {
2685 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2688 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2690 if (interval_.par[actual._dataEnd+1] == '[') {
2691 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2692 if ((interval_.par[actual._dataEnd+2] == '{') &&
2693 (interval_.par[posdown-1] == '}')) {
2694 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2695 interval_.addIntervall(posdown-1, posdown+1);
2698 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2699 interval_.addIntervall(posdown, posdown+1);
2701 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2702 if (blk > posdown) {
2703 // Discard at most 1 space after empty item
2705 for (count = 0; count < 1; count++) {
2706 if (interval_.par[blk+count] != ' ')
2710 interval_.addIntervall(blk, blk+count);
2715 case KeyInfo::isSectioning: {
2716 // Discard spaces before _tokenstart
2718 int val = actual._tokenstart;
2719 for (count = 0; count < actual._tokenstart;) {
2720 val = interval_.previousNotIgnored(val-1);
2721 if (val < 0 || interval_.par[val] != ' ')
2724 count = actual._tokenstart - val;
2727 if (actual.disabled) {
2728 removeHead(actual, count);
2729 nextKeyIdx = getNextKey();
2731 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2732 nextKeyIdx = process(os, actual);
2736 case KeyInfo::isMath: {
2737 // Same as regex, use the content unchanged
2738 nextKeyIdx = getNextKey();
2741 case KeyInfo::isRegex: {
2742 // DO NOT SPLIT ON REGEX
2744 nextKeyIdx = getNextKey();
2747 case KeyInfo::isIgnored: {
2748 // Treat like a character for now
2749 nextKeyIdx = getNextKey();
2752 case KeyInfo::isMain: {
2753 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2754 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2755 if (actual._tokenstart > 0) {
2756 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2757 if ((prev >= 0) && interval_.par[prev] == '%')
2758 interval_.addIntervall(prev, prev+1);
2760 if (actual.disabled) {
2762 interval_.langcount++;
2763 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2764 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2765 // Discard also the space before math-equation
2766 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2768 nextKeyIdx = getNextKey();
2769 // interval.resetOpenedP(actual._dataStart-1);
2772 if (actual._tokenstart < 26) {
2773 // for the first (and maybe dummy) language
2774 interval_.setForDefaultLang(actual);
2776 interval_.resetOpenedP(actual._dataStart-1);
2780 case KeyInfo::invalid:
2781 case KeyInfo::headRemove:
2782 // These two cases cannot happen, already handled
2785 // LYXERR(Debug::INFO, "Unhandled keytype");
2786 nextKeyIdx = getNextKey();
2793 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2795 int end = interval_.nextNotIgnored(actual._dataEnd);
2796 int oldStart = actual._dataStart;
2797 int nextKeyIdx = getNextKey();
2799 if ((nextKeyIdx < 0) ||
2800 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2801 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2802 if (oldStart <= end) {
2803 processRegion(oldStart, end);
2808 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2810 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2811 (void) dispatch(os, actual._dataStart, nextKey);
2812 end = nextKey._tokenstart;
2815 processRegion(oldStart, nextKey._tokenstart);
2816 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2818 oldStart = nextKey._dataEnd+1;
2820 // now nextKey is either invalid or is outside of actual._dataEnd
2821 // output the remaining and discard myself
2822 if (oldStart <= end) {
2823 processRegion(oldStart, end);
2825 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2827 // This is the normal case.
2828 // But if using the firstlanguage, the closing may be missing
2830 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2832 if (actual._dataEnd < end)
2833 output_end = interval_.nextNotIgnored(actual._dataEnd);
2834 else if (interval_.par.size() > (size_t) end)
2835 output_end = interval_.nextNotIgnored(end);
2837 output_end = interval_.par.size();
2838 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2839 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2841 // Remove possible empty data
2842 int dstart = interval_.nextNotIgnored(actual._dataStart);
2843 while (interval_.isOpeningPar(dstart) == 1) {
2844 interval_.addIntervall(dstart, dstart+1);
2845 int dend = interval_.findclosing(dstart+1, output_end);
2846 interval_.addIntervall(dend, dend+1);
2847 dstart = interval_.nextNotIgnored(dstart+1);
2849 if (dstart < output_end)
2850 interval_.output(os, output_end);
2852 interval_.addIntervall(0, end);
2854 interval_.addIntervall(actual._tokenstart, end);
2858 string splitOnKnownMacros(string par, bool isPatternString)
2861 LatexInfo li(par, isPatternString);
2862 // LYXERR(Debug::INFO, "Berfore split: " << par);
2863 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2865 DummyKey._tokensize = 0;
2866 DummyKey._dataStart = 0;
2867 DummyKey._dataEnd = par.length();
2868 DummyKey.disabled = true;
2869 int firstkeyIdx = li.getFirstKey();
2871 if (firstkeyIdx >= 0) {
2872 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2873 DummyKey._tokenstart = firstKey._tokenstart;
2875 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2876 // Use dummy firstKey
2877 firstKey = DummyKey;
2878 (void) li.setNextKey(firstkeyIdx);
2881 if (par.substr(firstKey._dataStart, 2) == "% ")
2882 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2884 nextkeyIdx = li.process(os, firstKey);
2885 while (nextkeyIdx >= 0) {
2886 // Check for a possible gap between the last
2887 // entry and this one
2888 int datastart = li.nextNotIgnored(firstKey._dataStart);
2889 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2890 if ((nextKey._tokenstart > datastart)) {
2892 firstKey._dataStart = datastart;
2893 firstKey._dataEnd = par.length();
2894 (void) li.setNextKey(nextkeyIdx);
2895 // Fake the last opened parenthesis
2896 li.setForDefaultLang(firstKey);
2897 nextkeyIdx = li.process(os, firstKey);
2900 if (nextKey.keytype != KeyInfo::isMain) {
2901 firstKey._dataStart = datastart;
2902 firstKey._dataEnd = nextKey._dataEnd+1;
2903 (void) li.setNextKey(nextkeyIdx);
2904 li.setForDefaultLang(firstKey);
2905 nextkeyIdx = li.process(os, firstKey);
2908 nextkeyIdx = li.process(os, nextKey);
2912 // Handle the remaining
2913 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2914 firstKey._dataEnd = par.length();
2916 if ((firstKey._dataStart < firstKey._dataEnd) &&
2917 (par[firstKey._dataStart] != '}')) {
2918 li.setForDefaultLang(firstKey);
2919 (void) li.process(os, firstKey);
2923 // return string definitelly impossible to match
2924 s = "\\foreignlanguage{ignore}{ }";
2928 s = par; /* no known macros found */
2929 // LYXERR(Debug::INFO, "After split: " << s);
2934 * Try to unify the language specs in the latexified text.
2935 * Resulting modified string is set to "", if
2936 * the searched tex does not contain all the features in the search pattern
2938 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
2940 static Features regex_f;
2941 static int missed = 0;
2942 static bool regex_with_format = false;
2944 int parlen = par.length();
2946 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2949 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2950 // Happens to be there in case of description or labeling environment
2955 // Split the latex input into pieces which
2956 // can be digested by our search engine
2957 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2958 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
2959 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
2960 string doclang = pbuf->params().language->polyglossia();
2961 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
2963 bool toIgnoreLang = true;
2964 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
2966 if (sub.str(2) != doclang) {
2967 toIgnoreLang = false;
2971 setIgnoreFormat("language", toIgnoreLang, false);
2974 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2975 LYXERR(Debug::FIND, "After splitOnKnownMacros:\n\"" << result << "\"");
2978 result = par.substr(0, parlen);
2979 if (isPatternString) {
2982 regex_f = identifyFeatures(result);
2983 string features = "";
2984 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2985 string a = it->first;
2986 regex_with_format = true;
2987 features += " " + a;
2988 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2990 LYXERR(Debug::FIND, "Identified Features" << features);
2993 } else if (regex_with_format) {
2994 Features info = identifyFeatures(result);
2995 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2996 string a = it->first;
2997 bool b = it->second;
2998 if (b && ! info[a]) {
3000 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3007 // LYXERR(Debug::INFO, "No regex formats");
3013 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3014 static int identifyClosing(string & t)
3016 int open_braces = 0;
3018 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
3019 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3021 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3023 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
3025 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
3034 static int num_replaced = 0;
3035 static bool previous_single_replace = true;
3037 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3040 // Handle \w properly
3041 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3042 if (! opt.casesensitive) {
3043 popts |= QRegularExpression::CaseInsensitiveOption;
3045 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3046 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3048 if (regexp.isValid() && regexp2.isValid()) {
3049 regexIsValid = true;
3050 // Check '{', '}' pairs inside the regex
3053 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3054 char c = par_as_string[i];
3061 else if (c == '}') {
3068 if (balanced != 0) {
3069 regexIsValid = false;
3070 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3074 regexIsValid = false;
3075 if (!regexp.isValid())
3076 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3078 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3081 if (opt.casesensitive) {
3082 regexp = regex(regexp_str);
3083 regexp2 = regex(regexp2_str);
3086 regexp = regex(regexp_str, std::regex_constants::icase);
3087 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3092 static void modifyRegexForMatchWord(string &t)
3095 regex wordre("(\\\\)*((\\.|\\\\b))");
3098 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3100 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3103 else if (sub.str(2) == "\\\\b")
3105 if (lastpos < (size_t) sub.position(2))
3106 s += t.substr(lastpos, sub.position(2) - lastpos);
3108 lastpos = sub.position(2) + sub.length(2);
3111 s = "\\b" + t + "\\b";
3115 else if (lastpos < t.length())
3116 s += t.substr(lastpos, t.length() - lastpos);
3117 t = "\\b" + s + "\\b";
3120 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3121 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3123 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3124 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3125 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
3126 if (opt.replace_all && previous_single_replace) {
3127 previous_single_replace = false;
3130 else if (!opt.replace_all) {
3131 num_replaced = 0; // count number of replaced strings
3132 previous_single_replace = true;
3134 // When using regexp, braces are hacked already by escape_for_regex()
3135 par_as_string = normalize(ds);
3137 close_wildcards = 0;
3139 size_t lead_size = 0;
3140 // correct the language settings
3141 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3142 opt.matchAtStart = false;
3144 identifyClosing(par_as_string); // Removes math closings ($, ], ...) at end of string
3145 if (opt.ignoreformat) {
3149 lead_size = identifyLeading(par_as_string);
3151 lead_as_string = par_as_string.substr(0, lead_size);
3152 string lead_as_regex_string = string2regex(lead_as_string);
3153 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3154 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3155 /* Handle whole words too in this case
3157 if (opt.matchword) {
3158 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3159 opt.matchword = false;
3161 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3162 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3163 CreateRegexp(opt, regexp_str, regexp2_str);
3165 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3166 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3170 if (!opt.ignoreformat) {
3171 lead_size = identifyLeading(par_as_string);
3172 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
3173 lead_as_string = par_as_string.substr(0, lead_size);
3174 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3177 // Here we are using regexp
3178 LASSERT(use_regexp, /**/);
3180 string lead_as_regexp;
3181 if (lead_size > 0) {
3182 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3183 regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3184 par_as_string = par_as_string_nolead;
3185 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
3186 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3188 // LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3189 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3190 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3191 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3193 size_t lng = par_as_string.size();
3194 if (!opt.ignoreformat) {
3195 // Remove extra '\}' at end if not part of \{\.\}
3197 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3199 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3208 if (lng < par_as_string.size())
3209 par_as_string = par_as_string.substr(0,lng);
3211 LYXERR(Debug::FIND, "par_as_string after correctRegex is '" << par_as_string << "'");
3212 if ((lng > 0) && (par_as_string[0] == '^')) {
3213 par_as_string = par_as_string.substr(1);
3215 opt.matchAtStart = true;
3217 // LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3218 // LYXERR(Debug::FIND, "Open braces: " << open_braces);
3219 // LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3221 // If entered regexp must match at begin of searched string buffer
3222 // Kornel: Added parentheses to use $1 for size of the leading string
3226 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3227 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3228 // so the convert has no effect in that case
3229 for (int i = 7; i > 0; --i) {
3230 string orig = "\\\\" + std::to_string(i);
3231 string dest = "\\" + std::to_string(i+2);
3232 while (regex_replace(par_as_string, par_as_string, orig, dest));
3234 if (opt.matchword) {
3235 modifyRegexForMatchWord(par_as_string);
3236 opt.matchword = false;
3238 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3239 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3241 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3242 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3243 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3247 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3251 mres.searched_size = len;
3253 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3256 docstring docstr = stringifyFromForSearch(opt, cur, len);
3258 str = normalize(docstr);
3259 if (!opt.ignoreformat) {
3260 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3261 // remove closing '}' and '\n' to allow for use of '$' in regex
3262 size_t lng = str.size();
3263 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3265 if (lng != str.size()) {
3266 str = str.substr(0, lng);
3270 mres.match_len = -1;
3273 LYXERR(Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3275 LASSERT(use_regexp, /**/);
3277 // use_regexp always true
3278 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3280 QString qstr = QString::fromStdString(str);
3281 QRegularExpression const *p_regexp;
3282 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3286 p_regexp = ®exp2;
3288 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3289 if (!match.hasMatch())
3292 regex const *p_regexp;
3293 regex_constants::match_flag_type flags;
3295 flags = regex_constants::match_continuous;
3298 flags = regex_constants::match_default;
3299 p_regexp = ®exp2;
3301 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3302 if (re_it == sregex_iterator())
3304 match_results<string::const_iterator> const & m = *re_it;
3306 // Whole found string, including the leading
3307 // std: m[0].second - m[0].first
3308 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3310 // Size of the leading string
3311 // std: m[1].second - m[1].first
3312 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3313 int leadingsize = 0;
3315 if (match.lastCapturedIndex() > 0) {
3316 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3321 leadingsize = m[1].second - m[1].first;
3325 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3326 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3327 // because of different number of closing at end of string
3328 // we have to 'unify' the length of the post-match.
3329 // Done by ignoring closing parenthesis and linefeeds at string end
3330 int matchend = match.capturedEnd(0);
3331 size_t strsize = qstr.size();
3332 if (!opt.ignoreformat) {
3333 while (mres.match_len > 0) {
3334 QChar c = qstr.at(matchend - 1);
3335 if ((c == '\n') || (c == '}') || (c == '{')) {
3342 while (strsize > (size_t) match.capturedEnd(0)) {
3343 QChar c = qstr.at(strsize-1);
3344 if ((c == '\n') || (c == '}')) {
3351 // LYXERR0(qstr.toStdString());
3352 mres.match2end = strsize - matchend;
3353 mres.pos = match.capturedStart(2);
3355 mres.match_prefix = m[2].second - m[2].first;
3356 mres.match_len = m[0].second - m[2].second;
3357 // ignore closing parenthesis and linefeeds at string end
3358 size_t strend = m[0].second - m[0].first;
3359 int matchend = strend;
3360 size_t strsize = str.size();
3361 if (!opt.ignoreformat) {
3362 while (mres.match_len > 0) {
3363 char c = str.at(matchend - 1);
3364 if ((c == '\n') || (c == '}') || (c == '{')) {
3371 while (strsize > strend) {
3372 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3380 mres.match2end = strsize - matchend;
3381 mres.pos = m[2].first - m[0].first;;
3383 if (mres.match2end < 0)
3385 mres.leadsize = leadingsize;
3387 if (mres.match_len > 0) {
3388 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3389 mres.result.push_back(a0);
3390 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3391 mres.result.push_back(match.captured(i).toStdString());
3395 if (mres.match_len > 0) {
3396 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3397 mres.result.push_back(a0);
3398 for (size_t i = 3; i < m.size(); i++) {
3399 mres.result.push_back(m[i]);
3408 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3410 MatchResult mres = findAux(cur, len, at_begin);
3411 int res = mres.match_len;
3413 "res=" << res << ", at_begin=" << at_begin
3414 << ", matchAtStart=" << opt.matchAtStart
3415 << ", inTexted=" << cur.inTexted());
3416 if (opt.matchAtStart) {
3419 else if (mres.match_prefix > 0)
3428 static bool simple_replace(string &t, string from, string to)
3430 regex repl("(\\\\)*(" + from + ")");
3434 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3436 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3438 if (lastpos < (size_t) sub.position(2))
3439 s += t.substr(lastpos, sub.position(2) - lastpos);
3441 lastpos = sub.position(2) + sub.length(2);
3445 else if (lastpos < t.length())
3446 s += t.substr(lastpos, t.length() - lastpos);
3452 string MatchStringAdv::normalize(docstring const & s) const
3455 t = lyx::to_utf8(s);
3456 // Remove \n at begin
3457 while (!t.empty() && t[0] == '\n')
3460 while (!t.empty() && t[t.size() - 1] == '\n')
3461 t = t.substr(0, t.size() - 1);
3463 // Handle all other '\n'
3464 while ((pos = t.find("\n")) != string::npos) {
3465 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3467 if (isAlnumASCII(t[pos+1])) {
3468 t.replace(pos-2, 3, " ");
3471 t.replace(pos-2, 3, "");
3474 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3475 // '\n' adjacent to non-alpha-numerics, discard
3476 t.replace(pos, 1, "");
3479 // Replace all other \n with spaces
3480 t.replace(pos, 1, " ");
3483 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3484 // Kornel: Added textsl, textsf, textit, texttt and noun
3485 // + allow to seach for colored text too
3486 LYXERR(Debug::FIND, "Removing stale empty macros from: " << t);
3487 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3488 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3489 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3490 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3491 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3497 docstring stringifyFromCursor(DocIterator const & cur, int len)
3499 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3500 if (cur.inTexted()) {
3501 Paragraph const & par = cur.paragraph();
3502 // TODO what about searching beyond/across paragraph breaks ?
3503 // TODO Try adding a AS_STR_INSERTS as last arg
3504 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3505 int(par.size()) : cur.pos() + len;
3506 // OutputParams runparams(&cur.buffer()->params().encoding());
3507 OutputParams runparams(encodings.fromLyXName("utf8"));
3508 runparams.nice = true;
3509 runparams.flavor = Flavor::XeTeX;
3510 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3511 // No side effect of file copying and image conversion
3512 runparams.dryrun = true;
3513 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
3514 if (ignoreFormats.getDeleted()) {
3515 option |= AS_STR_SKIPDELETE;
3516 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3519 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3521 LYXERR(Debug::FIND, "Stringifying with cur: "
3522 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3523 return par.asString(cur.pos(), end,
3526 } else if (cur.inMathed()) {
3527 CursorSlice cs = cur.top();
3528 MathData md = cs.cell();
3529 MathData::const_iterator it_end =
3530 (( len == -1 || cs.pos() + len > int(md.size()))
3532 : md.begin() + cs.pos() + len );
3534 for (MathData::const_iterator it = md.begin() + cs.pos();
3537 docstring s = asString(md2);
3538 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3541 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3546 /** Computes the LaTeX export of buf starting from cur and ending len positions
3547 * after cur, if len is positive, or at the paragraph or innermost inset end
3550 docstring latexifyFromCursor(DocIterator const & cur, int len)
3553 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3554 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3555 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3557 Buffer const & buf = *cur.buffer();
3559 odocstringstream ods;
3561 //OutputParams runparams(&buf.params().encoding());
3562 OutputParams runparams(encodings.fromLyXName("utf8"));
3563 runparams.nice = false;
3564 runparams.flavor = Flavor::XeTeX;
3565 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3566 // No side effect of file copying and image conversion
3567 runparams.dryrun = true;
3568 if (ignoreFormats.getDeleted()) {
3569 runparams.for_searchAdv = OutputParams::SearchWithoutDeleted;
3572 runparams.for_searchAdv = OutputParams::SearchWithDeleted;
3575 if (cur.inTexted()) {
3576 // @TODO what about searching beyond/across paragraph breaks ?
3577 pos_type endpos = cur.paragraph().size();
3578 if (len != -1 && endpos > cur.pos() + len)
3579 endpos = cur.pos() + len;
3580 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3581 string(), cur.pos(), endpos);
3582 string s = lyx::to_utf8(ods.str());
3583 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3584 return(lyx::from_utf8(s));
3585 } else if (cur.inMathed()) {
3586 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3587 for (int s = cur.depth() - 1; s >= 0; --s) {
3588 CursorSlice const & cs = cur[s];
3589 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3590 TeXMathStream ws(os);
3591 cs.asInsetMath()->asHullInset()->header_write(ws);
3596 CursorSlice const & cs = cur.top();
3597 MathData md = cs.cell();
3598 MathData::const_iterator it_end =
3599 ((len == -1 || cs.pos() + len > int(md.size()))
3601 : md.begin() + cs.pos() + len);
3603 for (MathData::const_iterator it = md.begin() + cs.pos();
3607 ods << asString(md2);
3608 // Retrieve the math environment type, and add '$' or '$]'
3609 // or others (\end{equation}) accordingly
3610 for (int s = cur.depth() - 1; s >= 0; --s) {
3611 CursorSlice const & cs2 = cur[s];
3612 InsetMath * inset = cs2.asInsetMath();
3613 if (inset && inset->asHullInset()) {
3614 TeXMathStream ws(os);
3615 inset->asHullInset()->footer_write(ws);
3619 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3621 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3626 #if defined(ResultsDebug)
3628 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
3630 LYXERR0( "from:\t\t\t" << from);
3632 if (mres.pos_len > 0) {
3634 status = "FINALSEARCH";
3637 if (mres.match_len > 0) {
3638 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
3639 status = "Good Match";
3641 status = "Matched in";
3644 status = "MissedSearch";
3647 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
3648 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
3649 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
3650 if ((mres.pos > 0) || (mres.match_prefix > 0))
3651 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
3652 for (size_t i = 0; i < mres.result.size(); i++)
3653 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3655 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
3657 #define displayMres(s, txt, cur)
3660 /** Finalize an advanced find operation, advancing the cursor to the innermost
3661 ** position that matches, plus computing the length of the matching text to
3663 ** Return the cur.pos() difference between start and end of found match
3665 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3667 // Search the foremost position that matches (avoids find of entire math
3668 // inset when match at start of it)
3669 DocIterator old_cur(cur.buffer());
3671 static MatchResult fail = MatchResult();
3672 MatchResult max_match;
3673 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3674 // Happens with e.g. hyperlinks
3675 // either one sees "http://www.bla.bla" or nothing
3676 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3677 // and although we search for only 3 chars, we find the whole hyperlink inset
3678 bool at_begin = (expected.match_prefix == 0);
3679 if (!match.opt.forward && match.opt.ignoreformat) {
3680 if (expected.pos > 0)
3683 LASSERT(at_begin, /**/);
3684 if (expected.match_len > 0 && at_begin) {
3685 // Search for deepest match
3687 max_match = expected;
3689 size_t d = cur.depth();
3693 if (cur.depth() < d)
3695 if (cur.depth() == d)
3698 while (cur && cur.depth() > lastd) {
3699 lastd = cur.depth();
3700 mres = match(cur, -1, at_begin);
3701 displayMres(mres, "Checking innermost", cur);
3702 if (mres.match_len > 0)
3707 if (mres.match_len < expected.match_len)
3715 // (expected.match_len <= 0)
3716 mres = match(cur); /* match valid only if not searching whole words */
3717 displayMres(mres, "Start with negative match", cur);
3720 if (max_match.match_len <= 0) return fail;
3721 LYXERR(Debug::FIND, "Ok");
3723 // Compute the match length
3725 if (cur.pos() + len > cur.lastpos())
3728 LASSERT(match.use_regexp, /**/);
3731 int maxl = cur.lastpos() - cur.pos();
3732 // Greedy behaviour while matching regexps
3733 while (maxl > minl) {
3735 mres2 = match(cur, len, at_begin);
3736 displayMres(mres2, "Finalize loop", cur);
3737 int actual_match_len = mres2.match_len;
3738 if (actual_match_len >= max_match.match_len) {
3739 // actual_match_len > max_match _can_ happen,
3740 // if the search area splits
3741 // some following word so that the regex
3742 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3744 // This means, the len value is too big
3745 actual_match_len = max_match.match_len;
3747 max_match.match_len = actual_match_len;
3749 if (maxl - minl < 4)
3750 len = (int)((maxl + minl)/2);
3752 len = (int)(minl + (maxl - minl + 3)/4);
3755 // (actual_match_len < max_match.match_len)
3757 len = (int)((maxl + minl)/2);
3762 // Search for real start of matched characters
3764 MatchResult actual_match;
3767 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3768 if (cur.depth() < old_cur.depth()) {
3770 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3773 if (cur.pos() != old_cur.pos()) {
3774 // OK, forwarded 1 pos in actual inset
3775 actual_match = match(cur, len-1, at_begin);
3776 if (actual_match.match_len == max_match.match_len) {
3777 // Ha, got it! The shorter selection has the same match length
3780 max_match = actual_match;
3783 // OK, the shorter selection matches less chars, revert to previous value
3789 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3790 actual_match = match(cur, len, at_begin);
3791 if (actual_match.match_len == max_match.match_len) {
3793 max_match = actual_match;
3800 max_match.pos_len = len;
3801 displayMres(max_match, "SEARCH RESULT", cur)
3808 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3812 bool repeat = false;
3813 DocIterator orig_cur; // to be used if repeat not successful
3814 MatchResult orig_mres;
3815 while (!theApp()->longOperationCancelled() && cur) {
3816 //(void) findAdvForwardInnermost(cur);
3817 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3818 MatchResult mres = match(cur, -1, false);
3819 string msg = "Starting";
3822 displayMres(mres, msg + " findForwardAdv", cur)
3823 int match_len = mres.match_len;
3824 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3825 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3828 if (match_len <= 0) {
3829 // This should exit nested insets, if any, or otherwise undefine the currsor.
3830 cur.pos() = cur.lastpos();
3831 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3834 else { // match_len > 0
3835 // Try to find the begin of searched string
3837 int firstInvalid = cur.lastpos() - cur.pos();
3839 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3840 int incrcur = (firstInvalid + 1 )*3/4;
3841 if (incrcur < incrmatch)
3842 increment = incrcur;
3844 increment = incrmatch;
3848 LYXERR(Debug::FIND, "Set increment to " << increment);
3849 while (increment > 0) {
3850 DocIterator old_cur = cur;
3851 if (cur.pos() + increment >= cur.lastpos()) {
3855 cur.pos() = cur.pos() + increment;
3856 MatchResult mres2 = match(cur, -1, false);
3857 displayMres(mres2, "findForwardAdv loop", cur)
3858 switch (interpretMatch(mres, mres2)) {
3859 case MatchResult::newIsTooFar:
3860 // behind the expected match
3861 firstInvalid = increment;
3865 case MatchResult::newIsBetter:
3866 // not reached yet, but cur.pos()+increment is bettert
3868 firstInvalid -= increment;
3869 if (increment > firstInvalid*3/4)
3870 increment = firstInvalid*3/4;
3871 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3872 if (increment >= mres2.match_prefix)
3873 increment = (mres2.match_prefix+1)*3/4;
3878 // Handle not like MatchResult::newIsTooFar
3879 LYXERR0( "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3881 increment = increment*3/4;
3886 if (mres.match_len > 0) {
3887 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
3888 // The match seems to indicate some deeper level
3897 // should never be reached.
3901 // LYXERR0("Leaving first loop");
3902 LYXERR(Debug::FIND, "Finalizing 1");
3903 MatchResult found_match = findAdvFinalize(cur, match, mres);
3904 if (found_match.match_len > 0) {
3905 LASSERT(found_match.pos_len > 0, /**/);
3906 match.FillResults(found_match);
3907 return found_match.pos_len;
3910 // try next possible match
3921 /// Find the most backward consecutive match within same paragraph while searching backwards.
3922 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
3924 DocIterator cur_begin = cur;
3925 cur_begin.pos() = 0;
3926 DocIterator tmp_cur = cur;
3927 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
3928 Inset & inset = cur.inset();
3929 for (; cur != cur_begin; cur.backwardPos()) {
3930 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3931 DocIterator new_cur = cur;
3932 new_cur.backwardPos();
3933 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3935 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
3936 if (new_mr.match_len == mr.match_len)
3940 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3946 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3950 // Backup of original position
3951 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3952 if (cur == cur_begin)
3955 DocIterator cur_orig(cur);
3956 bool pit_changed = false;
3959 MatchResult found_match = match(cur, -1, false);
3961 if (found_match.match_len > 0) {
3963 cur.pos() = cur.lastpos();
3965 cur.pos() = cur_orig.pos();
3966 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3967 DocIterator cur_prev_iter;
3969 found_match = match(cur);
3970 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3971 << (found_match.match_len > 0) << ", cur: " << cur);
3972 if (found_match.match_len > 0) {
3973 MatchResult found_mr = findMostBackwards(cur, match, found_match);
3974 if (found_mr.pos_len > 0) {
3975 match.FillResults(found_mr);
3976 return found_mr.pos_len;
3980 // Stop if begin of document reached
3981 if (cur == cur_begin)
3983 cur_prev_iter = cur;
3987 if (cur == cur_begin)
3994 } while (!theApp()->longOperationCancelled());
4002 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4003 DocIterator const & cur, int len)
4005 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4007 if (!opt.ignoreformat)
4008 return latexifyFromCursor(cur, len);
4010 return stringifyFromCursor(cur, len);
4014 FindAndReplaceOptions::FindAndReplaceOptions(
4015 docstring const & _find_buf_name, bool _casesensitive,
4016 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4017 docstring const & _repl_buf_name, bool _keep_case,
4018 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4019 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4020 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4021 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4029 /** Check if 'len' letters following cursor are all non-lowercase */
4030 static bool allNonLowercase(Cursor const & cur, int len)
4032 pos_type beg_pos = cur.selectionBegin().pos();
4033 pos_type end_pos = cur.selectionBegin().pos() + len;
4034 if (len > cur.lastpos() + 1 - beg_pos) {
4035 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4036 len = cur.lastpos() + 1 - beg_pos;
4037 end_pos = beg_pos + len;
4039 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4040 if (isLowerCase(cur.paragraph().getChar(pos)))
4046 /** Check if first letter is upper case and second one is lower case */
4047 static bool firstUppercase(Cursor const & cur)
4050 pos_type pos = cur.selectionBegin().pos();
4051 if (pos >= cur.lastpos() - 1) {
4052 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4055 ch1 = cur.paragraph().getChar(pos);
4056 ch2 = cur.paragraph().getChar(pos + 1);
4057 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4058 LYXERR(Debug::FIND, "firstUppercase(): "
4059 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4060 << ch2 << "(" << char(ch2) << ")"
4061 << ", result=" << result << ", cur=" << cur);
4066 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4068 ** \fixme What to do with possible further paragraphs in replace buffer ?
4070 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4072 ParagraphList::iterator pit = buffer.paragraphs().begin();
4073 LASSERT(!pit->empty(), /**/);
4074 pos_type right = pos_type(1);
4075 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4076 right = pit->size();
4077 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4081 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4083 // Should replace the string "$" + std::to_string(matchnum) with replacement
4084 // if the char '$' is not prefixed with odd number of char '\\'
4085 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4089 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4091 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4093 int num = stoi(sub.str(3), nullptr, 10);
4094 if (num >= maxmatchnum)
4096 if (lastpos < (size_t) sub.position(2))
4097 s += t.substr(lastpos, sub.position(2) - lastpos);
4098 s += replacements[num];
4099 lastpos = sub.position(2) + sub.length(2);
4103 else if (lastpos < t.length())
4104 s += t.substr(lastpos, t.length() - lastpos);
4110 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4112 Cursor & cur = bv->cursor();
4113 if (opt.repl_buf_name.empty()
4114 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4115 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4118 DocIterator sel_beg = cur.selectionBegin();
4119 DocIterator sel_end = cur.selectionEnd();
4120 if (&sel_beg.inset() != &sel_end.inset()
4121 || sel_beg.pit() != sel_end.pit()
4122 || sel_beg.idx() != sel_end.idx())
4124 int sel_len = sel_end.pos() - sel_beg.pos();
4125 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4126 << ", sel_len: " << sel_len << endl);
4129 LASSERT(sel_len > 0, return 0);
4131 if (!matchAdv(sel_beg, sel_len).match_len)
4134 // Build a copy of the replace buffer, adapted to the KeepCase option
4135 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4137 repl_buffer_orig.write(oss);
4138 string lyx = oss.str();
4139 if (matchAdv.valid_matches > 0) {
4140 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4142 Buffer repl_buffer("", false);
4143 repl_buffer.setUnnamed(true);
4144 LASSERT(repl_buffer.readString(lyx), return 0);
4145 if (opt.keep_case && sel_len >= 2) {
4146 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4147 if (cur.inTexted()) {
4148 if (firstUppercase(cur))
4149 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4150 else if (allNonLowercase(cur, sel_len))
4151 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4154 cap::cutSelection(cur, false);
4155 if (cur.inTexted()) {
4156 repl_buffer.changeLanguage(
4157 repl_buffer.language(),
4158 cur.getFont().language());
4159 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4160 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4161 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4162 repl_buffer.params().documentClassPtr(),
4163 repl_buffer.params().authors(),
4164 bv->buffer().errorList("Paste"));
4165 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4166 sel_len = repl_buffer.paragraphs().begin()->size();
4167 } else if (cur.inMathed()) {
4168 odocstringstream ods;
4170 // OutputParams runparams(&repl_buffer.params().encoding());
4171 OutputParams runparams(encodings.fromLyXName("utf8"));
4172 runparams.nice = false;
4173 runparams.flavor = Flavor::XeTeX;
4174 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4175 runparams.dryrun = true;
4176 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4177 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4178 docstring repl_latex = ods.str();
4179 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4181 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4182 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4183 repl_latex = from_utf8(s);
4184 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4185 MathData ar(cur.buffer());
4186 asArray(repl_latex, ar, Parse::NORMAL);
4188 sel_len = ar.size();
4189 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4191 if (cur.pos() >= sel_len)
4192 cur.pos() -= sel_len;
4195 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4196 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4197 bv->processUpdateFlags(Update::Force);
4202 /// Perform a FindAdv operation.
4203 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4208 // e.g., when invoking word-findadv from mini-buffer wither with
4209 // wrong options syntax or before ever opening advanced F&R pane
4210 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4214 MatchStringAdv matchAdv(bv->buffer(), opt);
4216 if (!matchAdv.regexIsValid) {
4217 bv->message(lyx::from_utf8(matchAdv.regexError));
4221 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4223 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4224 num_replaced += findAdvReplace(bv, opt, matchAdv);
4227 pos_len = findForwardAdv(cur, matchAdv);
4229 pos_len = findBackwardsAdv(cur, matchAdv);
4230 } catch (exception & ex) {
4231 bv->message(from_utf8(ex.what()));
4236 if (num_replaced > 0) {
4237 switch (num_replaced)
4240 bv->message(_("One match has been replaced."));
4243 bv->message(_("Two matches have been replaced."));
4246 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4252 bv->message(_("Match not found."));
4257 if (num_replaced > 0)
4258 bv->message(_("Match has been replaced."));
4260 bv->message(_("Match found."));
4262 if (cur.pos() + pos_len > cur.lastpos()) {
4263 // Prevent crash in bv->putSelectionAt()
4264 // Should never happen, maybe LASSERT() here?
4265 pos_len = cur.lastpos() - cur.pos();
4267 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4268 bv->putSelectionAt(cur, pos_len, !opt.forward);
4274 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4276 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4277 << opt.casesensitive << ' '
4278 << opt.matchword << ' '
4279 << opt.forward << ' '
4280 << opt.expandmacros << ' '
4281 << opt.ignoreformat << ' '
4282 << opt.replace_all << ' '
4283 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4284 << opt.keep_case << ' '
4285 << int(opt.scope) << ' '
4288 LYXERR(Debug::FIND, "built: " << os.str());
4294 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4296 // LYXERR(Debug::FIND, "parsing");
4300 while (line != "EOSS") {
4304 if (is.eof()) // Tolerate malformed request
4308 // LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4309 opt.find_buf_name = from_utf8(s);
4310 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4311 is.get(); // Waste space before replace string
4314 while (line != "EOSS") {
4318 if (is.eof()) // Tolerate malformed request
4322 // LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4323 opt.repl_buf_name = from_utf8(s);
4324 is >> opt.keep_case;
4327 opt.scope = FindAndReplaceOptions::SearchScope(i);
4329 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4332 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4333 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4334 << opt.scope << ' ' << opt.restr);