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.
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
27 #include "CutAndPaste.h"
28 #include "FuncRequest.h"
30 #include "output_latex.h"
31 #include "OutputParams.h"
32 #include "Paragraph.h"
37 #include "frontends/Application.h"
38 #include "frontends/alert.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
54 #include <unordered_map>
57 //#define ResultsDebug
58 #define USE_QT_FOR_SEARCH
59 #if defined(USE_QT_FOR_SEARCH)
60 #include <QRegularExpression>
67 using namespace lyx::support;
71 typedef unordered_map<string, string> AccentsMap;
72 typedef unordered_map<string,string>::const_iterator AccentsIterator;
73 static AccentsMap accents = unordered_map<string, string>();
75 // Helper class for deciding what should be ignored
79 IgnoreFormats() = default;
81 bool getFamily() const { return ignoreFamily_; }
83 bool getSeries() const { return ignoreSeries_; }
85 bool getShape() const { return ignoreShape_; }
87 bool getSize() const { return ignoreSize_; }
89 bool getUnderline() const { return ignoreUnderline_; }
91 bool getMarkUp() const { return ignoreMarkUp_; }
93 bool getStrikeOut() const { return ignoreStrikeOut_; }
95 bool getSectioning() const { return ignoreSectioning_; }
97 bool getFrontMatter() const { return ignoreFrontMatter_; }
99 bool getColor() const { return ignoreColor_; }
101 bool getLanguage() const { return ignoreLanguage_; }
103 bool getDeleted() const { return ignoreDeleted_; }
105 void setIgnoreDeleted(bool value);
107 bool getNonContent() const { return searchNonContent_; }
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 ignoreSize_ = true;
121 bool ignoreUnderline_ = false;
123 bool ignoreMarkUp_ = false;
125 bool ignoreStrikeOut_ = false;
127 bool ignoreSectioning_ = false;
129 bool ignoreFrontMatter_ = false;
131 bool ignoreColor_ = false;
133 bool ignoreLanguage_ = false;
134 bool userSelectedIgnoreLanguage_ = false;
136 bool ignoreDeleted_ = true;
138 bool searchNonContent_ = true;
141 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
143 if (type == "color") {
144 ignoreColor_ = value;
146 else if (type == "language") {
148 userSelectedIgnoreLanguage_ = value;
149 ignoreLanguage_ = value;
152 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
154 else if (type == "sectioning") {
155 ignoreSectioning_ = value;
156 ignoreFrontMatter_ = value;
158 else if (type == "font") {
159 ignoreSeries_ = value;
160 ignoreShape_ = value;
161 ignoreFamily_ = value;
163 else if (type == "series") {
164 ignoreSeries_ = value;
166 else if (type == "shape") {
167 ignoreShape_ = value;
169 else if (type == "size") {
172 else if (type == "family") {
173 ignoreFamily_ = value;
175 else if (type == "markup") {
176 ignoreMarkUp_ = value;
178 else if (type == "underline") {
179 ignoreUnderline_ = value;
181 else if (type == "strike") {
182 ignoreStrikeOut_ = value;
184 else if (type == "deleted") {
185 ignoreDeleted_ = value;
187 else if (type == "non-output-content") {
188 searchNonContent_ = !value;
192 // The global variable that can be changed from outside
193 IgnoreFormats ignoreFormats;
196 void setIgnoreFormat(string const & type, bool value, bool fromUser)
198 ignoreFormats.setIgnoreFormat(type, value, fromUser);
204 bool parse_bool(docstring & howto, bool const defvalue = false)
209 howto = split(howto, var, ' ');
217 MatchString(docstring const & s, bool cs, bool mw)
218 : str(s), case_sens(cs), whole_words(mw)
221 // returns true if the specified string is at the specified position
222 // del specifies whether deleted strings in ct mode will be considered
223 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
225 return par.find(str, case_sens, whole_words, pos, del);
233 // match whole words only
238 int findForward(DocIterator & cur, DocIterator const endcur,
239 MatchString const & match,
240 bool find_del = true, bool onlysel = false)
242 for (; cur; cur.forwardChar()) {
243 if (onlysel && endcur.pit() == cur.pit()
244 && endcur.idx() == cur.idx() && endcur.pos() < cur.pos())
246 if (cur.inTexted()) {
247 int len = match(cur.paragraph(), cur.pos(), find_del);
256 int findBackwards(DocIterator & cur, DocIterator const endcur,
257 MatchString const & match,
258 bool find_del = true, bool onlysel = false)
262 if (onlysel && endcur.pit() == cur.pit()
263 && endcur.idx() == cur.idx() && endcur.pos() > cur.pos())
265 if (cur.inTexted()) {
266 int len = match(cur.paragraph(), cur.pos(), find_del);
275 bool searchAllowed(docstring const & str)
278 frontend::Alert::error(_("Search error"), _("Search string is empty"));
287 bool findOne(BufferView * bv, docstring const & searchstr,
288 bool case_sens, bool whole, bool forward,
289 bool find_del, bool check_wrap, bool const auto_wrap,
290 bool instant, bool onlysel)
292 // Clean up previous selections with empty searchstr on instant
293 if (searchstr.empty() && instant) {
294 if (bv->cursor().selection()) {
295 bv->setCursor(bv->cursor().selectionBegin());
296 bv->clearSelection();
301 if (!searchAllowed(searchstr))
304 DocIterator const endcur = forward ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin();
306 if (onlysel && bv->cursor().selection()) {
307 docstring const matchstring = bv->cursor().selectionAsString(false);
308 docstring const lcmatchsting = support::lowercase(matchstring);
309 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
310 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
311 "Continue search outside?");
312 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
313 q, 0, 1, _("&Yes"), _("&No"));
314 if (search_answer == 0) {
315 bv->clearSelection();
316 if (findOne(bv, searchstr, case_sens, whole, forward,
317 find_del, check_wrap, auto_wrap, false, false))
324 DocIterator cur = forward
325 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
326 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
328 MatchString const match(searchstr, case_sens, whole);
330 int match_len = forward
331 ? findForward(cur, endcur, match, find_del, onlysel)
332 : findBackwards(cur, endcur, match, find_del, onlysel);
335 bv->putSelectionAt(cur, match_len, !forward);
336 else if (onlysel && bv->cursor().selection()) {
337 docstring q = _("The search string was not found within the selection.\n"
338 "Continue search outside?");
339 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
340 q, 0, 1, _("&Yes"), _("&No"));
341 if (search_answer == 0) {
342 bv->clearSelection();
343 if (findOne(bv, searchstr, case_sens, whole, forward,
344 find_del, check_wrap, auto_wrap, false, false))
349 else if (check_wrap) {
350 DocIterator cur_orig(bv->cursor());
351 bool wrap = auto_wrap;
355 q = _("End of file reached while searching forward.\n"
356 "Continue searching from the beginning?");
358 q = _("Beginning of file reached while searching backward.\n"
359 "Continue searching from the end?");
360 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
361 q, 0, 1, _("&Yes"), _("&No"));
362 wrap = wrap_answer == 0;
366 bv->cursor().clear();
367 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
369 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
370 bv->cursor().backwardPos();
373 docstring const msg = forward
374 ? _("Search reached end of document, continuing from beginning.")
375 : _("Search reached beginning of document, continuing from end.");
378 bv->clearSelection();
379 if (findOne(bv, searchstr, case_sens, whole, forward,
380 find_del, false, false, false, false))
383 bv->cursor().setCursor(cur_orig);
387 return match_len > 0;
393 int replaceAll(BufferView * bv,
394 docstring const & searchstr, docstring const & replacestr,
395 bool case_sens, bool whole, bool onlysel)
397 Buffer & buf = bv->buffer();
399 if (!searchAllowed(searchstr) || buf.isReadonly())
402 DocIterator startcur = bv->cursor().selectionBegin();
403 DocIterator endcur = bv->cursor().selectionEnd();
404 bool const had_selection = bv->cursor().selection();
406 MatchString const match(searchstr, case_sens, whole);
409 int const rsize = replacestr.size();
410 int const ssize = searchstr.size();
413 cur.setCursor(doc_iterator_begin(&buf));
414 int match_len = findForward(cur, endcur, match, false, onlysel);
415 while (match_len > 0) {
416 // Backup current cursor position and font.
417 pos_type const pos = cur.pos();
418 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
420 int ct_deleted_text = ssize -
421 cur.paragraph().eraseChars(pos, pos + match_len,
422 buf.params().track_changes);
423 cur.paragraph().insert(pos, replacestr, font,
424 Change(buf.params().track_changes
426 : Change::UNCHANGED));
427 for (int i = 0; i < rsize + ct_deleted_text
428 && cur.pos() < cur.lastpos(); ++i)
430 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
431 // Adjust end of selection for replace-all in selection
433 int const offset = rsize - ssize;
434 for (int i = 0; i < offset + ct_deleted_text
435 && endcur.pos() < endcur.lastpos(); ++i)
438 int const offset = ssize - rsize;
439 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
440 endcur.backwardPos();
441 for (int i = 0; i < ct_deleted_text
442 && endcur.pos() < endcur.lastpos(); ++i)
447 match_len = findForward(cur, endcur, match, false, onlysel);
450 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
452 startcur.fixIfBroken();
453 bv->setCursor(startcur);
455 // Reset selection, accounting for changes in selection
457 endcur.fixIfBroken();
458 bv->cursor().resetAnchor();
459 bv->setCursorSelectionTo(endcur);
466 // the idea here is that we are going to replace the string that
467 // is selected IF it is the search string.
468 // if there is a selection, but it is not the search string, then
469 // we basically ignore it. (FIXME We ought to replace only within
471 // if there is no selection, then:
472 // (i) if some search string has been provided, then we find it.
473 // (think of how the dialog works when you hit "replace" the
475 // (ii) if no search string has been provided, then we treat the
476 // word the cursor is in as the search string. (why? i have no
477 // idea.) but this only works in text?
479 // returns the number of replacements made (one, if any) and
480 // whether anything at all was done.
481 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
482 docstring const & replacestr, bool case_sens,
483 bool whole, bool forward, bool findnext, bool wrap,
486 Cursor & cur = bv->cursor();
487 if (!cur.selection() || onlysel) {
488 // no selection, non-empty search string: find it
489 if (!searchstr.empty()) {
490 bool const found = findOne(bv, searchstr, case_sens, whole,
491 forward, true, findnext, wrap, false, onlysel);
492 return make_pair(found, 0);
494 // empty search string
497 return make_pair(false, 0);
498 // select current word and treat it as the search string.
499 // This causes a minor bug as undo will restore this selection,
500 // which the user did not create (#8986).
501 cur.innerText()->selectWord(cur, WHOLE_WORD);
502 searchstr = cur.selectionAsString(false, true);
505 // if we still don't have a search string, report the error
507 if (!searchAllowed(searchstr))
508 return make_pair(false, 0);
510 bool have_selection = cur.selection();
511 docstring const selected = cur.selectionAsString(false, true);
514 ? searchstr == selected
515 : compare_no_case(searchstr, selected) == 0;
517 // no selection or current selection is not search word:
518 // just find the search word
519 if (!have_selection || !match) {
520 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
521 true, findnext, wrap, false, onlysel);
522 return make_pair(found, 0);
525 // we're now actually ready to replace. if the buffer is
526 // read-only, we can't, though.
527 if (bv->buffer().isReadonly())
528 return make_pair(false, 0);
530 cap::replaceSelectionWithString(cur, replacestr);
532 cur.pos() += replacestr.length();
533 LASSERT(cur.pos() <= cur.lastpos(),
534 cur.pos() = cur.lastpos());
537 findOne(bv, searchstr, case_sens, whole,
538 forward, false, findnext, wrap, false, onlysel);
540 return make_pair(true, 1);
546 docstring const find2string(docstring const & search,
547 bool casesensitive, bool matchword,
548 bool forward, bool wrap, bool instant,
553 << int(casesensitive) << ' '
554 << int(matchword) << ' '
555 << int(forward) << ' '
557 << int(instant) << ' '
563 docstring const replace2string(docstring const & replace,
564 docstring const & search,
565 bool casesensitive, bool matchword,
566 bool all, bool forward, bool findnext,
567 bool wrap, bool onlysel)
570 ss << replace << '\n'
572 << int(casesensitive) << ' '
573 << int(matchword) << ' '
575 << int(forward) << ' '
576 << int(findnext) << ' '
583 docstring const string2find(docstring const & argument,
591 // data is of the form
593 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
595 docstring howto = split(argument, search, '\n');
597 casesensitive = parse_bool(howto);
598 matchword = parse_bool(howto);
599 forward = parse_bool(howto, true);
600 wrap = parse_bool(howto);
601 instant = parse_bool(howto);
602 onlysel = parse_bool(howto);
608 bool lyxfind(BufferView * bv, FuncRequest const & ev)
610 if (!bv || ev.action() != LFUN_WORD_FIND)
613 //lyxerr << "find called, cmd: " << ev << endl;
621 docstring search = string2find(ev.argument(), casesensitive,
622 matchword, forward, wrap, instant, onlysel);
624 return findOne(bv, search, casesensitive, matchword, forward,
625 false, true, wrap, instant, onlysel);
629 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
631 if (!bv || ev.action() != LFUN_WORD_REPLACE)
634 // data is of the form
637 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
640 docstring howto = split(ev.argument(), rplc, '\n');
641 howto = split(howto, search, '\n');
643 bool casesensitive = parse_bool(howto);
644 bool matchword = parse_bool(howto);
645 bool all = parse_bool(howto);
646 bool forward = parse_bool(howto, true);
647 bool findnext = parse_bool(howto, true);
648 bool wrap = parse_bool(howto);
649 bool onlysel = parse_bool(howto);
651 if (!bv->cursor().selection())
652 // only selection only makes sense with selection
657 int replace_count = 0;
659 replace_count = replaceAll(bv, search, rplc, casesensitive,
661 update = replace_count > 0;
664 replaceOne(bv, search, rplc, casesensitive, matchword,
665 forward, findnext, wrap, onlysel);
667 replace_count = rv.second;
670 Buffer const & buf = bv->buffer();
672 // emit message signal.
674 buf.message(_("String not found in selection."));
676 buf.message(_("String not found."));
678 if (replace_count == 0) {
679 buf.message(_("String found."));
680 } else if (replace_count == 1) {
681 buf.message(_("String has been replaced."));
683 docstring const str = onlysel
684 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
685 : bformat(_("%1$d strings have been replaced."), replace_count);
693 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
695 for (; cur; cur.forwardPos())
696 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
700 DocIterator cur_orig(bv->cursor());
701 docstring q = _("End of file reached while searching forward.\n"
702 "Continue searching from the beginning?");
703 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
704 q, 0, 1, _("&Yes"), _("&No"));
705 if (wrap_answer == 0) {
706 bv->cursor().clear();
707 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
708 bv->clearSelection();
709 cur.setCursor(bv->cursor().selectionBegin());
710 if (findNextChange(bv, cur, false))
713 bv->cursor().setCursor(cur_orig);
720 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
722 for (cur.backwardPos(); cur; cur.backwardPos()) {
723 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
728 DocIterator cur_orig(bv->cursor());
729 docstring q = _("Beginning of file reached while searching backward.\n"
730 "Continue searching from the end?");
731 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
732 q, 0, 1, _("&Yes"), _("&No"));
733 if (wrap_answer == 0) {
734 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
735 bv->cursor().backwardPos();
736 bv->clearSelection();
737 cur.setCursor(bv->cursor().selectionBegin());
738 if (findPreviousChange(bv, cur, false))
741 bv->cursor().setCursor(cur_orig);
748 bool selectChange(Cursor & cur, bool forward)
750 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
752 Change ch = cur.paragraph().lookupChange(cur.pos());
754 CursorSlice tip1 = cur.top();
755 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
756 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
757 if (!ch2.isSimilarTo(ch))
760 CursorSlice tip2 = cur.top();
761 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
763 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
764 if (!ch2.isSimilarTo(ch)) {
765 // take a step forward to correctly set the selection
773 cur.bv().mouseSetCursor(cur, false);
775 cur.bv().mouseSetCursor(cur, true);
783 bool findChange(BufferView * bv, bool forward)
786 cur.setCursor(forward ? bv->cursor().selectionEnd()
787 : bv->cursor().selectionBegin());
788 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
789 return selectChange(cur, forward);
794 bool findNextChange(BufferView * bv)
796 return findChange(bv, true);
800 bool findPreviousChange(BufferView * bv)
802 return findChange(bv, false);
809 typedef vector<pair<string, string> > Escapes;
811 static string getRegexSpaceCount(int count)
815 return "\\s{" + std::to_string(count) + "}";
822 string string2regex(string in)
824 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\$\\])" };
825 string tempx = std::regex_replace(in, specialChars, R"(\$&)" );
826 // Special handling for ' '
829 for (unsigned i = 0; i < tempx.size(); i++) {
830 if (tempx[i] == ' ' || tempx[i] == '~' ) {
834 else if ((tempx[i] == '\302' && tempx[i+1] == '\240')
835 || (tempx[i] == '\342' && tempx[i+1] == '\200')) {
843 temp += getRegexSpaceCount(blanks);
850 temp += getRegexSpaceCount(blanks);
857 while (fl_pos < temp.size()) {
858 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
859 if (fl_pos == string::npos)
862 temp2 += temp.substr(lastpos, fl_pos - lastpos);
868 if (lastpos < temp.size()) {
869 temp2 += temp.substr(lastpos, temp.size() - lastpos);
874 static void buildAccentsMap();
876 string correctRegex(string t, bool withformat)
878 /* Convert \backslash => \
879 * and \{, \}, \[, \] => {, }, [, ]
882 static std::regex wordre("(\\\\)*(\\\\(( |[A-Za-z]+|[\\{\\}%])( |\\{\\})?|[\\[\\]\\{\\}]))");
883 static std::regex protectedSpace { R"(~)" };
886 bool backslashed = false;
890 //LYXERR0("correctRegex input '" << t << "'");
892 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
895 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
899 if (sub.str(4) == "backslash") {
900 replace = string("\\");
902 // transforms '\backslash \{' into '\{'
903 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
904 if ((next == "\\{") || (next == "\\}") || (next == "\\ ")) {
908 else if (withformat && next[0] == '$') {
909 replace = accents["lyxdollar"];
910 skip = 1; // Skip following '$'
914 else if (sub.str(4) == "mathcircumflex")
916 else if (backslashed) {
919 if (sub.str(3) == "{")
920 replace = accents["braceleft"];
921 else if (sub.str(3) == "}")
922 replace = accents["braceright"];
923 else if (sub.str(3) == " ")
926 // else part should not exist
931 if (sub.str(3) == "{")
933 else if (sub.str(3) == "}")
935 else if (sub.str(3) == " ")
938 // else part should not exist
943 else if (sub.str(4) == "{") // transforms '\{' into '{'
945 else if (sub.str(4) == "}")
947 else if (sub.str(4) == "%")
949 else if (sub.str(4) == " ")
952 AccentsIterator it_ac = accents.find(sub.str(4));
953 if (it_ac == accents.end()) {
954 replace = sub.str(2);
957 replace = it_ac->second;
961 if (lastpos < (size_t) sub.position(2))
962 s += std::regex_replace(t.substr(lastpos, sub.position(2) - lastpos), protectedSpace, R"( )");
964 lastpos = sub.position(2) + sub.length(2) + skip;
968 s = std::regex_replace(t, protectedSpace, R"( )");
969 else if (lastpos < t.length())
970 s += std::regex_replace(t.substr(lastpos, t.length() - lastpos), protectedSpace, R"( )");
971 // Handle quotes in regex
972 // substitute all '„', '“', '»', '«' with '"'
973 // and all '‚', '‘', '›', '‹' with "\'"
974 static std::regex plainquotes { R"(„|“|»|«)" };
975 static std::regex innerquotes { R"(‚|‘|›|‹)" };
976 t = std::regex_replace(s, plainquotes, R"(")");
977 s = std::regex_replace(t, innerquotes, R"(')");
978 //LYXERR0("correctRegex output '" << s << "'");
982 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
983 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
984 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
985 string escape_for_regex(string s, bool withformat)
989 while (lastpos < s.size()) {
990 size_t regex_pos = s.find("\\regexp{", lastpos);
991 if (regex_pos == string::npos) {
992 regex_pos = s.size();
994 if (regex_pos > lastpos) {
995 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
997 if (lastpos == s.size())
1000 size_t end_pos = s.find("\\endregexp", regex_pos + 8);
1001 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
1002 lastpos = end_pos + 13;
1008 /// Wrapper for lyx::regex_replace with simpler interface
1009 bool regex_replace(string const & s, string & t, string const & searchstr,
1010 string const & replacestr)
1012 regex e(searchstr, regex_constants::ECMAScript);
1014 ostream_iterator<char, char> it(oss);
1015 regex_replace(it, s.begin(), s.end(), e, replacestr);
1016 // tolerate t and s be references to the same variable
1017 bool rv = (s != oss.str());
1036 vector <string> result = vector <string>();
1037 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {}
1040 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
1042 if (newres.match2end < oldres.match2end)
1043 return MatchResult::newIsTooFar;
1044 if (newres.match_len < oldres.match_len)
1045 return MatchResult::newIsTooFar;
1047 if (newres.match_len == oldres.match_len) {
1048 if (newres.match2end == oldres.match2end)
1049 return MatchResult::newIsBetter;
1051 return MatchResult::newIsInvalid;
1054 /** The class performing a match between a position in the document and the FindAdvOptions.
1057 class MatchStringAdv {
1059 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
1061 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
1062 ** constructor as opt.search, under the opt.* options settings.
1065 ** If set to MatchStringAdv::MatchFromStart,
1066 ** then match is searched only against beginning of text starting at cur.
1067 ** Otherwise the match is searched anywhere in text starting at cur.
1070 ** The length of the matching text, or zero if no match was found.
1076 string matchTypeAsString(matchType const x) const { return (x == MatchFromStart ? "MatchFromStart" : "MatchAnyPlace"); }
1077 MatchResult operator()(DocIterator const & cur, int len, matchType at_begin) const;
1085 lyx::Buffer * p_buf;
1086 /// first buffer on which search was started
1087 lyx::Buffer * const p_first_buf;
1089 FindAndReplaceOptions const & opt;
1092 /// Auxiliary find method (does not account for opt.matchword)
1093 MatchResult findAux(DocIterator const & cur, int len, matchType at_begin) const;
1094 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
1096 /** Normalize a stringified or latexified LyX paragraph.
1100 ** <li>if search is not casesensitive, then lowercase the string;
1101 ** <li>remove any newline at begin or end of the string;
1102 ** <li>replace any newline in the middle of the string with a simple space;
1103 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
1106 ** @todo Normalization should also expand macros, if the corresponding
1107 ** search option was checked.
1109 string convertLF2Space(docstring const & s, bool ignore_fomat) const;
1110 // normalized string to search
1111 string par_as_string;
1112 // regular expression to use for searching
1113 // regexp2 is same as regexp, but prefixed with a ".*?"
1115 QRegularExpression regexp;
1116 QRegularExpression regexp2;
1121 // leading format material as string
1122 string lead_as_string;
1123 // par_as_string after removal of lead_as_string
1124 string par_as_string_nolead;
1125 // unmatched open braces in the search string/regexp
1126 int open_braces = 0;
1127 // number of (.*?) subexpressions added at end of search regexp for closing
1128 // environments, math mode, styles, etc...
1129 int close_wildcards = 0;
1131 // Are we searching with regular expressions ?
1132 bool use_regexp = false;
1133 static int valid_matches;
1134 static vector <string> matches;
1135 void FillResults(MatchResult &found_mr);
1138 int MatchStringAdv::valid_matches = 0;
1139 vector <string> MatchStringAdv::matches = vector <string>(10);
1141 void MatchStringAdv::FillResults(MatchResult &found_mr)
1143 if (found_mr.match_len > 0) {
1144 valid_matches = found_mr.result.size();
1145 for (size_t i = 0; i < found_mr.result.size(); i++)
1146 matches[i] = found_mr.result[i];
1151 static void setFindParams(OutputParams &runparams)
1153 runparams.flavor = Flavor::XeTeX;
1154 //runparams.use_polyglossia = true;
1155 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1156 // No side effect of file copying and image conversion
1157 runparams.dryrun = true;
1160 static docstring buffer_to_latex(Buffer & buffer)
1162 //OutputParams runparams(&buffer.params().encoding());
1163 OutputParams runparams(encodings.fromLyXName("utf8"));
1164 odocstringstream ods;
1166 runparams.nice = true;
1167 setFindParams(runparams);
1168 if (ignoreFormats.getDeleted())
1169 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1171 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1172 if (ignoreFormats.getNonContent()) {
1173 runparams.find_add_feature(OutputParams::SearchNonOutput);
1175 pit_type const endpit = buffer.paragraphs().size();
1176 for (pit_type pit = 0; pit != endpit; ++pit) {
1177 TeXOnePar(buffer, buffer.text(), pit, os, runparams, string(), -1, -1, true);
1178 LYXERR(Debug::FINDVERBOSE, "searchString up to here: " << ods.str());
1183 static string latexNamesToUtf8(docstring strIn, bool withformat)
1185 string addtmp = to_utf8(strIn);
1186 static regex const rmAcc("(\\\\)*("
1187 "\\\\([A-Za-z]+\\{.\\})" // e.g. "ddot{A}" == sub.str(3)
1188 "|\\\\([A-Za-z]+)( |\\{\\})?" // e.g. "LyX", "LyX{}", "LyX " == sub.str(4)
1195 if (accents.empty())
1197 for (sregex_iterator it_add(addtmp.begin(), addtmp.end(), rmAcc), end; it_add != end; ++it_add) {
1199 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
1204 if (sub.length(3) > 0)
1208 AccentsIterator it_ac = accents.find(key);
1209 if (it_ac == accents.end()) {
1210 replace = sub.str(2);
1213 replace = it_ac->second;
1216 if (lastpos < (size_t) sub.position(2))
1217 add += addtmp.substr(lastpos, sub.position(2) - lastpos);
1219 lastpos = sub.position(2) + sub.length(2);
1223 else if (addtmp.length() > lastpos)
1224 add += addtmp.substr(lastpos, addtmp.length() - lastpos);
1226 static std::regex repltilde { R"(~)" };
1227 add = std::regex_replace(add, repltilde, accents["lyxtilde"]);
1229 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1234 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1237 if (!opt.ignoreformat) {
1238 str = buffer_to_latex(buffer);
1240 // OutputParams runparams(&buffer.params().encoding());
1241 OutputParams runparams(encodings.fromLyXName("utf8"));
1242 runparams.nice = true;
1243 setFindParams(runparams);
1244 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1245 if (ignoreFormats.getDeleted()) {
1246 option |= AS_STR_SKIPDELETE;
1247 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1250 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1252 if (ignoreFormats.getNonContent()) {
1253 runparams.find_add_feature(OutputParams::SearchNonOutput);
1256 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1257 Paragraph const & par = buffer.paragraphs().at(pit);
1258 string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1260 &runparams), !opt.ignoreformat);
1261 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1265 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1266 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1273 /// Return separation pos between the leading material and the rest
1274 static size_t identifyLeading(string const & s)
1277 // @TODO Support \item[text]
1278 // Kornel: Added textsl, textsf, textit, texttt and noun
1279 // + allow to search for colored text too
1280 while (regex_replace(t, t, "^\\\\(("
1281 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1282 "lyxaddress|lyxrightaddress|"
1283 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1284 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1285 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1286 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1287 || regex_replace(t, t, "^\\$", "")
1288 || regex_replace(t, t, "^\\\\\\[", "")
1289 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1290 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1292 LYXERR(Debug::FINDVERBOSE, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1293 return s.size() - t.size();
1297 * Given a latexified string, retrieve some handled features
1298 * The features of the regex will later be compared with the features
1299 * of the searched text. If the regex features are not a
1300 * subset of the analized, then, in not format ignoring search
1301 * we can early stop the search in the relevant inset.
1303 typedef map<string, bool> Features;
1305 static Features identifyFeatures(string const & s)
1307 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1308 static regex const valid("^("
1310 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1311 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1312 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1313 "(u|uu)line|(s|x)out|uwave|"
1314 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1315 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1320 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1323 if (sub.str(1).compare("regexp") == 0) {
1327 string token = sub.str(1);
1329 if (regex_match(token, sub2, valid)) {
1337 if (sub.str(1).compare("endregexp") == 0) {
1347 * defines values features of a key "\\[a-z]+{"
1352 /* Char type with content discarded
1353 * like \hspace{1cm} */
1355 /* Char, like \backslash */
1357 /* replace starting backslash with '#' */
1359 /* \part, \section*, ... */
1361 /* title, author etc */
1363 /* \foreignlanguage{ngerman}, ... */
1366 * to discard language in content */
1369 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1371 /* fonts, colors, markups, ... */
1373 /* footnotesize, ... large, ...
1374 * Ignore all of them */
1377 /* inputencoding, ...
1378 * Discard also content, because they do not help in search */
1381 * like remove, but also all arguments */
1383 /* item, listitem */
1385 /* tex, latex, ... like isChar */
1387 /* like \lettrine[lines=5]{}{} */
1389 // like isStandard, but always remove head
1391 /* End of arguments marker for lettrine,
1392 * so that they can be ignored */
1395 KeyInfo() = default;
1396 KeyInfo(KeyType type, int parcount, bool disable)
1398 parenthesiscount(parcount),
1399 disabled(disable) {}
1400 KeyType keytype = invalid;
1402 int _tokensize = -1;
1403 int _tokenstart = -1;
1404 int _dataStart = -1;
1406 int parenthesiscount = 1;
1407 bool disabled = false;
1408 bool used = false; /* by pattern */
1413 Border(int l=0, int u=0) : low(l), upper(u) {}
1418 #define MAXOPENED 30
1420 bool isPatternString_;
1422 explicit Intervall(bool isPattern, string const & p)
1423 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1424 actualdeptindex(0), hasTitle(false), langcount(0)
1432 static vector<Border> borders;
1433 static vector<int> depts;
1434 static vector<int> closes;
1435 int actualdeptindex;
1436 int previousNotIgnored(int) const;
1437 int nextNotIgnored(int) const;
1438 void handleOpenP(int i);
1439 void handleCloseP(int i, bool closingAllowed);
1440 void resetOpenedP(int openPos);
1441 void addIntervall(int upper);
1442 void addIntervall(int low, int upper); /* if explicit */
1443 void removeAccents();
1444 void setForDefaultLang(KeyInfo const & defLang) const;
1445 int findclosing(int start, int end, char up, char down, int repeat);
1446 void removeInvalidClosings(void);
1447 void handleParentheses(int lastpos, bool closingAllowed);
1449 // Number of disabled language specs up
1450 // to current position in actual interval
1452 int isOpeningPar(int pos) const;
1454 void output(ostringstream &os, int lastpos);
1455 // string show(int lastpos);
1458 vector<Border> Intervall::borders = vector<Border>(30);
1459 vector<int> Intervall::depts = vector<int>(30);
1460 vector<int> Intervall::closes = vector<int>(30);
1462 int Intervall::isOpeningPar(int pos) const
1464 if ((pos < 0) || (size_t(pos) >= par.size()))
1466 if (par[pos] != '{')
1468 if (size_t(pos) + 2 >= par.size())
1470 if (par[pos+2] != '}')
1472 if (par[pos+1] == '[' || par[pos+1] == ']')
1477 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1479 // Enable the use of first token again
1480 if (ignoreidx >= 0) {
1481 int value = defLang._tokenstart + defLang._tokensize;
1486 if (borders[borderidx].low < value)
1487 borders[borderidx].low = value;
1488 if (borders[borderidx].upper < value)
1489 borders[borderidx].upper = value;
1495 // Not needed, because dpts and closes are now dynamically expanded
1496 static void checkDepthIndex(int val)
1498 static int maxdepthidx = MAXOPENED-2;
1499 static int lastmaxdepth = 0;
1500 if (val > lastmaxdepth) {
1501 LYXERR(Debug::INFO, "Depth reached " << val);
1504 if (val > maxdepthidx) {
1506 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1512 // Not needed, because borders are now dynamically expanded
1513 static void checkIgnoreIdx(int val)
1515 static int lastmaxignore = -1;
1516 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1517 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1518 lastmaxignore = val;
1524 * Expand the region of ignored parts of the input latex string
1525 * The region is only relevant in output()
1527 void Intervall::addIntervall(int low, int upper)
1530 if (low == upper) return;
1531 for (idx = ignoreidx+1; idx > 0; --idx) {
1532 if (low > borders[idx-1].upper) {
1536 Border br(low, upper);
1537 if (idx > ignoreidx) {
1538 if (borders.size() <= size_t(idx)) {
1539 borders.push_back(br);
1545 // checkIgnoreIdx(ignoreidx);
1549 // Expand only if one of the new bound is inside the interwall
1550 // We know here that br.low > borders[idx-1].upper
1551 if (br.upper < borders[idx].low) {
1552 // We have to insert at this pos
1553 if (size_t(ignoreidx+1) >= borders.size()) {
1554 borders.push_back(borders[ignoreidx]);
1557 borders[ignoreidx+1] = borders[ignoreidx];
1559 for (int i = ignoreidx; i > idx; --i) {
1560 borders[i] = borders[i-1];
1564 // checkIgnoreIdx(ignoreidx);
1567 // Here we know, that we are overlapping
1568 if (br.low > borders[idx].low)
1569 br.low = borders[idx].low;
1570 // check what has to be concatenated
1572 for (int i = idx; i <= ignoreidx; i++) {
1573 if (br.upper >= borders[i].low) {
1575 if (br.upper < borders[i].upper)
1576 br.upper = borders[i].upper;
1582 // count should be >= 1 here
1585 for (int i = idx + count; i <= ignoreidx; i++) {
1586 borders[i-count+1] = borders[i];
1588 ignoreidx -= count - 1;
1594 static void buildaccent(string n, string param, string values)
1598 const char delim = '|';
1599 while (getline(s, name, delim)) {
1601 for (char c : param) {
1602 string key = name + "{" + c + "}";
1603 // get the corresponding utf8-value
1604 if ((values[start] & 0xc0) != 0xc0) {
1605 // should not happen, utf8 encoding starts at least with 11xxxxxx
1606 // but value for '\dot{i}' is 'i', which is ascii
1607 if ((values[start] & 0x80) == 0) {
1609 accents[key] = values.substr(start, 1);
1610 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1615 for (int j = 1; ;j++) {
1616 if (start + j >= values.size()) {
1617 accents[key] = values.substr(start, j);
1618 start = values.size() - 1;
1621 else if ((values[start+j] & 0xc0) != 0x80) {
1622 // This is the first byte of following utf8 char
1623 accents[key] = values.substr(start, j);
1625 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1634 static string getutf8(unsigned uchar)
1637 string ret = string();
1639 if (uchar <= 0x7f) {
1640 c[maxc-1] = uchar & 0x7f;
1643 unsigned char rest = 0x40;
1644 unsigned char first = 0x80;
1646 for (int i = start; i >=0; --i) {
1648 c[i] = first + uchar;
1651 c[i] = 0x80 | (uchar & 0x3f);
1658 for (int i = 0; i < maxc; i++) {
1659 if (c[i] == 0) continue;
1665 static void addAccents(string latex_in, string unicode_out)
1667 latex_in = latex_in.substr(1);
1668 AccentsIterator it_ac = accents.find(latex_in);
1669 if (it_ac == accents.end()) {
1670 accents[latex_in] = unicode_out;
1673 LYXERR0("Key " << latex_in << " already set");
1677 void static fillMissingUnicodesymbols()
1679 addAccents("\\pounds", getutf8(0x00a3));
1680 addAccents("\\textsterling", getutf8(0x00a3));
1681 addAccents("\\textyen", getutf8(0x00a5));
1682 addAccents("\\yen", getutf8(0x00a5));
1683 addAccents("\\textsection", getutf8(0x00a7));
1684 addAccents("\\mathsection", getutf8(0x00a7));
1685 addAccents("\\textcopyright", getutf8(0x00a9));
1686 addAccents("\\copyright", getutf8(0x00a9));
1687 addAccents("\\textlnot", getutf8(0x00ac));
1688 addAccents("\\neg", getutf8(0x00ac));
1689 addAccents("\\textregistered", getutf8(0x00ae));
1690 addAccents("\\circledR", getutf8(0x00ae));
1691 addAccents("\\textpm", getutf8(0x00b1));
1692 addAccents("\\pm", getutf8(0x00b1));
1693 addAccents("\\textparagraph", getutf8(0x00b6));
1694 addAccents("\\mathparagraph", getutf8(0x00b6));
1695 addAccents("\\textperiodcentered", getutf8(0x00b7));
1696 addAccents("\\texttimes", getutf8(0x00d7));
1697 addAccents("\\times", getutf8(0x00d7));
1698 addAccents("\\O", getutf8(0x00d8));
1699 addAccents("\\dh", getutf8(0x00f0));
1700 addAccents("\\eth", getutf8(0x00f0));
1701 addAccents("\\textdiv", getutf8(0x00f7));
1702 addAccents("\\div", getutf8(0x00f7));
1703 addAccents("\\o", getutf8(0x00f8));
1704 addAccents("\\textcrlambda", getutf8(0x019b));
1705 addAccents("\\j", getutf8(0x0237));
1706 addAccents("\\textrevepsilon", getutf8(0x025c));
1707 addAccents("\\textbaru", getutf8(0x0289));
1708 addAccents("\\textquoteleft", getutf8(0x02bb));
1709 addAccents("\\textGamma", getutf8(0x0393));
1710 addAccents("\\Gamma", getutf8(0x0393));
1711 addAccents("\\textDelta", getutf8(0x0394));
1712 addAccents("\\Delta", getutf8(0x0394));
1713 addAccents("\\textTheta", getutf8(0x0398));
1714 addAccents("\\Theta", getutf8(0x0398));
1715 addAccents("\\textLambda", getutf8(0x039b));
1716 addAccents("\\Lambda", getutf8(0x039b));
1717 addAccents("\\textXi", getutf8(0x039e));
1718 addAccents("\\Xi", getutf8(0x039e));
1719 addAccents("\\textPi", getutf8(0x03a0));
1720 addAccents("\\Pi", getutf8(0x03a0));
1721 addAccents("\\textSigma", getutf8(0x03a3));
1722 addAccents("\\Sigma", getutf8(0x03a3));
1723 addAccents("\\textUpsilon", getutf8(0x03a5));
1724 addAccents("\\Upsilon", getutf8(0x03a5));
1725 addAccents("\\textPhi", getutf8(0x03a6));
1726 addAccents("\\Phi", getutf8(0x03a6));
1727 addAccents("\\textPsi", getutf8(0x03a8));
1728 addAccents("\\Psi", getutf8(0x03a8));
1729 addAccents("\\textOmega", getutf8(0x03a9));
1730 addAccents("\\Omega", getutf8(0x03a9));
1731 addAccents("\\textalpha", getutf8(0x03b1));
1732 addAccents("\\alpha", getutf8(0x03b1));
1733 addAccents("\\textbeta", getutf8(0x03b2));
1734 addAccents("\\beta", getutf8(0x03b2));
1735 addAccents("\\textgamma", getutf8(0x03b3));
1736 addAccents("\\gamma", getutf8(0x03b3));
1737 addAccents("\\textdelta", getutf8(0x03b4));
1738 addAccents("\\delta", getutf8(0x03b4));
1739 addAccents("\\textepsilon", getutf8(0x03b5));
1740 addAccents("\\varepsilon", getutf8(0x03b5));
1741 addAccents("\\textzeta", getutf8(0x03b6));
1742 addAccents("\\zeta", getutf8(0x03b6));
1743 addAccents("\\texteta", getutf8(0x03b7));
1744 addAccents("\\eta", getutf8(0x03b7));
1745 addAccents("\\texttheta", getutf8(0x03b8));
1746 addAccents("\\theta", getutf8(0x03b8));
1747 addAccents("\\textiota", getutf8(0x03b9));
1748 addAccents("\\iota", getutf8(0x03b9));
1749 addAccents("\\textkappa", getutf8(0x03ba));
1750 addAccents("\\kappa", getutf8(0x03ba));
1751 addAccents("\\textlambda", getutf8(0x03bb));
1752 addAccents("\\lambda", getutf8(0x03bb));
1753 addAccents("\\textmu", getutf8(0x03bc));
1754 addAccents("\\mu", getutf8(0x03bc));
1755 addAccents("\\textnu", getutf8(0x03bd));
1756 addAccents("\\nu", getutf8(0x03bd));
1757 addAccents("\\textxi", getutf8(0x03be));
1758 addAccents("\\xi", getutf8(0x03be));
1759 addAccents("\\textpi", getutf8(0x03c0));
1760 addAccents("\\pi", getutf8(0x03c0));
1761 addAccents("\\textrho", getutf8(0x03c1));
1762 addAccents("\\rho", getutf8(0x03c1));
1763 addAccents("\\textfinalsigma", getutf8(0x03c2));
1764 addAccents("\\varsigma", getutf8(0x03c2));
1765 addAccents("\\textsigma", getutf8(0x03c3));
1766 addAccents("\\sigma", getutf8(0x03c3));
1767 addAccents("\\texttau", getutf8(0x03c4));
1768 addAccents("\\tau", getutf8(0x03c4));
1769 addAccents("\\textupsilon", getutf8(0x03c5));
1770 addAccents("\\upsilon", getutf8(0x03c5));
1771 addAccents("\\textphi", getutf8(0x03c6));
1772 addAccents("\\varphi", getutf8(0x03c6));
1773 addAccents("\\textchi", getutf8(0x03c7));
1774 addAccents("\\chi", getutf8(0x03c7));
1775 addAccents("\\textpsi", getutf8(0x03c8));
1776 addAccents("\\psi", getutf8(0x03c8));
1777 addAccents("\\textomega", getutf8(0x03c9));
1778 addAccents("\\omega", getutf8(0x03c9));
1779 addAccents("\\textdigamma", getutf8(0x03dd));
1780 addAccents("\\digamma", getutf8(0x03dd));
1781 addAccents("\\hebalef", getutf8(0x05d0));
1782 addAccents("\\aleph", getutf8(0x05d0));
1783 addAccents("\\hebbet", getutf8(0x05d1));
1784 addAccents("\\beth", getutf8(0x05d1));
1785 addAccents("\\hebgimel", getutf8(0x05d2));
1786 addAccents("\\gimel", getutf8(0x05d2));
1787 addAccents("\\hebdalet", getutf8(0x05d3));
1788 addAccents("\\daleth", getutf8(0x05d3));
1789 addAccents("\\hebhe", getutf8(0x05d4));
1790 addAccents("\\hebvav", getutf8(0x05d5));
1791 addAccents("\\hebzayin", getutf8(0x05d6));
1792 addAccents("\\hebhet", getutf8(0x05d7));
1793 addAccents("\\hebtet", getutf8(0x05d8));
1794 addAccents("\\hebyod", getutf8(0x05d9));
1795 addAccents("\\hebfinalkaf", getutf8(0x05da));
1796 addAccents("\\hebkaf", getutf8(0x05db));
1797 addAccents("\\heblamed", getutf8(0x05dc));
1798 addAccents("\\hebfinalmem", getutf8(0x05dd));
1799 addAccents("\\hebmem", getutf8(0x05de));
1800 addAccents("\\hebfinalnun", getutf8(0x05df));
1801 addAccents("\\hebnun", getutf8(0x05e0));
1802 addAccents("\\hebsamekh", getutf8(0x05e1));
1803 addAccents("\\hebayin", getutf8(0x05e2));
1804 addAccents("\\hebfinalpe", getutf8(0x05e3));
1805 addAccents("\\hebpe", getutf8(0x05e4));
1806 addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1807 addAccents("\\hebtsadi", getutf8(0x05e6));
1808 addAccents("\\hebqof", getutf8(0x05e7));
1809 addAccents("\\hebresh", getutf8(0x05e8));
1810 addAccents("\\hebshin", getutf8(0x05e9));
1811 addAccents("\\hebtav", getutf8(0x05ea));
1814 addAccents("\\thaiKoKai", getutf8(0x0e01));
1815 addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1816 addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1817 addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1818 addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1819 addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1820 addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1821 addAccents("\\thaiChoChan", getutf8(0x0e08));
1822 addAccents("\\thaiChoChing", getutf8(0x0e09));
1823 addAccents("\\thaiChoChang", getutf8(0x0e0a));
1824 addAccents("\\thaiSoSo", getutf8(0x0e0b));
1825 addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1826 addAccents("\\thaiYoYing", getutf8(0x0e0d));
1827 addAccents("\\thaiDoChada", getutf8(0x0e0e));
1828 addAccents("\\thaiToPatak", getutf8(0x0e0f));
1829 addAccents("\\thaiThoThan", getutf8(0x0e10));
1830 addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1831 addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1832 addAccents("\\thaiNoNen", getutf8(0x0e13));
1833 addAccents("\\thaiDoDek", getutf8(0x0e14));
1834 addAccents("\\thaiToTao", getutf8(0x0e15));
1835 addAccents("\\thaiThoThung", getutf8(0x0e16));
1836 addAccents("\\thaiThoThahan", getutf8(0x0e17));
1837 addAccents("\\thaiThoThong", getutf8(0x0e18));
1838 addAccents("\\thaiNoNu", getutf8(0x0e19));
1839 addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1840 addAccents("\\thaiPoPla", getutf8(0x0e1b));
1841 addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1842 addAccents("\\thaiFoFa", getutf8(0x0e1d));
1843 addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1844 addAccents("\\thaiFoFan", getutf8(0x0e1f));
1845 addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1846 addAccents("\\thaiMoMa", getutf8(0x0e21));
1847 addAccents("\\thaiYoYak", getutf8(0x0e22));
1848 addAccents("\\thaiRoRua", getutf8(0x0e23));
1849 addAccents("\\thaiRu", getutf8(0x0e24));
1850 addAccents("\\thaiLoLing", getutf8(0x0e25));
1851 addAccents("\\thaiLu", getutf8(0x0e26));
1852 addAccents("\\thaiWoWaen", getutf8(0x0e27));
1853 addAccents("\\thaiSoSala", getutf8(0x0e28));
1854 addAccents("\\thaiSoRusi", getutf8(0x0e29));
1855 addAccents("\\thaiSoSua", getutf8(0x0e2a));
1856 addAccents("\\thaiHoHip", getutf8(0x0e2b));
1857 addAccents("\\thaiLoChula", getutf8(0x0e2c));
1858 addAccents("\\thaiOAng", getutf8(0x0e2d));
1859 addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1860 addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1861 addAccents("\\thaiSaraA", getutf8(0x0e30));
1862 addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1863 addAccents("\\thaiSaraAa", getutf8(0x0e32));
1864 addAccents("\\thaiSaraAm", getutf8(0x0e33));
1865 addAccents("\\thaiSaraI", getutf8(0x0e34));
1866 addAccents("\\thaiSaraIi", getutf8(0x0e35));
1867 addAccents("\\thaiSaraUe", getutf8(0x0e36));
1868 addAccents("\\thaiSaraUee", getutf8(0x0e37));
1869 addAccents("\\thaiSaraU", getutf8(0x0e38));
1870 addAccents("\\thaiSaraUu", getutf8(0x0e39));
1871 addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1872 addAccents("\\thaiSaraE", getutf8(0x0e40));
1873 addAccents("\\thaiSaraAe", getutf8(0x0e41));
1874 addAccents("\\thaiSaraO", getutf8(0x0e42));
1875 addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1876 addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1877 addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1878 addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1879 addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1880 addAccents("\\thaiMaiEk", getutf8(0x0e48));
1881 addAccents("\\thaiMaiTho", getutf8(0x0e49));
1882 addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1883 addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1884 addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1885 addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1886 addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1887 addAccents("\\thaiFongman", getutf8(0x0e4f));
1888 addAccents("\\thaizero", getutf8(0x0e50));
1889 addAccents("\\thaione", getutf8(0x0e51));
1890 addAccents("\\thaitwo", getutf8(0x0e52));
1891 addAccents("\\thaithree", getutf8(0x0e53));
1892 addAccents("\\thaifour", getutf8(0x0e54));
1893 addAccents("\\thaifive", getutf8(0x0e55));
1894 addAccents("\\thaisix", getutf8(0x0e56));
1895 addAccents("\\thaiseven", getutf8(0x0e57));
1896 addAccents("\\thaieight", getutf8(0x0e58));
1897 addAccents("\\thainine", getutf8(0x0e59));
1898 addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1899 addAccents("\\thaiKhomut", getutf8(0x0e5b));
1900 addAccents("\\dag", getutf8(0x2020));
1901 addAccents("\\dagger", getutf8(0x2020));
1902 addAccents("\\textdagger", getutf8(0x2020));
1903 addAccents("\\ddag", getutf8(0x2021));
1904 addAccents("\\ddagger", getutf8(0x2021));
1905 addAccents("\\textdaggerdbl", getutf8(0x2021));
1906 addAccents("\\textbullet", getutf8(0x2022));
1907 addAccents("\\bullet", getutf8(0x2022));
1908 addAccents("\\dots", getutf8(0x2026));
1909 addAccents("\\ldots", getutf8(0x2026));
1910 addAccents("\\textellipsis", getutf8(0x2026));
1911 addAccents("\\textasciiacute", getutf8(0x2032));
1912 addAccents("\\prime", getutf8(0x2032));
1913 addAccents("\\textacutedbl", getutf8(0x2033));
1914 addAccents("\\dprime", getutf8(0x2033));
1915 addAccents("\\textasciigrave", getutf8(0x2035));
1916 addAccents("\\backprime", getutf8(0x2035));
1917 addAccents("\\textsubcircum{ }", getutf8(0x2038));
1918 addAccents("\\caretinsert", getutf8(0x2038));
1919 addAccents("\\textasteriskcentered", getutf8(0x204e));
1920 addAccents("\\ast", getutf8(0x204e));
1921 addAccents("\\textmho", getutf8(0x2127));
1922 addAccents("\\mho", getutf8(0x2127));
1923 addAccents("\\textleftarrow", getutf8(0x2190));
1924 addAccents("\\leftarrow", getutf8(0x2190));
1925 addAccents("\\textuparrow", getutf8(0x2191));
1926 addAccents("\\uparrow", getutf8(0x2191));
1927 addAccents("\\textrightarrow", getutf8(0x2192));
1928 addAccents("\\rightarrow", getutf8(0x2192));
1929 addAccents("\\textdownarrow", getutf8(0x2193));
1930 addAccents("\\downarrow", getutf8(0x2193));
1931 addAccents("\\textglobrise", getutf8(0x2197));
1932 addAccents("\\nearrow", getutf8(0x2197));
1933 addAccents("\\textglobfall", getutf8(0x2198));
1934 addAccents("\\searrow", getutf8(0x2198));
1935 addAccents("\\textsurd", getutf8(0x221a));
1936 addAccents("\\surd", getutf8(0x221a));
1937 addAccents("\\textbigcircle", getutf8(0x25ef));
1938 addAccents("\\bigcirc", getutf8(0x25ef));
1939 addAccents("\\FiveStar", getutf8(0x2605));
1940 addAccents("\\bigstar", getutf8(0x2605));
1941 addAccents("\\FiveStarOpen", getutf8(0x2606));
1942 addAccents("\\bigwhitestar", getutf8(0x2606));
1943 addAccents("\\Checkmark", getutf8(0x2713));
1944 addAccents("\\checkmark", getutf8(0x2713));
1945 addAccents("\\CrossMaltese", getutf8(0x2720));
1946 addAccents("\\maltese", getutf8(0x2720));
1947 addAccents("\\textlangle", getutf8(0x27e8));
1948 addAccents("\\langle", getutf8(0x27e8));
1949 addAccents("\\textrangle", getutf8(0x27e9));
1950 addAccents("\\rangle", getutf8(0x27e9));
1953 static void buildAccentsMap()
1955 accents["imath"] = "ı";
1957 accents["jmath"] = "ȷ";
1958 accents["cdot"] = "·";
1959 accents["textasciicircum"] = "^";
1960 accents["mathcircumflex"] = "^";
1961 accents["guillemotright"] = "»";
1962 accents["guillemotleft"] = "«";
1963 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1964 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1965 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1966 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1967 accents["negmedspace"] = getutf8(0xf0005);
1968 accents["thickspace"] = getutf8(0xf0006);
1969 accents["negthickspace"] = getutf8(0xf0007);
1970 accents["lyx"] = getutf8(0xf0010); // Used logos
1971 accents["LyX"] = getutf8(0xf0010);
1972 accents["tex"] = getutf8(0xf0011);
1973 accents["TeX"] = getutf8(0xf0011);
1974 accents["latex"] = getutf8(0xf0012);
1975 accents["LaTeX"] = getutf8(0xf0012);
1976 accents["latexe"] = getutf8(0xf0013);
1977 accents["LaTeXe"] = getutf8(0xf0013);
1978 accents["lyxarrow"] = getutf8(0xf0020);
1979 accents["braceleft"] = getutf8(0xf0030);
1980 accents["braceright"] = getutf8(0xf0031);
1981 accents["lyxtilde"] = getutf8(0xf0032);
1982 accents["sim"] = getutf8(0xf0032);
1983 accents["lyxdollar"] = getutf8(0xf0033);
1984 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1985 accents["backslash LyX"] = getutf8(0xf0010);
1986 accents["backslash tex"] = getutf8(0xf0011);
1987 accents["backslash TeX"] = getutf8(0xf0011);
1988 accents["backslash latex"] = getutf8(0xf0012);
1989 accents["backslash LaTeX"] = getutf8(0xf0012);
1990 accents["backslash latexe"] = getutf8(0xf0013);
1991 accents["backslash LaTeXe"] = getutf8(0xf0013);
1992 accents["backslash lyxarrow"] = getutf8(0xf0020);
1993 accents["ddot{\\imath}"] = "ï";
1994 buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
1995 "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1996 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1997 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1998 accents["acute{\\imath}"] = "í";
1999 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2000 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2001 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
2002 buildaccent("mathring|r", "aAuUwy",
2004 accents["check{\\imath}"] = "ǐ";
2005 accents["check{\\jmath}"] = "ǰ";
2006 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2007 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
2008 accents["hat{\\imath}"] = "î";
2009 accents["hat{\\jmath}"] = "ĵ";
2010 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2011 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
2012 accents["bar{\\imath}"] = "ī";
2013 buildaccent("bar|=", "aAeEiIoOuUyY",
2014 "āĀēĒīĪōŌūŪȳȲ"); // macron
2015 accents["tilde{\\imath}"] = "ĩ";
2016 buildaccent("tilde", "aAeEiInNoOuUvVyY",
2017 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
2018 accents["breve{\\imath}"] = "ĭ";
2019 buildaccent("breve|u", "aAeEgGiIoOuU",
2020 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
2021 accents["grave{\\imath}"] = "ì";
2022 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2023 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
2024 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2025 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
2026 buildaccent("ogonek|k", "AaEeIiUuOo",
2027 "ĄąĘęĮįŲųǪǫ"); // ogonek
2028 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2029 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
2030 buildaccent("subring|textsubring", "Aa",
2032 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2033 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
2034 buildaccent("subtilde|textsubtilde", "EeIiUu",
2035 "ḚḛḬḭṴṵ"); // subtilde
2036 accents["dgrave{\\imath}"] = "ȉ";
2037 accents["textdoublegrave{\\i}"] = "ȉ";
2038 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2039 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2040 accents["rcap{\\imath}"] = "ȋ";
2041 accents["textroundcap{\\i}"] = "ȋ";
2042 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2043 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2044 buildaccent("slashed", "oO",
2046 fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2047 // LYXERR0("Number of accents " << accents.size());
2051 * Created accents in math or regexp environment
2052 * are macros, but we need the utf8 equivalent
2054 void Intervall::removeAccents()
2056 if (accents.empty())
2058 static regex const accre("\\\\("
2059 "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]+\\}"
2060 "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2062 "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2067 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2069 string key = sub.str(1);
2070 AccentsIterator it_ac = accents.find(key);
2071 if (it_ac != accents.end()) {
2072 string val = it_ac->second;
2073 size_t pos = sub.position(size_t(0));
2074 for (size_t i = 0; i < val.size(); i++) {
2075 par[pos+i] = val[i];
2077 // Remove possibly following space too
2078 if (par[pos+sub.str(0).size()] == ' ')
2079 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2081 addIntervall(pos+val.size(), pos + sub.str(0).size());
2082 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2083 // remove traces of any remaining chars
2088 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2093 void Intervall::handleOpenP(int i)
2096 if ((size_t) actualdeptindex >= depts.size()) {
2097 depts.resize(actualdeptindex + 30);
2098 closes.resize(actualdeptindex + 30);
2100 depts[actualdeptindex] = i+1;
2101 closes[actualdeptindex] = -1;
2102 // checkDepthIndex(actualdeptindex);
2105 void Intervall::handleCloseP(int i, bool closingAllowed)
2107 if (actualdeptindex <= 0) {
2108 if (! closingAllowed)
2109 LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
2110 // if we are at the very end
2111 addIntervall(i, i+1);
2114 closes[actualdeptindex] = i+1;
2119 void Intervall::resetOpenedP(int openPos)
2121 // Used as initializer for foreignlanguage entry
2122 actualdeptindex = 1;
2123 depts[1] = openPos+1;
2127 int Intervall::previousNotIgnored(int start) const
2129 int idx = 0; /* int intervalls */
2130 for (idx = ignoreidx; idx >= 0; --idx) {
2131 if (start > borders[idx].upper)
2133 if (start >= borders[idx].low)
2134 start = borders[idx].low-1;
2139 int Intervall::nextNotIgnored(int start) const
2141 int idx = 0; /* int intervalls */
2142 for (idx = 0; idx <= ignoreidx; idx++) {
2143 if (start < borders[idx].low)
2145 if (start < borders[idx].upper)
2146 start = borders[idx].upper;
2151 typedef unordered_map<string, KeyInfo> KeysMap;
2152 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2153 typedef vector< KeyInfo> Entries;
2154 static KeysMap keys = unordered_map<string, KeyInfo>();
2160 Intervall interval_;
2161 void buildKeys(bool);
2162 void buildEntries(bool);
2163 void makeKey(const string &, KeyInfo, bool isPatternString);
2164 void processRegion(int start, int region_end); /* remove {} parts */
2165 void removeHead(KeyInfo const &, int count=0);
2168 LatexInfo(string const & par, bool isPatternString)
2169 : entidx_(-1), interval_(isPatternString, par)
2171 buildKeys(isPatternString);
2172 entries_ = vector<KeyInfo>();
2173 buildEntries(isPatternString);
2177 if (entries_.empty()) {
2180 if (entries_[0].keytype == KeyInfo::isTitle) {
2181 interval_.hasTitle = true;
2182 if (! entries_[0].disabled) {
2183 interval_.titleValue = entries_[0].head;
2186 interval_.titleValue = "";
2188 removeHead(entries_[0]);
2189 if (entries_.size() > 1)
2198 if (int(entries_.size()) > entidx_) {
2205 bool setNextKey(int idx) {
2206 if ((idx == entidx_) && (entidx_ >= 0)) {
2213 int find(int start, KeyInfo::KeyType keytype) const {
2217 while (tmpIdx < int(entries_.size())) {
2218 if (entries_[tmpIdx].keytype == keytype)
2224 int process(ostringstream & os, KeyInfo const & actual);
2225 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2226 // string show(int lastpos) { return interval.show(lastpos);}
2227 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2228 KeyInfo &getKeyInfo(int keyinfo) {
2229 static KeyInfo invalidInfo = KeyInfo();
2230 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2233 return entries_[keyinfo];
2235 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2236 void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2240 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2244 for (int i = start; i < end; i += 1 + skip) {
2248 if (c == '\\') skip = 1;
2252 else if (c == down) {
2255 if ((repeat <= 0) || (par[i+1] != up))
2264 void Intervall::removeInvalidClosings(void)
2266 // this can happen, if there are deleted parts
2269 for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2272 if (c == '\\') skip = 1;
2275 else if (c == '}') {
2277 addIntervall(i, i+1);
2278 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2290 size_t mathpostfixsize;
2292 size_t mathprefixsize;
2296 vector<MathEntry> entries_;
2301 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2302 MathEntry m = MathEntry();
2304 m.mathStart = start;
2305 m.mathprefixsize = prefixsize;
2306 m.mathEnd = end + postfixsize;
2307 m.mathpostfixsize = postfixsize;
2308 m.mathSize = m.mathEnd - m.mathStart;
2309 entries_.push_back(m);
2311 bool empty() const { return entries_.empty(); }
2312 size_t getEndPos() const {
2313 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2316 return entries_[actualIdx_].mathEnd;
2318 size_t getStartPos() const {
2319 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2320 return 100000; /* definitely enough? */
2322 return entries_[actualIdx_].mathStart;
2324 size_t getPrefixSize() const {
2325 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2328 return entries_[actualIdx_].mathprefixsize;
2330 size_t getPostfixSize() const {
2331 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2334 return entries_[actualIdx_].mathpostfixsize;
2336 size_t getFirstPos() {
2338 return getStartPos();
2340 size_t getSize() const {
2341 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2344 return entries_[actualIdx_].mathSize;
2346 void incrEntry() { actualIdx_++; }
2349 void LatexInfo::buildEntries(bool isPatternString)
2351 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2352 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2353 static bool disableLanguageOverride = false;
2354 smatch sub, submath;
2355 bool evaluatingRegexp = false;
2357 bool evaluatingMath = false;
2358 bool evaluatingCode = false;
2360 bool evaluatingOptional = false;
2361 size_t optionalEnd = 0;
2364 bool math_end_waiting = false;
2365 size_t math_pos = 10000;
2366 size_t math_prefix_size = 1;
2368 static vector<string> usedText = vector<string>();
2369 static bool removeMathHull = false;
2371 interval_.removeAccents();
2372 interval_.removeInvalidClosings();
2374 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2376 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2377 // prefixed by odd count of '\\'
2380 if (math_end_waiting) {
2381 size_t pos = submath.position(size_t(2));
2382 if ((math_end == "$") &&
2383 (submath.str(2) == "$")) {
2384 mi.insert("$", math_pos, 1, pos, 1);
2385 math_end_waiting = false;
2387 else if ((math_end == "\\]") &&
2388 (submath.str(2) == "\\]")) {
2389 mi.insert("\\]", math_pos, 2, pos, 2);
2390 math_end_waiting = false;
2392 else if ((submath.str(3).compare("end") == 0) &&
2393 (submath.str(5).compare(math_end) == 0)) {
2394 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2395 math_end_waiting = false;
2401 if (submath.str(3).compare("begin") == 0) {
2402 math_end_waiting = true;
2403 math_end = submath.str(5);
2404 math_pos = submath.position(size_t(2));
2405 math_prefix_size = submath.str(2).length();
2407 else if (submath.str(2).compare("\\[") == 0) {
2408 math_end_waiting = true;
2410 math_pos = submath.position(size_t(2));
2412 else if (submath.str(2) == "$") {
2413 size_t pos = submath.position(size_t(2));
2414 math_end_waiting = true;
2420 // Ignore language if there is math somewhere in pattern-string
2421 if (isPatternString) {
2422 for (auto const & s: usedText) {
2423 // Remove entries created in previous search runs
2426 usedText = vector<string>();
2429 keys["foreignlanguage"].disabled = true;
2430 disableLanguageOverride = true;
2431 removeMathHull = false;
2434 removeMathHull = true; // used later if not isPatternString
2435 disableLanguageOverride = false;
2439 if (disableLanguageOverride) {
2440 keys["foreignlanguage"].disabled = true;
2443 math_pos = mi.getFirstPos();
2444 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2446 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2447 // prefixed by odd count of '\\'
2450 string key = sub.str(5);
2452 if (sub.str(2)[0] == '\\')
2453 key = sub.str(2)[1];
2458 KeysIterator it_key = keys.find(key);
2459 if (it_key != keys.end()) {
2460 if (it_key->second.keytype == KeyInfo::headRemove) {
2461 KeyInfo found1 = it_key->second;
2462 found1.disabled = true;
2463 found1.head = "\\" + key + "{";
2464 found1._tokenstart = sub.position(size_t(2));
2465 found1._tokensize = found1.head.length();
2466 found1._dataStart = found1._tokenstart + found1.head.length();
2467 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2468 found1._dataEnd = endpos;
2473 if (evaluatingRegexp) {
2474 if (sub.str(3).compare("endregexp") == 0) {
2475 evaluatingRegexp = false;
2476 // found._tokenstart already set
2477 found._dataEnd = sub.position(size_t(2)) + 13;
2478 found._dataStart = found._dataEnd;
2479 found._tokensize = found._dataEnd - found._tokenstart;
2480 found.parenthesiscount = 0;
2481 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2488 if (evaluatingMath) {
2489 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2491 evaluatingMath = false;
2493 math_pos = mi.getStartPos();
2495 if (it_key == keys.end()) {
2496 found = KeyInfo(KeyInfo::isStandard, 0, true);
2497 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2498 found = KeyInfo(KeyInfo::isText, 0, false);
2499 if (isPatternString) {
2500 found.keytype = KeyInfo::isChar;
2501 found.disabled = false;
2505 usedText.push_back(key);
2509 if (key.compare("regexp") == 0) {
2510 evaluatingRegexp = true;
2511 found._tokenstart = sub.position(size_t(2));
2512 found._tokensize = 0;
2516 // Handle the other params of key
2517 if (found.keytype == KeyInfo::isIgnored)
2519 else if (found.keytype == KeyInfo::isMath) {
2520 if (size_t(sub.position(size_t(2))) == math_pos) {
2522 found._tokenstart = sub.position(size_t(2));
2523 found._tokensize = mi.getSize();
2524 found._dataEnd = found._tokenstart + found._tokensize;
2525 found._dataStart = found._dataEnd;
2526 found.parenthesiscount = 0;
2527 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2528 if (removeMathHull) {
2529 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2530 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2533 // Treate all math constructs as simple math
2534 interval_.par[found._tokenstart] = '$';
2535 interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2536 interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2537 interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2539 evaluatingMath = true;
2542 // begin|end of unknown env, discard
2543 // First handle tables
2544 // longtable|tabular
2545 bool discardComment;
2547 found.keytype = KeyInfo::doRemove;
2548 if ((sub.str(7).compare("longtable") == 0) ||
2549 (sub.str(7).compare("tabular") == 0)) {
2550 discardComment = true; /* '%' */
2553 discardComment = false;
2554 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2556 string token = sub.str(7);
2557 if (regex_match(token, sub2, removeArgs)) {
2558 found.keytype = KeyInfo::removeWithArg;
2561 // discard spaces before pos(2)
2562 int pos = sub.position(size_t(2));
2564 for (count = 0; pos - count > 0; count++) {
2565 char c = interval_.par[pos-count-1];
2566 if (discardComment) {
2567 if ((c != ' ') && (c != '%'))
2573 found._tokenstart = pos - count;
2574 if (sub.str(3).compare(0, 5, "begin") == 0) {
2575 size_t pos1 = pos + sub.str(2).length();
2576 if (sub.str(7).compare("cjk") == 0) {
2577 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2578 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2580 found.keytype = KeyInfo::isMain;
2581 found._dataStart = pos1;
2582 found._dataEnd = interval_.par.length();
2583 found.disabled = keys["foreignlanguage"].disabled;
2584 found.used = keys["foreignlanguage"].used;
2585 found._tokensize = pos1 - found._tokenstart;
2586 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2589 // Swallow possible optional params
2590 while (interval_.par[pos1] == '[') {
2591 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2593 // Swallow also the eventual parameter
2594 if (interval_.par[pos1] == '{') {
2595 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2598 found._dataEnd = pos1;
2600 found._dataStart = found._dataEnd;
2601 found._tokensize = count + found._dataEnd - pos;
2602 found.parenthesiscount = 0;
2603 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2604 found.disabled = true;
2608 // Handle "\end{...}"
2609 found._dataStart = pos + sub.str(2).length();
2610 found._dataEnd = found._dataStart;
2611 found._tokensize = count + found._dataEnd - pos;
2612 found.parenthesiscount = 0;
2613 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2614 found.disabled = true;
2618 else if (found.keytype != KeyInfo::isRegex) {
2619 found._tokenstart = sub.position(size_t(2));
2620 if (found.parenthesiscount == 0) {
2621 // Probably to be discarded
2622 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2623 char following = interval_.par[following_pos];
2624 if (following == ' ')
2625 found.head = "\\" + sub.str(5) + " ";
2626 else if (following == '=') {
2627 // like \uldepth=1000pt
2628 found.head = sub.str(2);
2631 found.head = "\\" + key;
2632 found._tokensize = found.head.length();
2633 found._dataEnd = found._tokenstart + found._tokensize;
2634 found._dataStart = found._dataEnd;
2637 int params = found._tokenstart + key.length() + 1;
2638 if (evaluatingOptional) {
2639 if (size_t(found._tokenstart) > optionalEnd) {
2640 evaluatingOptional = false;
2643 found.disabled = true;
2646 int optend = params;
2647 while (interval_.par[optend] == '[') {
2648 // discard optional parameters
2649 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2651 if (optend > params) {
2652 key += interval_.par.substr(params, optend-params);
2653 evaluatingOptional = true;
2654 optionalEnd = optend;
2655 if (found.keytype == KeyInfo::isSectioning) {
2656 // Remove optional values (but still keep in header)
2657 interval_.addIntervall(params, optend);
2660 string token = sub.str(7);
2662 if (interval_.par[optend] != '{') {
2664 found.parenthesiscount = 0;
2665 found.head = "\\" + key;
2668 closings = found.parenthesiscount;
2669 if (found.parenthesiscount == 1) {
2670 found.head = "\\" + key + "{";
2672 else if (found.parenthesiscount > 1) {
2674 found.head = sub.str(2) + "{";
2675 closings = found.parenthesiscount - 1;
2678 found.head = "\\" + key + "{";
2681 found._tokensize = found.head.length();
2682 found._dataStart = found._tokenstart + found.head.length();
2683 if (found.keytype == KeyInfo::doRemove) {
2685 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2686 if (endpar >= interval_.par.length())
2687 found._dataStart = interval_.par.length();
2689 found._dataStart = endpar;
2690 found._tokensize = found._dataStart - found._tokenstart;
2693 found._dataStart = found._tokenstart + found._tokensize;
2697 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2698 found._dataStart += 15;
2702 endpos = found._dataStart - 1;
2704 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2705 if (found.keytype == KeyInfo::isList) {
2706 // Check if it really is list env
2707 static regex const listre("^([a-z]+)$");
2709 if (!regex_match(token, sub2, listre)) {
2710 // Change the key of this entry. It is not in a list/item environment
2711 found.keytype = KeyInfo::endArguments;
2714 if (found.keytype == KeyInfo::noMain) {
2715 evaluatingCode = true;
2717 codeStart = found._dataStart;
2719 else if (evaluatingCode) {
2720 if (size_t(found._dataStart) > codeEnd)
2721 evaluatingCode = false;
2722 else if (found.keytype == KeyInfo::isMain) {
2723 // Disable this key, treate it as standard
2724 found.keytype = KeyInfo::isStandard;
2725 found.disabled = true;
2726 if ((codeEnd +1 >= interval_.par.length()) &&
2727 (found._tokenstart == codeStart)) {
2728 // trickery, because the code inset starts
2729 // with \selectlanguage ...
2731 if (entries_.size() > 1) {
2732 entries_[entries_.size()-1]._dataEnd = codeEnd;
2737 if ((endpos == interval_.par.length()) &&
2738 (found.keytype == KeyInfo::doRemove)) {
2739 // Missing closing => error in latex-input?
2740 // therefore do not delete remaining data
2741 found._dataStart -= 1;
2742 found._dataEnd = found._dataStart;
2745 found._dataEnd = endpos;
2747 if (isPatternString) {
2748 keys[key].used = true;
2751 entries_.push_back(found);
2755 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2757 stringstream s(keysstring);
2759 const char delim = '|';
2760 while (getline(s, key, delim)) {
2761 KeyInfo keyII(keyI);
2762 if (isPatternString) {
2765 else if ( !keys[key].used)
2766 keyII.disabled = true;
2771 void LatexInfo::buildKeys(bool isPatternString)
2774 static bool keysBuilt = false;
2775 if (keysBuilt && !isPatternString) return;
2777 // Keys to ignore in any case
2778 makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2779 makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2780 // Known standard keys with 1 parameter.
2781 // Split is done, if not at start of region
2782 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2783 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2784 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2785 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2786 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2787 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2789 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2790 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2791 makeKey("section*|subsection*|subsubsection*|paragraph*",
2792 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2793 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2794 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2796 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2798 // Split is done, if not at start of region
2799 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2800 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2802 // Split is done always.
2803 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2807 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2808 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2809 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2810 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2812 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2813 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2814 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2815 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2817 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2818 // Custom space/skip, remove the content (== length value)
2819 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2820 // Found in fr/UserGuide.lyx
2821 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2823 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2824 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2825 // Known macros to remove (including their parameter)
2827 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2828 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2829 // handle like standard keys with 1 parameter.
2830 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2832 if (ignoreFormats.getDeleted()) {
2833 // Ignore deleted text
2834 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2837 // but preserve added text
2838 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2840 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2842 // Macros to remove, but let the parameter survive
2844 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2846 // Remove language spec from content of these insets
2847 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2849 // Same effect as previous, parameter will survive (because there is no one anyway)
2851 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2852 // Remove table decorations
2853 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2854 // Discard shape-header.
2855 // For footnote or shortcut too, because of lang settings
2856 // and wrong handling if used 'KeyInfo::noMain'
2857 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2858 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2859 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2860 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2861 makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2862 makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2863 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2864 // like ('tiny{}' or '\tiny ' ... )
2865 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2867 // Survives, like known character
2868 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2869 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2870 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2872 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2873 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2874 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2876 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2877 // Remove RTL/LTR marker
2878 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2879 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2880 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2881 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2882 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2883 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2884 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2885 if (isPatternString) {
2886 // Allow the first searched string to rebuild the keys too
2890 // no need to rebuild again
2896 * Keep the list of actual opened parentheses actual
2897 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2899 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2902 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2906 if (c == '\\') skip = 1;
2907 else if (c == '{') {
2910 else if (c == '}') {
2911 handleCloseP(i, closingAllowed);
2917 string Intervall::show(int lastpos)
2919 int idx = 0; /* int intervalls */
2922 if ((unsigned) lastpos > par.size())
2923 lastpos = par.size();
2924 for (idx = 0; idx <= ignoreidx; idx++) {
2925 while (i < lastpos) {
2927 if (i <= borders[idx].low) {
2928 if (borders[idx].low > lastpos)
2929 printsize = lastpos - i;
2931 printsize = borders[idx].low - i;
2932 s += par.substr(i, printsize);
2934 if (i >= borders[idx].low)
2935 i = borders[idx].upper;
2938 i = borders[idx].upper;
2944 s += par.substr(i, lastpos-i);
2950 void Intervall::output(ostringstream &os, int lastpos)
2952 // get number of chars to output
2953 int idx = 0; /* int intervalls */
2956 string startTitle = titleValue;
2957 for (idx = 0; idx <= ignoreidx; idx++) {
2959 if (i <= borders[idx].low) {
2961 if (borders[idx].low > lastpos)
2962 printsize = lastpos - i;
2964 printsize = borders[idx].low - i;
2965 if (printsize > 0) {
2966 os << startTitle << par.substr(i, printsize);
2968 printed += printsize;
2971 handleParentheses(i, false);
2972 if (i >= borders[idx].low)
2973 i = borders[idx].upper;
2976 i = borders[idx].upper;
2983 os << startTitle << par.substr(i, lastpos-i);
2984 printed += lastpos-i;
2986 handleParentheses(lastpos, false);
2988 if (keys["foreignlanguage"].disabled)
2989 startindex = actualdeptindex-langcount;
2991 startindex = actualdeptindex;
2992 for (int i = startindex; i > 0; --i) {
2995 if (hasTitle && (printed > 0))
2997 if (! isPatternString_)
2999 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3002 void LatexInfo::processRegion(int start, int region_end)
3004 while (start < region_end) { /* Let {[} and {]} survive */
3005 int cnt = interval_.isOpeningPar(start);
3007 // Closing is allowed past the region
3008 int closing = interval_.findclosing(start+1, interval_.par.length());
3009 interval_.addIntervall(start, start+1);
3010 interval_.addIntervall(closing, closing+1);
3014 start = interval_.nextNotIgnored(start+1);
3018 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3020 if (actual.parenthesiscount == 0) {
3021 // "{\tiny{} ...}" ==> "{{} ...}"
3022 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3025 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3026 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3027 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3031 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3034 switch (actual.keytype)
3036 case KeyInfo::isTitle: {
3038 nextKeyIdx = getNextKey();
3041 case KeyInfo::cleanToStart: {
3042 actual._dataEnd = actual._dataStart;
3043 nextKeyIdx = getNextKey();
3044 // Search for end of arguments
3045 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3047 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3048 entries_[i].disabled = true;
3050 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3052 while (interval_.par[actual._dataEnd] == ' ')
3054 interval_.addIntervall(0, actual._dataEnd+1);
3055 interval_.actualdeptindex = 0;
3056 interval_.depts[0] = actual._dataEnd+1;
3057 interval_.closes[0] = -1;
3060 case KeyInfo::isText:
3061 interval_.par[actual._tokenstart] = '#';
3062 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3063 nextKeyIdx = getNextKey();
3065 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
3066 if (actual.disabled)
3067 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3069 interval_.addIntervall(actual._dataStart, actual._dataEnd);
3072 case KeyInfo::isChar: {
3073 nextKeyIdx = getNextKey();
3076 case KeyInfo::isSize: {
3077 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3078 if (actual.parenthesiscount == 0)
3079 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3081 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3083 nextKeyIdx = getNextKey();
3085 // Here _dataStart points to '{', so correct it
3086 actual._dataStart += 1;
3087 actual._tokensize += 1;
3088 actual.parenthesiscount = 1;
3089 if (interval_.par[actual._dataStart] == '}') {
3090 // Determine the end if used like '{\tiny{}...}'
3091 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3092 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3095 // Determine the end if used like '\tiny{...}'
3096 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3098 // Split on this key if not at start
3099 int start = interval_.nextNotIgnored(previousStart);
3100 if (start < actual._tokenstart) {
3101 interval_.output(os, actual._tokenstart);
3102 interval_.addIntervall(start, actual._tokenstart);
3104 // discard entry if at end of actual
3105 nextKeyIdx = process(os, actual);
3109 case KeyInfo::endArguments: {
3110 // Remove trailing '{}' too
3111 actual._dataStart += 1;
3112 actual._dataEnd += 1;
3113 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3114 nextKeyIdx = getNextKey();
3117 case KeyInfo::noMain:
3119 case KeyInfo::isStandard: {
3120 if (actual.disabled) {
3122 processRegion(actual._dataStart, actual._dataStart+1);
3123 nextKeyIdx = getNextKey();
3125 // Split on this key if not at datastart of calling entry
3126 int start = interval_.nextNotIgnored(previousStart);
3127 if (start < actual._tokenstart) {
3128 interval_.output(os, actual._tokenstart);
3129 interval_.addIntervall(start, actual._tokenstart);
3131 // discard entry if at end of actual
3132 nextKeyIdx = process(os, actual);
3136 case KeyInfo::removeWithArg: {
3137 nextKeyIdx = getNextKey();
3138 // Search for end of arguments
3139 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3141 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3142 entries_[i].disabled = true;
3144 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3146 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3149 case KeyInfo::doRemove: {
3150 // Remove the key with all parameters and following spaces
3153 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3154 start = actual._dataEnd;
3156 start = actual._dataEnd+1;
3157 for (pos = start; pos < interval_.par.length(); pos++) {
3158 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3161 // Remove also enclosing parentheses [] and {}
3164 while (actual._tokenstart > numpars) {
3165 if (pos+numpars >= interval_.par.size())
3167 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3169 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3175 if (interval_.par[pos+numpars] == ' ')
3179 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3180 nextKeyIdx = getNextKey();
3183 case KeyInfo::isList: {
3184 // Discard space before _tokenstart
3186 for (count = 0; count < actual._tokenstart; count++) {
3187 if (interval_.par[actual._tokenstart-count-1] != ' ')
3190 nextKeyIdx = getNextKey();
3191 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3193 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3195 // How else can we catch this one?
3196 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3197 entries_[i].disabled = true;
3199 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3201 else if (nextKeyIdx > 0) {
3202 // Ignore any lang entries inside data region
3203 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3204 if (entries_[i].keytype == KeyInfo::isMain)
3205 entries_[i].disabled = true;
3208 if (actual.disabled) {
3209 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3212 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3214 if (interval_.par[actual._dataEnd+1] == '[') {
3215 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3216 if ((interval_.par[actual._dataEnd+2] == '{') &&
3217 (interval_.par[posdown-1] == '}')) {
3218 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3219 interval_.addIntervall(posdown-1, posdown+1);
3222 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3223 interval_.addIntervall(posdown, posdown+1);
3225 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3226 if (blk > posdown) {
3227 // Discard at most 1 space after empty item
3229 for (count = 0; count < 1; count++) {
3230 if (interval_.par[blk+count] != ' ')
3234 interval_.addIntervall(blk, blk+count);
3239 case KeyInfo::isSectioning: {
3240 // Discard spaces before _tokenstart
3242 int val = actual._tokenstart;
3243 for (count = 0; count < actual._tokenstart;) {
3244 val = interval_.previousNotIgnored(val-1);
3245 if (val < 0 || interval_.par[val] != ' ')
3248 count = actual._tokenstart - val;
3251 if (actual.disabled) {
3252 removeHead(actual, count);
3253 nextKeyIdx = getNextKey();
3255 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3256 nextKeyIdx = process(os, actual);
3260 case KeyInfo::isMath: {
3261 // Same as regex, use the content unchanged
3262 nextKeyIdx = getNextKey();
3265 case KeyInfo::isRegex: {
3266 // DO NOT SPLIT ON REGEX
3268 nextKeyIdx = getNextKey();
3271 case KeyInfo::isIgnored: {
3272 // Treat like a character for now
3273 nextKeyIdx = getNextKey();
3276 case KeyInfo::isMain: {
3277 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3278 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3279 if (actual._tokenstart > 0) {
3280 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3281 if ((prev >= 0) && interval_.par[prev] == '%')
3282 interval_.addIntervall(prev, prev+1);
3284 if (actual.disabled) {
3286 interval_.langcount++;
3287 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3288 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3289 // Discard also the space before math-equation
3290 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3292 nextKeyIdx = getNextKey();
3293 // interval.resetOpenedP(actual._dataStart-1);
3296 if (actual._tokenstart < 26) {
3297 // for the first (and maybe dummy) language
3298 interval_.setForDefaultLang(actual);
3300 interval_.resetOpenedP(actual._dataStart-1);
3304 case KeyInfo::invalid:
3305 case KeyInfo::headRemove:
3306 // These two cases cannot happen, already handled
3309 // LYXERR(Debug::INFO, "Unhandled keytype");
3310 nextKeyIdx = getNextKey();
3317 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3319 int end = interval_.nextNotIgnored(actual._dataEnd);
3320 int oldStart = actual._dataStart;
3321 int nextKeyIdx = getNextKey();
3323 if ((nextKeyIdx < 0) ||
3324 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3325 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3326 if (oldStart <= end) {
3327 processRegion(oldStart, end);
3332 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3334 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3335 (void) dispatch(os, actual._dataStart, nextKey);
3336 end = nextKey._tokenstart;
3339 processRegion(oldStart, nextKey._tokenstart);
3340 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3342 oldStart = nextKey._dataEnd+1;
3344 // now nextKey is either invalid or is outside of actual._dataEnd
3345 // output the remaining and discard myself
3346 if (oldStart <= end) {
3347 processRegion(oldStart, end);
3349 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3351 // This is the normal case.
3352 // But if using the firstlanguage, the closing may be missing
3354 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3356 if (actual._dataEnd < end)
3357 output_end = interval_.nextNotIgnored(actual._dataEnd);
3358 else if (interval_.par.size() > (size_t) end)
3359 output_end = interval_.nextNotIgnored(end);
3361 output_end = interval_.par.size();
3362 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3363 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3365 // Remove possible empty data
3366 int dstart = interval_.nextNotIgnored(actual._dataStart);
3367 while (interval_.isOpeningPar(dstart) == 1) {
3368 interval_.addIntervall(dstart, dstart+1);
3369 int dend = interval_.findclosing(dstart+1, output_end);
3370 interval_.addIntervall(dend, dend+1);
3371 dstart = interval_.nextNotIgnored(dstart+1);
3373 if (dstart < output_end)
3374 interval_.output(os, output_end);
3376 interval_.addIntervall(0, end);
3378 interval_.addIntervall(actual._tokenstart, end);
3382 string splitOnKnownMacros(string par, bool isPatternString)
3385 LatexInfo li(par, isPatternString);
3386 // LYXERR(Debug::INFO, "Berfore split: " << par);
3387 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3389 DummyKey._tokensize = 0;
3390 DummyKey._dataStart = 0;
3391 DummyKey._dataEnd = par.length();
3392 DummyKey.disabled = true;
3393 int firstkeyIdx = li.getFirstKey();
3395 if (firstkeyIdx >= 0) {
3396 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3397 DummyKey._tokenstart = firstKey._tokenstart;
3399 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3400 // Use dummy firstKey
3401 firstKey = DummyKey;
3402 (void) li.setNextKey(firstkeyIdx);
3405 if (par.substr(firstKey._dataStart, 2) == "% ")
3406 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3408 nextkeyIdx = li.process(os, firstKey);
3409 while (nextkeyIdx >= 0) {
3410 // Check for a possible gap between the last
3411 // entry and this one
3412 int datastart = li.nextNotIgnored(firstKey._dataStart);
3413 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3414 if ((nextKey._tokenstart > datastart)) {
3416 firstKey._dataStart = datastart;
3417 firstKey._dataEnd = par.length();
3418 (void) li.setNextKey(nextkeyIdx);
3419 // Fake the last opened parenthesis
3420 li.setForDefaultLang(firstKey);
3421 nextkeyIdx = li.process(os, firstKey);
3424 if (nextKey.keytype != KeyInfo::isMain) {
3425 firstKey._dataStart = datastart;
3426 firstKey._dataEnd = nextKey._dataEnd+1;
3427 (void) li.setNextKey(nextkeyIdx);
3428 li.setForDefaultLang(firstKey);
3429 nextkeyIdx = li.process(os, firstKey);
3432 nextkeyIdx = li.process(os, nextKey);
3436 // Handle the remaining
3437 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3438 firstKey._dataEnd = par.length();
3440 if ((firstKey._dataStart < firstKey._dataEnd) &&
3441 (par[firstKey._dataStart] != '}')) {
3442 li.setForDefaultLang(firstKey);
3443 (void) li.process(os, firstKey);
3446 // return string definitelly impossible to match, but should be known
3449 s = par; /* no known macros found */
3450 // LYXERR(Debug::INFO, "After split: " << s);
3455 * Try to unify the language specs in the latexified text.
3456 * Resulting modified string is set to "", if
3457 * the searched tex does not contain all the features in the search pattern
3459 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3461 static Features regex_f;
3462 static int missed = 0;
3463 static bool regex_with_format = false;
3465 int parlen = par.length();
3467 while ((parlen > 0) && (par[parlen-1] == '\n')) {
3471 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3472 // Happens to be there in case of description or labeling environment
3478 // Split the latex input into pieces which
3479 // can be digested by our search engine
3480 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3481 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3482 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3483 string doclang = pbuf->params().language->polyglossia();
3484 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3486 bool toIgnoreLang = true;
3487 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3489 if (sub.str(2) != doclang) {
3490 toIgnoreLang = false;
3494 setIgnoreFormat("language", toIgnoreLang, false);
3497 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3498 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3501 result = par.substr(0, parlen);
3502 if (isPatternString) {
3505 regex_f = identifyFeatures(result);
3506 string features = "";
3507 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3508 string a = it->first;
3509 regex_with_format = true;
3510 features += " " + a;
3511 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3513 LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3516 } else if (regex_with_format) {
3517 Features info = identifyFeatures(result);
3518 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3519 string a = it->first;
3520 bool b = it->second;
3521 if (b && ! info[a]) {
3523 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3530 // LYXERR(Debug::INFO, "No regex formats");
3536 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3537 static void identifyClosing(string & t, bool ignoreformat)
3540 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3541 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3543 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3545 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3547 if (! ignoreformat) {
3548 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3556 static int num_replaced = 0;
3557 static bool previous_single_replace = true;
3559 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3562 if (regexp_str.empty() || regexp2_str.empty()) {
3563 regexIsValid = false;
3564 regexError = "Invalid empty regex";
3567 // Handle \w properly
3568 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3569 if (! opt.casesensitive) {
3570 popts |= QRegularExpression::CaseInsensitiveOption;
3572 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3573 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3575 if (regexp.isValid() && regexp2.isValid()) {
3576 regexIsValid = true;
3577 // Check '{', '}' pairs inside the regex
3580 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3581 char c = par_as_string[i];
3588 else if (c == '}') {
3595 if (balanced != 0) {
3596 regexIsValid = false;
3597 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3601 regexIsValid = false;
3602 if (!regexp.isValid())
3603 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3605 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3608 (void)par_as_string;
3609 if (opt.casesensitive) {
3610 regexp = regex(regexp_str);
3611 regexp2 = regex(regexp2_str);
3614 regexp = regex(regexp_str, std::regex_constants::icase);
3615 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3620 static void modifyRegexForMatchWord(string &t)
3623 regex wordre("(\\\\)*((\\.|\\\\b))");
3626 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3628 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3631 else if (sub.str(2) == "\\\\b")
3633 if (lastpos < (size_t) sub.position(2))
3634 s += t.substr(lastpos, sub.position(2) - lastpos);
3636 lastpos = sub.position(2) + sub.length(2);
3639 s = "\\b" + t + "\\b";
3643 else if (lastpos < t.length())
3644 s += t.substr(lastpos, t.length() - lastpos);
3645 t = "\\b" + s + "\\b";
3648 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3649 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3651 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3652 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3654 CreateRegexp(opt, "", "", "");
3657 use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3658 if (opt.replace_all && previous_single_replace) {
3659 previous_single_replace = false;
3662 else if (!opt.replace_all) {
3663 num_replaced = 0; // count number of replaced strings
3664 previous_single_replace = true;
3666 // When using regexp, braces are hacked already by escape_for_regex()
3667 par_as_string = convertLF2Space(ds, opt.ignoreformat);
3669 size_t lead_size = 0;
3670 // correct the language settings
3671 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3672 if (par_as_string.empty()) {
3673 CreateRegexp(opt, "", "", "");
3676 opt.matchAtStart = false;
3678 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3679 if (opt.ignoreformat) {
3683 lead_size = identifyLeading(par_as_string);
3685 lead_as_string = par_as_string.substr(0, lead_size);
3686 string lead_as_regex_string = string2regex(lead_as_string);
3687 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3688 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3689 /* Handle whole words too in this case
3691 if (opt.matchword) {
3692 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3693 opt.matchword = false;
3695 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3696 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3697 CreateRegexp(opt, regexp_str, regexp2_str);
3699 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3700 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3704 if (!opt.ignoreformat) {
3705 lead_size = identifyLeading(par_as_string);
3706 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3707 lead_as_string = par_as_string.substr(0, lead_size);
3708 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3711 // Here we are using regexp
3712 LASSERT(use_regexp, /**/);
3714 string lead_as_regexp;
3715 if (lead_size > 0) {
3716 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3717 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3718 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3719 par_as_string = par_as_string_nolead;
3720 LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3721 LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3723 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3724 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3725 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3726 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3728 size_t lng = par_as_string.size();
3729 if (!opt.ignoreformat) {
3730 // Remove extra '\}' at end if not part of \{\.\}
3732 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3734 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3743 if (lng < par_as_string.size())
3744 par_as_string.resize(lng);
3746 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3747 if ((lng > 0) && (par_as_string[0] == '^')) {
3748 par_as_string = par_as_string.substr(1);
3750 opt.matchAtStart = true;
3752 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3753 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3754 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3756 // If entered regexp must match at begin of searched string buffer
3757 // Kornel: Added parentheses to use $1 for size of the leading string
3761 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3762 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3763 // so the convert has no effect in that case
3764 for (int i = 7; i > 0; --i) {
3765 string orig = "\\\\" + std::to_string(i);
3766 string dest = "\\" + std::to_string(i+2);
3767 while (regex_replace(par_as_string, par_as_string, orig, dest));
3769 if (opt.matchword) {
3770 modifyRegexForMatchWord(par_as_string);
3771 // opt.matchword = false;
3773 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3774 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3776 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3777 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3778 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3782 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3786 mres.searched_size = len;
3788 docstring docstr = stringifyFromForSearch(opt, cur, len);
3790 str = convertLF2Space(docstr, opt.ignoreformat);
3791 if (!opt.ignoreformat) {
3792 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3793 // remove closing '}' and '\n' to allow for use of '$' in regex
3794 size_t lng = str.size();
3795 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3797 if (lng != str.size()) {
3798 str = str.substr(0, lng);
3800 // Replace occurences of '~' to ' '
3801 static std::regex specialChars { R"(~)" };
3802 str = std::regex_replace(str, specialChars, R"( )" );
3805 mres.match_len = -1;
3808 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3810 LASSERT(use_regexp, /**/);
3812 // use_regexp always true
3813 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3815 QString qstr = QString::fromStdString(str);
3816 QRegularExpression const *p_regexp;
3817 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3818 if (at_begin == MatchStringAdv::MatchFromStart) {
3821 p_regexp = ®exp2;
3823 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3824 if (!match.hasMatch())
3827 regex const *p_regexp;
3828 regex_constants::match_flag_type flags;
3829 if (at_begin == MatchStringAdv::MatchFromStart) {
3830 flags = regex_constants::match_continuous;
3833 flags = regex_constants::match_default;
3834 p_regexp = ®exp2;
3836 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3837 if (re_it == sregex_iterator())
3839 match_results<string::const_iterator> const & m = *re_it;
3841 // Whole found string, including the leading
3842 // std: m[0].second - m[0].first
3843 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3845 // Size of the leading string
3846 // std: m[1].second - m[1].first
3847 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3848 int leadingsize = 0;
3850 if (match.lastCapturedIndex() > 0) {
3851 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3856 leadingsize = m[1].second - m[1].first;
3860 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3861 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3862 // because of different number of closing at end of string
3863 // we have to 'unify' the length of the post-match.
3864 // Done by ignoring closing parenthesis and linefeeds at string end
3865 int matchend = match.capturedEnd(0);
3866 size_t strsize = qstr.size();
3867 if (!opt.ignoreformat) {
3868 while (mres.match_len > 1) {
3869 QChar c = qstr.at(matchend - 1);
3870 if ((c == '\n') || (c == '}') || (c == '{')) {
3877 while (strsize > (size_t) match.capturedEnd(0)) {
3878 QChar c = qstr.at(strsize-1);
3879 if ((c == '\n') || (c == '}')) {
3886 // LYXERR0(qstr.toStdString());
3887 mres.match2end = strsize - matchend;
3888 mres.pos = match.capturedStart(2);
3890 mres.match_prefix = m[2].second - m[2].first;
3891 mres.match_len = m[0].second - m[2].second;
3892 // ignore closing parenthesis and linefeeds at string end
3893 size_t strend = m[0].second - m[0].first;
3894 int matchend = strend;
3895 size_t strsize = str.size();
3896 if (!opt.ignoreformat) {
3897 while (mres.match_len > 1) {
3898 char c = str.at(matchend - 1);
3899 if ((c == '\n') || (c == '}') || (c == '{')) {
3906 while (strsize > strend) {
3907 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3915 mres.match2end = strsize - matchend;
3916 mres.pos = m[2].first - m[0].first;;
3918 if (mres.match2end < 0)
3920 mres.leadsize = leadingsize;
3922 if (mres.match_len > 0) {
3923 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3924 mres.result.push_back(a0);
3925 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3926 mres.result.push_back(match.captured(i).toStdString());
3930 if (mres.match_len > 0) {
3931 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3932 mres.result.push_back(a0);
3933 for (size_t i = 3; i < m.size(); i++) {
3934 mres.result.push_back(m[i]);
3943 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3945 MatchResult mres = findAux(cur, len, at_begin);
3946 LYXERR(Debug::FINDVERBOSE,
3947 "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3948 << ", matchAtStart=" << opt.matchAtStart
3949 << ", inTexted=" << cur.inTexted());
3950 if (mres.match_len > 0) {
3951 if (opt.matchAtStart) {
3952 if (cur.pos() > 0 || mres.match_prefix > 0)
3960 static bool simple_replace(string &t, string from, string to)
3962 regex repl("(\\\\)*(" + from + ")");
3966 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3968 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3970 if (lastpos < (size_t) sub.position(2))
3971 s += t.substr(lastpos, sub.position(2) - lastpos);
3973 lastpos = sub.position(2) + sub.length(2);
3977 else if (lastpos < t.length())
3978 s += t.substr(lastpos, t.length() - lastpos);
3984 string MatchStringAdv::convertLF2Space(docstring const &s, bool ignore_format) const
3986 // Using original docstring to handle '\n'
3988 if (s.size() == 0) return "";
3992 size_t end = s.size() - 1;
3993 if (!ignore_format) {
3994 while (s[start] == '\n' && start <= end)
3996 while (end >= start && s[end] == '\n')
3998 if (start >= end + 1)
4002 bool dospace = true;
4004 pos = s.find('\n', start);
4006 t << lyx::to_utf8(s.substr(start, end + 1 - start));
4009 if (!ignore_format) {
4010 if ((pos > start + 1) &&
4014 if ((pos > start + 2) &&
4015 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4016 s[pos-3] == '~' || isSpace(s[pos-3]))) {
4017 // discard "\\\\\n", do not replace with space
4021 else if (pos > start) {
4022 if (s[pos-1] == '%') {
4024 while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4026 if ((pos > start+skip) &&
4027 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4028 s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4029 // discard '%%%%%\n'
4033 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4035 skip = 0; // remove the '\n' only
4043 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4047 } while (start <= end);
4051 docstring stringifyFromCursor(DocIterator const & cur, int len)
4053 LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4054 if (cur.inTexted()) {
4055 Paragraph const & par = cur.paragraph();
4056 // TODO what about searching beyond/across paragraph breaks ?
4057 // TODO Try adding a AS_STR_INSERTS as last arg
4058 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4059 int(par.size()) : cur.pos() + len;
4060 // OutputParams runparams(&cur.buffer()->params().encoding());
4061 OutputParams runparams(encodings.fromLyXName("utf8"));
4062 runparams.nice = true;
4063 setFindParams(runparams);
4064 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4065 if (ignoreFormats.getDeleted()) {
4066 option |= AS_STR_SKIPDELETE;
4067 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4070 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4072 if (ignoreFormats.getNonContent()) {
4073 runparams.find_add_feature(OutputParams::SearchNonOutput);
4075 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4076 << cur << ", from pos: " << cur.pos() << ", end: " << end);
4077 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4079 &runparams), false));
4080 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4082 } else if (cur.inMathed()) {
4083 CursorSlice cs = cur.top();
4084 MathData md = cs.cell();
4085 MathData::const_iterator it_end =
4086 (( len == -1 || cs.pos() + len > int(md.size()))
4088 : md.begin() + cs.pos() + len );
4090 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4092 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4093 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4096 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4100 /** Computes the LaTeX export of buf starting from cur and ending len positions
4101 * after cur, if len is positive, or at the paragraph or innermost inset end
4104 docstring latexifyFromCursor(DocIterator const & cur, int len)
4107 LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4108 LYXERR(Debug::FINDVERBOSE, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4109 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4111 Buffer const & buf = *cur.buffer();
4113 odocstringstream ods;
4115 //OutputParams runparams(&buf.params().encoding());
4116 OutputParams runparams(encodings.fromLyXName("utf8"));
4117 runparams.nice = false;
4118 setFindParams(runparams);
4119 if (ignoreFormats.getDeleted()) {
4120 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4123 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4125 if (ignoreFormats.getNonContent()) {
4126 runparams.find_add_feature(OutputParams::SearchNonOutput);
4129 if (cur.inTexted()) {
4130 // @TODO what about searching beyond/across paragraph breaks ?
4131 pos_type endpos = cur.paragraph().size();
4132 if (len != -1 && endpos > cur.pos() + len)
4133 endpos = cur.pos() + len;
4134 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4135 string(), cur.pos(), endpos, true);
4136 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4138 } else if (cur.inMathed()) {
4139 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4140 for (int s = cur.depth() - 1; s >= 0; --s) {
4141 CursorSlice const & cs = cur[s];
4142 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4143 TeXMathStream ws(os);
4144 cs.asInsetMath()->asHullInset()->header_write(ws);
4149 CursorSlice const & cs = cur.top();
4150 MathData md = cs.cell();
4151 MathData::const_iterator it_end =
4152 ((len == -1 || cs.pos() + len > int(md.size()))
4154 : md.begin() + cs.pos() + len);
4156 for (MathData::const_iterator it = md.begin() + cs.pos();
4160 ods << asString(md2);
4161 // Retrieve the math environment type, and add '$' or '$]'
4162 // or others (\end{equation}) accordingly
4163 for (int s = cur.depth() - 1; s >= 0; --s) {
4164 CursorSlice const & cs2 = cur[s];
4165 InsetMath * inset = cs2.asInsetMath();
4166 if (inset && inset->asHullInset()) {
4167 TeXMathStream ws(os);
4168 inset->asHullInset()->footer_write(ws);
4172 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4174 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4179 #if defined(ResultsDebug)
4181 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4183 LYXERR0( "from:\t\t\t" << from);
4185 if (mres.pos_len > 0) {
4187 status = "FINALSEARCH";
4190 if (mres.match_len > 0) {
4191 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4192 status = "Good Match";
4194 status = "Matched in";
4197 status = "MissedSearch";
4200 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4201 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4202 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4203 if ((mres.pos > 0) || (mres.match_prefix > 0))
4204 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4205 for (size_t i = 0; i < mres.result.size(); i++)
4206 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4208 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4210 #define displayMres(s, txt, cur)
4213 /** Finalize an advanced find operation, advancing the cursor to the innermost
4214 ** position that matches, plus computing the length of the matching text to
4216 ** Return the cur.pos() difference between start and end of found match
4218 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4220 // Search the foremost position that matches (avoids find of entire math
4221 // inset when match at start of it)
4222 DocIterator old_cur(cur.buffer());
4224 static MatchResult fail = MatchResult();
4225 MatchResult max_match;
4226 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4227 // Happens with e.g. hyperlinks
4228 // either one sees "http://www.bla.bla" or nothing
4229 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4230 // and although we search for only 3 chars, we find the whole hyperlink inset
4231 MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4232 if (!match.opt.forward && match.opt.ignoreformat) {
4233 if (expected.pos > 0)
4236 LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4237 if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4238 // Search for deepest match
4240 max_match = expected;
4242 size_t d = cur.depth();
4246 if (cur.depth() < d)
4248 if (cur.depth() == d)
4251 while (cur && cur.depth() > lastd) {
4252 lastd = cur.depth();
4253 mres = match(cur, -1, at_begin);
4254 displayMres(mres, "Checking innermost", cur);
4255 if (mres.match_len > 0)
4260 if (mres.match_len < expected.match_len)
4268 // (expected.match_len <= 0)
4269 mres = match(cur, -1, MatchStringAdv::MatchFromStart); /* match valid only if not searching whole words */
4270 displayMres(mres, "Start with negative match", cur);
4273 // Only now we are really at_begin
4274 if ((max_match.match_len <= 0) ||
4275 (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4277 LYXERR(Debug::FINDVERBOSE, "Ok");
4279 // Compute the match length
4281 if (cur.pos() + len > cur.lastpos())
4284 LASSERT(match.use_regexp, /**/);
4287 int maxl = cur.lastpos() - cur.pos();
4288 // Greedy behaviour while matching regexps
4289 while (maxl > minl) {
4291 mres2 = match(cur, len, at_begin);
4292 displayMres(mres2, "Finalize loop", cur);
4293 int actual_match_len = mres2.match_len;
4294 if (actual_match_len >= max_match.match_len) {
4295 // actual_match_len > max_match _can_ happen,
4296 // if the search area splits
4297 // some following word so that the regex
4298 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4300 // This means, the len value is too big
4301 actual_match_len = max_match.match_len;
4303 max_match.match_len = actual_match_len;
4305 if (maxl - minl < 4)
4306 len = (maxl + minl)/2;
4308 len = minl + (maxl - minl + 3)/4;
4311 // (actual_match_len < max_match.match_len)
4313 len = (maxl + minl)/2;
4318 // Search for real start of matched characters
4320 MatchResult actual_match;
4323 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4324 if (cur.depth() < old_cur.depth()) {
4326 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4329 if (cur.pos() != old_cur.pos()) {
4330 // OK, forwarded 1 pos in actual inset
4331 actual_match = match(cur, len-1, at_begin);
4332 if (actual_match.match_len == max_match.match_len) {
4333 // Ha, got it! The shorter selection has the same match length
4336 max_match = actual_match;
4339 // OK, the shorter selection matches less chars, revert to previous value
4345 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4346 actual_match = match(cur, len, at_begin);
4347 if (actual_match.match_len == max_match.match_len) {
4349 max_match = actual_match;
4356 max_match.pos_len = len;
4357 displayMres(max_match, "SEARCH RESULT", cur)
4364 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4369 DocIterator orig_cur; // to be used if repeat not successful
4370 MatchResult orig_mres;
4374 } while (cur.depth() > orig_cur.depth());
4376 while (!theApp()->longOperationCancelled() && cur) {
4377 //(void) findAdvForwardInnermost(cur);
4378 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4379 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4380 string msg = "Starting";
4383 displayMres(mres, msg + " findForwardAdv", cur)
4384 int match_len = mres.match_len;
4385 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4386 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4389 if (match_len <= 0) {
4394 // This should exit nested insets, if any, or otherwise undefine the currsor.
4395 cur.pos() = cur.lastpos();
4397 LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4400 else { // match_len > 0
4401 // Try to find the begin of searched string
4403 int firstInvalid = cur.lastpos() - cur.pos();
4405 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4406 int incrcur = (firstInvalid + 1 )*3/4;
4407 if (incrcur < incrmatch)
4408 increment = incrcur;
4410 increment = incrmatch;
4414 LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4415 while (increment > 0) {
4416 DocIterator old_cur = cur;
4417 if (cur.pos() + increment >= cur.lastpos()) {
4421 cur.pos() = cur.pos() + increment;
4422 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4423 displayMres(mres2, "findForwardAdv loop", cur)
4424 switch (interpretMatch(mres, mres2)) {
4425 case MatchResult::newIsTooFar:
4426 // behind the expected match
4427 firstInvalid = increment;
4431 case MatchResult::newIsBetter:
4432 // not reached yet, but cur.pos()+increment is better
4434 firstInvalid -= increment;
4435 if (increment > firstInvalid*3/4)
4436 increment = firstInvalid*3/4;
4437 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4438 if (increment >= mres2.match_prefix)
4439 increment = (mres2.match_prefix+1)*3/4;
4444 // Handle not like MatchResult::newIsTooFar
4445 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4447 increment = increment*3/4;
4452 if (mres.match_len > 0) {
4453 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4454 // The match seems to indicate some deeper level
4462 else if (repeat > 0) {
4463 // should never be reached.
4467 // LYXERR0("Leaving first loop");
4468 LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4469 MatchResult found_match = findAdvFinalize(cur, match, mres);
4470 if (found_match.match_len > 0) {
4471 match.FillResults(found_match);
4472 return found_match.pos_len;
4475 // try next possible match
4486 /// Find the most backward consecutive match within same paragraph while searching backwards.
4487 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4489 DocIterator cur_begin = cur;
4490 cur_begin.pos() = 0;
4491 DocIterator tmp_cur = cur;
4492 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4493 Inset & inset = cur.inset();
4494 for (; cur != cur_begin; cur.backwardPos()) {
4495 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4496 DocIterator new_cur = cur;
4497 new_cur.backwardPos();
4498 if (new_cur == cur || &new_cur.inset() != &inset
4499 || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4501 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4502 if (new_mr.match_len == mr.match_len)
4506 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4512 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4516 // Backup of original position
4517 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4518 if (cur == cur_begin)
4521 DocIterator cur_orig(cur);
4522 bool pit_changed = false;
4525 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4527 if (found_match.match_len > 0) {
4529 cur.pos() = cur.lastpos();
4531 cur.pos() = cur_orig.pos();
4532 LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4533 DocIterator cur_prev_iter;
4535 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4536 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4537 << (found_match.match_len > 0) << ", cur: " << cur);
4538 if (found_match.match_len > 0) {
4539 MatchResult found_mr = findMostBackwards(cur, match, found_match);
4540 if (found_mr.pos_len > 0) {
4541 match.FillResults(found_mr);
4542 return found_mr.pos_len;
4546 // Stop if begin of document reached
4547 if (cur == cur_begin)
4549 cur_prev_iter = cur;
4553 if (cur == cur_begin)
4560 } while (!theApp()->longOperationCancelled());
4568 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4569 DocIterator const & cur, int len)
4571 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4573 if (!opt.ignoreformat)
4574 return latexifyFromCursor(cur, len);
4576 return stringifyFromCursor(cur, len);
4580 FindAndReplaceOptions::FindAndReplaceOptions(
4581 docstring const & _find_buf_name, bool _casesensitive,
4582 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4583 docstring const & _repl_buf_name, bool _keep_case,
4584 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4585 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4586 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4587 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4595 /** Check if 'len' letters following cursor are all non-lowercase */
4596 static bool allNonLowercase(Cursor const & cur, int len)
4598 pos_type beg_pos = cur.selectionBegin().pos();
4599 pos_type end_pos = cur.selectionBegin().pos() + len;
4600 if (len > cur.lastpos() + 1 - beg_pos) {
4601 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4602 len = cur.lastpos() + 1 - beg_pos;
4603 end_pos = beg_pos + len;
4605 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4606 if (isLowerCase(cur.paragraph().getChar(pos)))
4612 /** Check if first letter is upper case and second one is lower case */
4613 static bool firstUppercase(Cursor const & cur)
4616 pos_type pos = cur.selectionBegin().pos();
4617 if (pos >= cur.lastpos() - 1) {
4618 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4621 ch1 = cur.paragraph().getChar(pos);
4622 ch2 = cur.paragraph().getChar(pos + 1);
4623 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4624 LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4625 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4626 << ch2 << "(" << char(ch2) << ")"
4627 << ", result=" << result << ", cur=" << cur);
4632 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4634 ** \fixme What to do with possible further paragraphs in replace buffer ?
4636 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4638 ParagraphList::iterator pit = buffer.paragraphs().begin();
4639 LASSERT(!pit->empty(), /**/);
4640 pos_type right = pos_type(1);
4641 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4642 right = pit->size();
4643 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4647 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4649 // Should replace the string "$" + std::to_string(matchnum) with replacement
4650 // if the char '$' is not prefixed with odd number of char '\\'
4651 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4655 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4657 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4659 int num = stoi(sub.str(3), nullptr, 10);
4660 if (num >= maxmatchnum)
4662 if (lastpos < (size_t) sub.position(2))
4663 s += t.substr(lastpos, sub.position(2) - lastpos);
4664 s += replacements[num];
4665 lastpos = sub.position(2) + sub.length(2);
4669 else if (lastpos < t.length())
4670 s += t.substr(lastpos, t.length() - lastpos);
4676 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4678 Cursor & cur = bv->cursor();
4679 if (opt.repl_buf_name.empty()
4680 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4681 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4684 DocIterator sel_beg = cur.selectionBegin();
4685 DocIterator sel_end = cur.selectionEnd();
4686 if (&sel_beg.inset() != &sel_end.inset()
4687 || sel_beg.pit() != sel_end.pit()
4688 || sel_beg.idx() != sel_end.idx())
4690 int sel_len = sel_end.pos() - sel_beg.pos();
4691 LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4692 << ", sel_len: " << sel_len << endl);
4695 LASSERT(sel_len > 0, return 0);
4697 if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4700 // Build a copy of the replace buffer, adapted to the KeepCase option
4701 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4703 repl_buffer_orig.write(oss);
4704 string lyx = oss.str();
4705 if (matchAdv.valid_matches > 0)
4706 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4707 Buffer repl_buffer(string(), false);
4708 repl_buffer.setInternal(true);
4709 repl_buffer.setUnnamed(true);
4710 LASSERT(repl_buffer.readString(lyx), return 0);
4711 if (opt.keep_case && sel_len >= 2) {
4712 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4713 if (cur.inTexted()) {
4714 if (firstUppercase(cur))
4715 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4716 else if (allNonLowercase(cur, sel_len))
4717 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4720 cap::cutSelection(cur, false);
4721 if (cur.inTexted()) {
4722 repl_buffer.changeLanguage(
4723 repl_buffer.language(),
4724 cur.getFont().language());
4725 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4726 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4727 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4728 repl_buffer.params().documentClassPtr(),
4729 repl_buffer.params().authors(),
4730 bv->buffer().errorList("Paste"));
4731 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4732 sel_len = repl_buffer.paragraphs().begin()->size();
4733 } else if (cur.inMathed()) {
4734 odocstringstream ods;
4736 // OutputParams runparams(&repl_buffer.params().encoding());
4737 OutputParams runparams(encodings.fromLyXName("utf8"));
4738 runparams.nice = false;
4739 setFindParams(runparams);
4740 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4741 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4742 docstring repl_latex = ods.str();
4743 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4745 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4746 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4747 repl_latex = from_utf8(s);
4748 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4749 MathData ar(cur.buffer());
4750 asArray(repl_latex, ar, Parse::NORMAL);
4752 sel_len = ar.size();
4753 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4755 if (cur.pos() >= sel_len)
4756 cur.pos() -= sel_len;
4759 LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4760 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4761 bv->processUpdateFlags(Update::Force);
4765 static bool isWordChar(char_type c)
4767 return isLetterChar(c) || isNumberChar(c);
4770 /// Perform a FindAdv operation.
4771 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4776 // e.g., when invoking word-findadv from mini-buffer wither with
4777 // wrong options syntax or before ever opening advanced F&R pane
4778 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4782 MatchStringAdv matchAdv(bv->buffer(), opt);
4784 if (!matchAdv.regexIsValid) {
4785 bv->message(lyx::from_utf8(matchAdv.regexError));
4789 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4791 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4792 num_replaced += findAdvReplace(bv, opt, matchAdv);
4795 if (opt.matchword && cur.pos() > 0) { // Skip word-characters if we are in the mid of a word
4796 if (cur.inTexted()) {
4797 Paragraph const & par = cur.paragraph();
4798 int len_limit, new_pos;
4799 if (cur.lastpos() < par.size())
4800 len_limit = cur.lastpos();
4802 len_limit = par.size();
4803 for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4804 if (!isWordChar(par.getChar(new_pos)))
4807 if (new_pos > cur.pos())
4808 cur.pos() = new_pos;
4810 else if (cur.inMathed()) {
4811 // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4812 // I am not sure, we should consider the selection
4813 bool sel = bv->cursor().selection();
4814 if (!sel && cur.pos() < cur.lastpos()) {
4815 CursorSlice const & cs = cur.top();
4816 MathData md = cs.cell();
4818 MathData::const_iterator it_end = md.end();
4820 // Start the check with one character before actual cursor position
4821 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4824 docstring inp = asString(md2);
4825 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4826 if (!isWordChar(inp[len]))
4829 // len == 0 means previous char was a word separator
4830 // len == 1 search starts with a word separator
4831 // len == 2 ... we have to skip len -1 chars
4833 cur.pos() = cur.pos() + len - 1;
4836 opt.matchword = false;
4838 pos_len = findForwardAdv(cur, matchAdv);
4841 pos_len = findBackwardsAdv(cur, matchAdv);
4842 } catch (exception & ex) {
4843 bv->message(from_utf8(ex.what()));
4848 if (num_replaced > 0) {
4849 switch (num_replaced)
4852 bv->message(_("One match has been replaced."));
4855 bv->message(_("Two matches have been replaced."));
4858 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4864 bv->message(_("Match not found."));
4869 if (num_replaced > 0)
4870 bv->message(_("Match has been replaced."));
4872 bv->message(_("Match found."));
4874 if (cur.pos() + pos_len > cur.lastpos()) {
4875 // Prevent crash in bv->putSelectionAt()
4876 // Should never happen, maybe LASSERT() here?
4877 pos_len = cur.lastpos() - cur.pos();
4879 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4880 bv->putSelectionAt(cur, pos_len, !opt.forward);
4886 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4888 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4889 << opt.casesensitive << ' '
4890 << opt.matchword << ' '
4891 << opt.forward << ' '
4892 << opt.expandmacros << ' '
4893 << opt.ignoreformat << ' '
4894 << opt.replace_all << ' '
4895 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4896 << opt.keep_case << ' '
4897 << int(opt.scope) << ' '
4900 LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4906 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4908 // LYXERR(Debug::FINDVERBOSE, "parsing");
4912 while (line != "EOSS") {
4916 if (is.eof()) // Tolerate malformed request
4920 // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4921 opt.find_buf_name = from_utf8(s);
4922 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4923 is.get(); // Waste space before replace string
4926 while (line != "EOSS") {
4930 if (is.eof()) // Tolerate malformed request
4934 // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
4935 opt.repl_buf_name = from_utf8(s);
4936 is >> opt.keep_case;
4939 opt.scope = FindAndReplaceOptions::SearchScope(i);
4941 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4944 LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4945 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4946 << opt.scope << ' ' << opt.restr);