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 <QtCore> // sets QT_VERSION
61 #if (QT_VERSION >= 0x050000)
62 #include <QRegularExpression>
72 using namespace lyx::support;
76 typedef unordered_map<string, string> AccentsMap;
77 typedef unordered_map<string,string>::const_iterator AccentsIterator;
78 static AccentsMap accents = unordered_map<string, string>();
80 // Helper class for deciding what should be ignored
84 IgnoreFormats() = default;
86 bool getFamily() const { return ignoreFamily_; }
88 bool getSeries() const { return ignoreSeries_; }
90 bool getShape() const { return ignoreShape_; }
92 bool getSize() const { return ignoreSize_; }
94 bool getUnderline() const { return ignoreUnderline_; }
96 bool getMarkUp() const { return ignoreMarkUp_; }
98 bool getStrikeOut() const { return ignoreStrikeOut_; }
100 bool getSectioning() const { return ignoreSectioning_; }
102 bool getFrontMatter() const { return ignoreFrontMatter_; }
104 bool getColor() const { return ignoreColor_; }
106 bool getLanguage() const { return ignoreLanguage_; }
108 bool getDeleted() const { return ignoreDeleted_; }
110 void setIgnoreDeleted(bool value);
112 bool getNonContent() const { return searchNonContent_; }
114 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
118 bool ignoreFamily_ = false;
120 bool ignoreSeries_ = false;
122 bool ignoreShape_ = false;
124 bool ignoreSize_ = true;
126 bool ignoreUnderline_ = false;
128 bool ignoreMarkUp_ = false;
130 bool ignoreStrikeOut_ = false;
132 bool ignoreSectioning_ = false;
134 bool ignoreFrontMatter_ = false;
136 bool ignoreColor_ = false;
138 bool ignoreLanguage_ = false;
139 bool userSelectedIgnoreLanguage_ = false;
141 bool ignoreDeleted_ = true;
143 bool searchNonContent_ = true;
146 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
148 if (type == "color") {
149 ignoreColor_ = value;
151 else if (type == "language") {
153 userSelectedIgnoreLanguage_ = value;
154 ignoreLanguage_ = value;
157 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
159 else if (type == "sectioning") {
160 ignoreSectioning_ = value;
161 ignoreFrontMatter_ = value;
163 else if (type == "font") {
164 ignoreSeries_ = value;
165 ignoreShape_ = value;
166 ignoreFamily_ = value;
168 else if (type == "series") {
169 ignoreSeries_ = value;
171 else if (type == "shape") {
172 ignoreShape_ = value;
174 else if (type == "size") {
177 else if (type == "family") {
178 ignoreFamily_ = value;
180 else if (type == "markup") {
181 ignoreMarkUp_ = value;
183 else if (type == "underline") {
184 ignoreUnderline_ = value;
186 else if (type == "strike") {
187 ignoreStrikeOut_ = value;
189 else if (type == "deleted") {
190 ignoreDeleted_ = value;
192 else if (type == "non-output-content") {
193 searchNonContent_ = !value;
197 // The global variable that can be changed from outside
198 IgnoreFormats ignoreFormats;
201 void setIgnoreFormat(string const & type, bool value, bool fromUser)
203 ignoreFormats.setIgnoreFormat(type, value, fromUser);
209 bool parse_bool(docstring & howto, bool const defvalue = false)
214 howto = split(howto, var, ' ');
222 MatchString(docstring const & s, bool cs, bool mw)
223 : str(s), case_sens(cs), whole_words(mw)
226 // returns true if the specified string is at the specified position
227 // del specifies whether deleted strings in ct mode will be considered
228 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
230 return par.find(str, case_sens, whole_words, pos, del);
238 // match whole words only
243 int findForward(DocIterator & cur, DocIterator const endcur,
244 MatchString const & match,
245 bool find_del = true, bool onlysel = false)
247 for (; cur; cur.forwardChar()) {
248 if (onlysel && endcur.pit() == cur.pit()
249 && endcur.idx() == cur.idx() && endcur.pos() < cur.pos())
251 if (cur.inTexted()) {
252 int len = match(cur.paragraph(), cur.pos(), find_del);
261 int findBackwards(DocIterator & cur, DocIterator const endcur,
262 MatchString const & match,
263 bool find_del = true, bool onlysel = false)
267 if (onlysel && endcur.pit() == cur.pit()
268 && endcur.idx() == cur.idx() && endcur.pos() > cur.pos())
270 if (cur.inTexted()) {
271 int len = match(cur.paragraph(), cur.pos(), find_del);
280 bool searchAllowed(docstring const & str)
283 frontend::Alert::error(_("Search error"), _("Search string is empty"));
292 bool findOne(BufferView * bv, docstring const & searchstr,
293 bool case_sens, bool whole, bool forward,
294 bool find_del, bool check_wrap, bool const auto_wrap,
295 bool instant, bool onlysel)
297 // Clean up previous selections with empty searchstr on instant
298 if (searchstr.empty() && instant) {
299 if (bv->cursor().selection()) {
300 bv->setCursor(bv->cursor().selectionBegin());
301 bv->clearSelection();
306 if (!searchAllowed(searchstr))
309 DocIterator const endcur = forward ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin();
311 if (onlysel && bv->cursor().selection()) {
312 docstring const matchstring = bv->cursor().selectionAsString(false);
313 docstring const lcmatchsting = support::lowercase(matchstring);
314 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
315 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
316 "Continue search outside?");
317 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
318 q, 0, 1, _("&Yes"), _("&No"));
319 if (search_answer == 0) {
320 bv->clearSelection();
321 if (findOne(bv, searchstr, case_sens, whole, forward,
322 find_del, check_wrap, auto_wrap, false, false))
329 DocIterator cur = forward
330 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
331 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
333 MatchString const match(searchstr, case_sens, whole);
335 int match_len = forward
336 ? findForward(cur, endcur, match, find_del, onlysel)
337 : findBackwards(cur, endcur, match, find_del, onlysel);
340 bv->putSelectionAt(cur, match_len, !forward);
342 docstring q = _("The search string was not found within the selection.\n"
343 "Continue search outside?");
344 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
345 q, 0, 1, _("&Yes"), _("&No"));
346 if (search_answer == 0) {
347 bv->clearSelection();
348 if (findOne(bv, searchstr, case_sens, whole, forward,
349 find_del, check_wrap, auto_wrap, false, false))
354 else if (check_wrap) {
355 DocIterator cur_orig(bv->cursor());
356 bool wrap = auto_wrap;
360 q = _("End of file reached while searching forward.\n"
361 "Continue searching from the beginning?");
363 q = _("Beginning of file reached while searching backward.\n"
364 "Continue searching from the end?");
365 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
366 q, 0, 1, _("&Yes"), _("&No"));
367 wrap = wrap_answer == 0;
371 bv->cursor().clear();
372 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
374 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
375 bv->cursor().backwardPos();
378 docstring const msg = forward
379 ? _("Search reached end of document, continuing from beginning.")
380 : _("Search reached beginning of document, continuing from end.");
383 bv->clearSelection();
384 if (findOne(bv, searchstr, case_sens, whole, forward,
385 find_del, false, false, false, false))
388 bv->cursor().setCursor(cur_orig);
392 return match_len > 0;
398 int replaceAll(BufferView * bv,
399 docstring const & searchstr, docstring const & replacestr,
400 bool case_sens, bool whole, bool onlysel)
402 Buffer & buf = bv->buffer();
404 if (!searchAllowed(searchstr) || buf.isReadonly())
407 DocIterator startcur = bv->cursor().selectionBegin();
408 DocIterator endcur = bv->cursor().selectionEnd();
409 bool const had_selection = bv->cursor().selection();
411 MatchString const match(searchstr, case_sens, whole);
414 int const rsize = replacestr.size();
415 int const ssize = searchstr.size();
418 cur.setCursor(doc_iterator_begin(&buf));
419 int match_len = findForward(cur, endcur, match, false, onlysel);
420 while (match_len > 0) {
421 // Backup current cursor position and font.
422 pos_type const pos = cur.pos();
423 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
425 int ct_deleted_text = ssize -
426 cur.paragraph().eraseChars(pos, pos + match_len,
427 buf.params().track_changes);
428 cur.paragraph().insert(pos, replacestr, font,
429 Change(buf.params().track_changes
431 : Change::UNCHANGED));
432 for (int i = 0; i < rsize + ct_deleted_text
433 && cur.pos() < cur.lastpos(); ++i)
435 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
436 // Adjust end of selection for replace-all in selection
438 int const offset = rsize - ssize;
439 for (int i = 0; i < offset + ct_deleted_text
440 && endcur.pos() < endcur.lastpos(); ++i)
443 int const offset = ssize - rsize;
444 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
445 endcur.backwardPos();
446 for (int i = 0; i < ct_deleted_text
447 && endcur.pos() < endcur.lastpos(); ++i)
452 match_len = findForward(cur, endcur, match, false, onlysel);
455 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
457 startcur.fixIfBroken();
458 bv->setCursor(startcur);
460 // Reset selection, accounting for changes in selection
462 endcur.fixIfBroken();
463 bv->cursor().resetAnchor();
464 bv->setCursorSelectionTo(endcur);
471 // the idea here is that we are going to replace the string that
472 // is selected IF it is the search string.
473 // if there is a selection, but it is not the search string, then
474 // we basically ignore it. (FIXME We ought to replace only within
476 // if there is no selection, then:
477 // (i) if some search string has been provided, then we find it.
478 // (think of how the dialog works when you hit "replace" the
480 // (ii) if no search string has been provided, then we treat the
481 // word the cursor is in as the search string. (why? i have no
482 // idea.) but this only works in text?
484 // returns the number of replacements made (one, if any) and
485 // whether anything at all was done.
486 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
487 docstring const & replacestr, bool case_sens,
488 bool whole, bool forward, bool findnext, bool wrap,
491 Cursor & cur = bv->cursor();
492 if (!cur.selection() || onlysel) {
493 // no selection, non-empty search string: find it
494 if (!searchstr.empty()) {
495 bool const found = findOne(bv, searchstr, case_sens, whole,
496 forward, true, findnext, wrap, false, onlysel);
497 return make_pair(found, 0);
499 // empty search string
502 return make_pair(false, 0);
503 // select current word and treat it as the search string.
504 // This causes a minor bug as undo will restore this selection,
505 // which the user did not create (#8986).
506 cur.innerText()->selectWord(cur, WHOLE_WORD);
507 searchstr = cur.selectionAsString(false, true);
510 // if we still don't have a search string, report the error
512 if (!searchAllowed(searchstr))
513 return make_pair(false, 0);
515 bool have_selection = cur.selection();
516 docstring const selected = cur.selectionAsString(false, true);
519 ? searchstr == selected
520 : compare_no_case(searchstr, selected) == 0;
522 // no selection or current selection is not search word:
523 // just find the search word
524 if (!have_selection || !match) {
525 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
526 true, findnext, wrap, false, onlysel);
527 return make_pair(found, 0);
530 // we're now actually ready to replace. if the buffer is
531 // read-only, we can't, though.
532 if (bv->buffer().isReadonly())
533 return make_pair(false, 0);
535 cap::replaceSelectionWithString(cur, replacestr);
537 cur.pos() += replacestr.length();
538 LASSERT(cur.pos() <= cur.lastpos(),
539 cur.pos() = cur.lastpos());
542 findOne(bv, searchstr, case_sens, whole,
543 forward, false, findnext, wrap, false, onlysel);
545 return make_pair(true, 1);
551 docstring const find2string(docstring const & search,
552 bool casesensitive, bool matchword,
553 bool forward, bool wrap, bool instant,
558 << int(casesensitive) << ' '
559 << int(matchword) << ' '
560 << int(forward) << ' '
562 << int(instant) << ' '
568 docstring const replace2string(docstring const & replace,
569 docstring const & search,
570 bool casesensitive, bool matchword,
571 bool all, bool forward, bool findnext,
572 bool wrap, bool onlysel)
575 ss << replace << '\n'
577 << int(casesensitive) << ' '
578 << int(matchword) << ' '
580 << int(forward) << ' '
581 << int(findnext) << ' '
588 docstring const string2find(docstring const & argument,
596 // data is of the form
598 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
600 docstring howto = split(argument, search, '\n');
602 casesensitive = parse_bool(howto);
603 matchword = parse_bool(howto);
604 forward = parse_bool(howto, true);
605 wrap = parse_bool(howto);
606 instant = parse_bool(howto);
607 onlysel = parse_bool(howto);
613 bool lyxfind(BufferView * bv, FuncRequest const & ev)
615 if (!bv || ev.action() != LFUN_WORD_FIND)
618 //lyxerr << "find called, cmd: " << ev << endl;
626 docstring search = string2find(ev.argument(), casesensitive,
627 matchword, forward, wrap, instant, onlysel);
629 return findOne(bv, search, casesensitive, matchword, forward,
630 false, true, wrap, instant, onlysel);
634 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
636 if (!bv || ev.action() != LFUN_WORD_REPLACE)
639 // data is of the form
642 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
645 docstring howto = split(ev.argument(), rplc, '\n');
646 howto = split(howto, search, '\n');
648 bool casesensitive = parse_bool(howto);
649 bool matchword = parse_bool(howto);
650 bool all = parse_bool(howto);
651 bool forward = parse_bool(howto, true);
652 bool findnext = parse_bool(howto, true);
653 bool wrap = parse_bool(howto);
654 bool onlysel = parse_bool(howto);
656 if (!bv->cursor().selection())
657 // only selection only makes sense with selection
662 int replace_count = 0;
664 replace_count = replaceAll(bv, search, rplc, casesensitive,
666 update = replace_count > 0;
669 replaceOne(bv, search, rplc, casesensitive, matchword,
670 forward, findnext, wrap, onlysel);
672 replace_count = rv.second;
675 Buffer const & buf = bv->buffer();
677 // emit message signal.
679 buf.message(_("String not found in selection."));
681 buf.message(_("String not found."));
683 if (replace_count == 0) {
684 buf.message(_("String found."));
685 } else if (replace_count == 1) {
686 buf.message(_("String has been replaced."));
688 docstring const str = onlysel
689 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
690 : bformat(_("%1$d strings have been replaced."), replace_count);
698 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
700 for (; cur; cur.forwardPos())
701 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
705 DocIterator cur_orig(bv->cursor());
706 docstring q = _("End of file reached while searching forward.\n"
707 "Continue searching from the beginning?");
708 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
709 q, 0, 1, _("&Yes"), _("&No"));
710 if (wrap_answer == 0) {
711 bv->cursor().clear();
712 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
713 bv->clearSelection();
714 cur.setCursor(bv->cursor().selectionBegin());
715 if (findNextChange(bv, cur, false))
718 bv->cursor().setCursor(cur_orig);
725 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
727 for (cur.backwardPos(); cur; cur.backwardPos()) {
728 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
733 DocIterator cur_orig(bv->cursor());
734 docstring q = _("Beginning of file reached while searching backward.\n"
735 "Continue searching from the end?");
736 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
737 q, 0, 1, _("&Yes"), _("&No"));
738 if (wrap_answer == 0) {
739 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
740 bv->cursor().backwardPos();
741 bv->clearSelection();
742 cur.setCursor(bv->cursor().selectionBegin());
743 if (findPreviousChange(bv, cur, false))
746 bv->cursor().setCursor(cur_orig);
753 bool selectChange(Cursor & cur, bool forward)
755 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
757 Change ch = cur.paragraph().lookupChange(cur.pos());
759 CursorSlice tip1 = cur.top();
760 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
761 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
762 if (!ch2.isSimilarTo(ch))
765 CursorSlice tip2 = cur.top();
766 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
768 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
769 if (!ch2.isSimilarTo(ch)) {
770 // take a step forward to correctly set the selection
778 cur.bv().mouseSetCursor(cur, false);
780 cur.bv().mouseSetCursor(cur, true);
788 bool findChange(BufferView * bv, bool forward)
791 cur.setCursor(forward ? bv->cursor().selectionEnd()
792 : bv->cursor().selectionBegin());
793 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
794 return selectChange(cur, forward);
799 bool findNextChange(BufferView * bv)
801 return findChange(bv, true);
805 bool findPreviousChange(BufferView * bv)
807 return findChange(bv, false);
814 typedef vector<pair<string, string> > Escapes;
816 static string getRegexSpaceCount(int count)
820 return "\\s{" + std::to_string(count) + "}";
827 string string2regex(string in)
829 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\$\\])" };
830 string tempx = std::regex_replace(in, specialChars, R"(\$&)" );
831 // Special handling for ' '
834 for (unsigned i = 0; i < tempx.size(); i++) {
835 if (tempx[i] == ' ' || tempx[i] == '~' ) {
839 else if ((tempx[i] == '\302' && tempx[i+1] == '\240')
840 || (tempx[i] == '\342' && tempx[i+1] == '\200')) {
848 temp += getRegexSpaceCount(blanks);
855 temp += getRegexSpaceCount(blanks);
862 while (fl_pos < temp.size()) {
863 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
864 if (fl_pos == string::npos)
867 temp2 += temp.substr(lastpos, fl_pos - lastpos);
873 if (lastpos < temp.size()) {
874 temp2 += temp.substr(lastpos, temp.size() - lastpos);
879 static void buildAccentsMap();
881 string correctRegex(string t, bool withformat)
883 /* Convert \backslash => \
884 * and \{, \}, \[, \] => {, }, [, ]
887 static std::regex wordre("(\\\\)*(\\\\(( |[A-Za-z]+|[\\{\\}%])( |\\{\\})?|[\\[\\]\\{\\}]))");
888 static std::regex protectedSpace { R"(~)" };
891 bool backslashed = false;
895 //LYXERR0("correctRegex input '" << t << "'");
897 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
900 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
904 if (sub.str(4) == "backslash") {
907 // transforms '\backslash \{' into '\{'
908 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
909 if ((next == "\\{") || (next == "\\}") || (next == "\\ ")) {
913 else if (withformat && next[0] == '$') {
914 replace = accents["lyxdollar"];
915 skip = 1; // Skip following '$'
919 else if (sub.str(4) == "mathcircumflex")
921 else if (backslashed) {
924 if (sub.str(3) == "{")
925 replace = accents["braceleft"];
926 else if (sub.str(3) == "}")
927 replace = accents["braceright"];
928 else if (sub.str(3) == " ")
931 // else part should not exist
936 if (sub.str(3) == "{")
938 else if (sub.str(3) == "}")
940 else if (sub.str(3) == " ")
943 // else part should not exist
948 else if (sub.str(4) == "{") // transforms '\{' into '{'
950 else if (sub.str(4) == "}")
952 else if (sub.str(4) == "%")
954 else if (sub.str(4) == " ")
957 AccentsIterator it_ac = accents.find(sub.str(4));
958 if (it_ac == accents.end()) {
959 replace = sub.str(2);
962 replace = it_ac->second;
966 if (lastpos < (size_t) sub.position(2))
967 s += std::regex_replace(t.substr(lastpos, sub.position(2) - lastpos), protectedSpace, R"( )");
969 lastpos = sub.position(2) + sub.length(2) + skip;
973 s = std::regex_replace(t, protectedSpace, R"( )");
974 else if (lastpos < t.length())
975 s += std::regex_replace(t.substr(lastpos, t.length() - lastpos), protectedSpace, R"( )");
976 // Handle quotes in regex
977 // substitute all '„', '“', '»', '«' with '"'
978 // and all '‚', '‘', '›', '‹' with "\'"
979 static std::regex plainquotes { R"(„|“|»|«)" };
980 static std::regex innerquotes { R"(‚|‘|›|‹)" };
981 t = std::regex_replace(s, plainquotes, R"(")");
982 s = std::regex_replace(t, innerquotes, R"(')");
983 //LYXERR0("correctRegex output '" << s << "'");
987 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
988 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
989 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
990 string escape_for_regex(string s, bool withformat)
994 while (lastpos < s.size()) {
995 size_t regex_pos = s.find("\\regexp{", lastpos);
996 if (regex_pos == string::npos) {
997 regex_pos = s.size();
999 if (regex_pos > lastpos) {
1000 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
1001 lastpos = regex_pos;
1002 if (lastpos == s.size())
1005 size_t end_pos = s.find("\\endregexp", regex_pos + 8);
1006 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
1007 lastpos = end_pos + 13;
1013 /// Wrapper for lyx::regex_replace with simpler interface
1014 bool regex_replace(string const & s, string & t, string const & searchstr,
1015 string const & replacestr)
1017 regex e(searchstr, regex_constants::ECMAScript);
1019 ostream_iterator<char, char> it(oss);
1020 regex_replace(it, s.begin(), s.end(), e, replacestr);
1021 // tolerate t and s be references to the same variable
1022 bool rv = (s != oss.str());
1041 vector <string> result = vector <string>();
1042 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {}
1045 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
1047 if (newres.match2end < oldres.match2end)
1048 return MatchResult::newIsTooFar;
1049 if (newres.match_len < oldres.match_len)
1050 return MatchResult::newIsTooFar;
1052 if (newres.match_len == oldres.match_len) {
1053 if (newres.match2end == oldres.match2end)
1054 return MatchResult::newIsBetter;
1056 return MatchResult::newIsInvalid;
1059 /** The class performing a match between a position in the document and the FindAdvOptions.
1062 class MatchStringAdv {
1064 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
1066 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
1067 ** constructor as opt.search, under the opt.* options settings.
1070 ** If set to MatchStringAdv::MatchFromStart,
1071 ** then match is searched only against beginning of text starting at cur.
1072 ** Otherwise the match is searched anywhere in text starting at cur.
1075 ** The length of the matching text, or zero if no match was found.
1081 string matchTypeAsString(matchType const x) const { return (x == MatchFromStart ? "MatchFromStart" : "MatchAnyPlace"); }
1082 MatchResult operator()(DocIterator const & cur, int len, matchType at_begin) const;
1090 lyx::Buffer * p_buf;
1091 /// first buffer on which search was started
1092 lyx::Buffer * const p_first_buf;
1094 FindAndReplaceOptions const & opt;
1097 /// Auxiliary find method (does not account for opt.matchword)
1098 MatchResult findAux(DocIterator const & cur, int len, matchType at_begin) const;
1099 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
1101 /** Normalize a stringified or latexified LyX paragraph.
1105 ** <li>if search is not casesensitive, then lowercase the string;
1106 ** <li>remove any newline at begin or end of the string;
1107 ** <li>replace any newline in the middle of the string with a simple space;
1108 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
1111 ** @todo Normalization should also expand macros, if the corresponding
1112 ** search option was checked.
1114 string normalize(docstring const & s, bool ignore_fomat) const;
1115 // normalized string to search
1116 string par_as_string;
1117 // regular expression to use for searching
1118 // regexp2 is same as regexp, but prefixed with a ".*?"
1120 QRegularExpression regexp;
1121 QRegularExpression regexp2;
1126 // leading format material as string
1127 string lead_as_string;
1128 // par_as_string after removal of lead_as_string
1129 string par_as_string_nolead;
1130 // unmatched open braces in the search string/regexp
1132 // number of (.*?) subexpressions added at end of search regexp for closing
1133 // environments, math mode, styles, etc...
1134 int close_wildcards;
1136 // Are we searching with regular expressions ?
1137 bool use_regexp = false;
1138 static int valid_matches;
1139 static vector <string> matches;
1140 void FillResults(MatchResult &found_mr);
1143 int MatchStringAdv::valid_matches = 0;
1144 vector <string> MatchStringAdv::matches = vector <string>(10);
1146 void MatchStringAdv::FillResults(MatchResult &found_mr)
1148 if (found_mr.match_len > 0) {
1149 valid_matches = found_mr.result.size();
1150 for (size_t i = 0; i < found_mr.result.size(); i++)
1151 matches[i] = found_mr.result[i];
1156 static void setFindParams(OutputParams &runparams)
1158 runparams.flavor = Flavor::XeTeX;
1159 //runparams.use_polyglossia = true;
1160 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1161 // No side effect of file copying and image conversion
1162 runparams.dryrun = true;
1165 static docstring buffer_to_latex(Buffer & buffer)
1167 //OutputParams runparams(&buffer.params().encoding());
1168 OutputParams runparams(encodings.fromLyXName("utf8"));
1169 odocstringstream ods;
1171 runparams.nice = true;
1172 setFindParams(runparams);
1173 if (ignoreFormats.getDeleted())
1174 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1176 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1177 if (ignoreFormats.getNonContent()) {
1178 runparams.find_add_feature(OutputParams::SearchNonOutput);
1180 pit_type const endpit = buffer.paragraphs().size();
1181 for (pit_type pit = 0; pit != endpit; ++pit) {
1182 TeXOnePar(buffer, buffer.text(), pit, os, runparams, string(), -1, -1, true);
1183 LYXERR(Debug::FINDVERBOSE, "searchString up to here: " << ods.str());
1188 static string latexNamesToUtf8(docstring strIn, bool withformat)
1190 string addtmp = to_utf8(strIn);
1191 static regex const rmAcc("(\\\\)*("
1192 "\\\\([A-Za-z]+\\{.\\})" // e.g. "ddot{A}" == sub.str(3)
1193 "|\\\\([A-Za-z]+)( |\\{\\})?" // e.g. "LyX", "LyX{}", "LyX " == sub.str(4)
1200 if (accents.empty())
1202 for (sregex_iterator it_add(addtmp.begin(), addtmp.end(), rmAcc), end; it_add != end; ++it_add) {
1204 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
1209 if (sub.length(3) > 0)
1213 AccentsIterator it_ac = accents.find(key);
1214 if (it_ac == accents.end()) {
1215 replace = sub.str(2);
1218 replace = it_ac->second;
1221 if (lastpos < (size_t) sub.position(2))
1222 add += addtmp.substr(lastpos, sub.position(2) - lastpos);
1224 lastpos = sub.position(2) + sub.length(2);
1228 else if (addtmp.length() > lastpos)
1229 add += addtmp.substr(lastpos, addtmp.length() - lastpos);
1231 static std::regex repltilde { R"(~)" };
1232 add = std::regex_replace(add, repltilde, accents["lyxtilde"]);
1234 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1239 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1242 if (!opt.ignoreformat) {
1243 str = buffer_to_latex(buffer);
1245 // OutputParams runparams(&buffer.params().encoding());
1246 OutputParams runparams(encodings.fromLyXName("utf8"));
1247 runparams.nice = true;
1248 setFindParams(runparams);
1249 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1250 if (ignoreFormats.getDeleted()) {
1251 option |= AS_STR_SKIPDELETE;
1252 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1255 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1257 if (ignoreFormats.getNonContent()) {
1258 runparams.find_add_feature(OutputParams::SearchNonOutput);
1261 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1262 Paragraph const & par = buffer.paragraphs().at(pit);
1263 string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1265 &runparams), !opt.ignoreformat);
1266 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1270 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1271 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1278 /// Return separation pos between the leading material and the rest
1279 static size_t identifyLeading(string const & s)
1282 // @TODO Support \item[text]
1283 // Kornel: Added textsl, textsf, textit, texttt and noun
1284 // + allow to search for colored text too
1285 while (regex_replace(t, t, "^\\\\(("
1286 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1287 "lyxaddress|lyxrightaddress|"
1288 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1289 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1290 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1291 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1292 || regex_replace(t, t, "^\\$", "")
1293 || regex_replace(t, t, "^\\\\\\[", "")
1294 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1295 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1297 LYXERR(Debug::FINDVERBOSE, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1298 return s.size() - t.size();
1302 * Given a latexified string, retrieve some handled features
1303 * The features of the regex will later be compared with the features
1304 * of the searched text. If the regex features are not a
1305 * subset of the analized, then, in not format ignoring search
1306 * we can early stop the search in the relevant inset.
1308 typedef map<string, bool> Features;
1310 static Features identifyFeatures(string const & s)
1312 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1313 static regex const valid("^("
1315 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1316 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1317 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1318 "(u|uu)line|(s|x)out|uwave|"
1319 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1320 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1325 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1328 if (sub.str(1).compare("regexp") == 0) {
1332 string token = sub.str(1);
1334 if (regex_match(token, sub2, valid)) {
1342 if (sub.str(1).compare("endregexp") == 0) {
1352 * defines values features of a key "\\[a-z]+{"
1357 /* Char type with content discarded
1358 * like \hspace{1cm} */
1360 /* Char, like \backslash */
1362 /* replace starting backslash with '#' */
1364 /* \part, \section*, ... */
1366 /* title, author etc */
1368 /* \foreignlanguage{ngerman}, ... */
1371 * to discard language in content */
1374 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1376 /* fonts, colors, markups, ... */
1378 /* footnotesize, ... large, ...
1379 * Ignore all of them */
1382 /* inputencoding, ...
1383 * Discard also content, because they do not help in search */
1386 * like remove, but also all arguments */
1388 /* item, listitem */
1390 /* tex, latex, ... like isChar */
1392 /* like \lettrine[lines=5]{}{} */
1394 // like isStandard, but always remove head
1396 /* End of arguments marker for lettrine,
1397 * so that they can be ignored */
1400 KeyInfo() = default;
1401 KeyInfo(KeyType type, int parcount, bool disable)
1403 parenthesiscount(parcount),
1404 disabled(disable) {}
1405 KeyType keytype = invalid;
1407 int _tokensize = -1;
1408 int _tokenstart = -1;
1409 int _dataStart = -1;
1411 int parenthesiscount = 1;
1412 bool disabled = false;
1413 bool used = false; /* by pattern */
1418 Border(int l=0, int u=0) : low(l), upper(u) {}
1423 #define MAXOPENED 30
1425 bool isPatternString_;
1427 explicit Intervall(bool isPattern, string const & p)
1428 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1429 actualdeptindex(0), hasTitle(false), langcount(0)
1437 static vector<Border> borders;
1438 static vector<int> depts;
1439 static vector<int> closes;
1440 int actualdeptindex;
1441 int previousNotIgnored(int) const;
1442 int nextNotIgnored(int) const;
1443 void handleOpenP(int i);
1444 void handleCloseP(int i, bool closingAllowed);
1445 void resetOpenedP(int openPos);
1446 void addIntervall(int upper);
1447 void addIntervall(int low, int upper); /* if explicit */
1448 void removeAccents();
1449 void setForDefaultLang(KeyInfo const & defLang) const;
1450 int findclosing(int start, int end, char up, char down, int repeat);
1451 void removeInvalidClosings(void);
1452 void handleParentheses(int lastpos, bool closingAllowed);
1454 // Number of disabled language specs up
1455 // to current position in actual interval
1457 int isOpeningPar(int pos) const;
1459 void output(ostringstream &os, int lastpos);
1460 // string show(int lastpos);
1463 vector<Border> Intervall::borders = vector<Border>(30);
1464 vector<int> Intervall::depts = vector<int>(30);
1465 vector<int> Intervall::closes = vector<int>(30);
1467 int Intervall::isOpeningPar(int pos) const
1469 if ((pos < 0) || (size_t(pos) >= par.size()))
1471 if (par[pos] != '{')
1473 if (size_t(pos) + 2 >= par.size())
1475 if (par[pos+2] != '}')
1477 if (par[pos+1] == '[' || par[pos+1] == ']')
1482 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1484 // Enable the use of first token again
1485 if (ignoreidx >= 0) {
1486 int value = defLang._tokenstart + defLang._tokensize;
1491 if (borders[borderidx].low < value)
1492 borders[borderidx].low = value;
1493 if (borders[borderidx].upper < value)
1494 borders[borderidx].upper = value;
1500 // Not needed, because dpts and closes are now dynamically expanded
1501 static void checkDepthIndex(int val)
1503 static int maxdepthidx = MAXOPENED-2;
1504 static int lastmaxdepth = 0;
1505 if (val > lastmaxdepth) {
1506 LYXERR(Debug::INFO, "Depth reached " << val);
1509 if (val > maxdepthidx) {
1511 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1517 // Not needed, because borders are now dynamically expanded
1518 static void checkIgnoreIdx(int val)
1520 static int lastmaxignore = -1;
1521 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1522 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1523 lastmaxignore = val;
1529 * Expand the region of ignored parts of the input latex string
1530 * The region is only relevant in output()
1532 void Intervall::addIntervall(int low, int upper)
1535 if (low == upper) return;
1536 for (idx = ignoreidx+1; idx > 0; --idx) {
1537 if (low > borders[idx-1].upper) {
1541 Border br(low, upper);
1542 if (idx > ignoreidx) {
1543 if (borders.size() <= size_t(idx)) {
1544 borders.push_back(br);
1550 // checkIgnoreIdx(ignoreidx);
1554 // Expand only if one of the new bound is inside the interwall
1555 // We know here that br.low > borders[idx-1].upper
1556 if (br.upper < borders[idx].low) {
1557 // We have to insert at this pos
1558 if (size_t(ignoreidx+1) >= borders.size()) {
1559 borders.push_back(borders[ignoreidx]);
1562 borders[ignoreidx+1] = borders[ignoreidx];
1564 for (int i = ignoreidx; i > idx; --i) {
1565 borders[i] = borders[i-1];
1569 // checkIgnoreIdx(ignoreidx);
1572 // Here we know, that we are overlapping
1573 if (br.low > borders[idx].low)
1574 br.low = borders[idx].low;
1575 // check what has to be concatenated
1577 for (int i = idx; i <= ignoreidx; i++) {
1578 if (br.upper >= borders[i].low) {
1580 if (br.upper < borders[i].upper)
1581 br.upper = borders[i].upper;
1587 // count should be >= 1 here
1590 for (int i = idx + count; i <= ignoreidx; i++) {
1591 borders[i-count+1] = borders[i];
1593 ignoreidx -= count - 1;
1599 static void buildaccent(string n, string param, string values)
1603 const char delim = '|';
1604 while (getline(s, name, delim)) {
1606 for (char c : param) {
1607 string key = name + "{" + c + "}";
1608 // get the corresponding utf8-value
1609 if ((values[start] & 0xc0) != 0xc0) {
1610 // should not happen, utf8 encoding starts at least with 11xxxxxx
1611 // but value for '\dot{i}' is 'i', which is ascii
1612 if ((values[start] & 0x80) == 0) {
1614 accents[key] = values.substr(start, 1);
1615 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1620 for (int j = 1; ;j++) {
1621 if (start + j >= values.size()) {
1622 accents[key] = values.substr(start, j);
1623 start = values.size() - 1;
1626 else if ((values[start+j] & 0xc0) != 0x80) {
1627 // This is the first byte of following utf8 char
1628 accents[key] = values.substr(start, j);
1630 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1639 static string getutf8(unsigned uchar)
1642 string ret = string();
1644 if (uchar <= 0x7f) {
1645 c[maxc-1] = uchar & 0x7f;
1648 unsigned char rest = 0x40;
1649 unsigned char first = 0x80;
1651 for (int i = start; i >=0; --i) {
1653 c[i] = first + uchar;
1656 c[i] = 0x80 | (uchar & 0x3f);
1663 for (int i = 0; i < maxc; i++) {
1664 if (c[i] == 0) continue;
1670 static void addAccents(string latex_in, string unicode_out)
1672 latex_in = latex_in.substr(1);
1673 AccentsIterator it_ac = accents.find(latex_in);
1674 if (it_ac == accents.end()) {
1675 accents[latex_in] = unicode_out;
1678 LYXERR0("Key " << latex_in << " already set");
1682 void static fillMissingUnicodesymbols()
1684 addAccents("\\pounds", getutf8(0x00a3));
1685 addAccents("\\textsterling", getutf8(0x00a3));
1686 addAccents("\\textyen", getutf8(0x00a5));
1687 addAccents("\\yen", getutf8(0x00a5));
1688 addAccents("\\textsection", getutf8(0x00a7));
1689 addAccents("\\mathsection", getutf8(0x00a7));
1690 addAccents("\\textcopyright", getutf8(0x00a9));
1691 addAccents("\\copyright", getutf8(0x00a9));
1692 addAccents("\\textlnot", getutf8(0x00ac));
1693 addAccents("\\neg", getutf8(0x00ac));
1694 addAccents("\\textregistered", getutf8(0x00ae));
1695 addAccents("\\circledR", getutf8(0x00ae));
1696 addAccents("\\textpm", getutf8(0x00b1));
1697 addAccents("\\pm", getutf8(0x00b1));
1698 addAccents("\\textparagraph", getutf8(0x00b6));
1699 addAccents("\\mathparagraph", getutf8(0x00b6));
1700 addAccents("\\textperiodcentered", getutf8(0x00b7));
1701 addAccents("\\texttimes", getutf8(0x00d7));
1702 addAccents("\\times", getutf8(0x00d7));
1703 addAccents("\\O", getutf8(0x00d8));
1704 addAccents("\\dh", getutf8(0x00f0));
1705 addAccents("\\eth", getutf8(0x00f0));
1706 addAccents("\\textdiv", getutf8(0x00f7));
1707 addAccents("\\div", getutf8(0x00f7));
1708 addAccents("\\o", getutf8(0x00f8));
1709 addAccents("\\textcrlambda", getutf8(0x019b));
1710 addAccents("\\j", getutf8(0x0237));
1711 addAccents("\\textrevepsilon", getutf8(0x025c));
1712 addAccents("\\textbaru", getutf8(0x0289));
1713 addAccents("\\textquoteleft", getutf8(0x02bb));
1714 addAccents("\\textGamma", getutf8(0x0393));
1715 addAccents("\\Gamma", getutf8(0x0393));
1716 addAccents("\\textDelta", getutf8(0x0394));
1717 addAccents("\\Delta", getutf8(0x0394));
1718 addAccents("\\textTheta", getutf8(0x0398));
1719 addAccents("\\Theta", getutf8(0x0398));
1720 addAccents("\\textLambda", getutf8(0x039b));
1721 addAccents("\\Lambda", getutf8(0x039b));
1722 addAccents("\\textXi", getutf8(0x039e));
1723 addAccents("\\Xi", getutf8(0x039e));
1724 addAccents("\\textPi", getutf8(0x03a0));
1725 addAccents("\\Pi", getutf8(0x03a0));
1726 addAccents("\\textSigma", getutf8(0x03a3));
1727 addAccents("\\Sigma", getutf8(0x03a3));
1728 addAccents("\\textUpsilon", getutf8(0x03a5));
1729 addAccents("\\Upsilon", getutf8(0x03a5));
1730 addAccents("\\textPhi", getutf8(0x03a6));
1731 addAccents("\\Phi", getutf8(0x03a6));
1732 addAccents("\\textPsi", getutf8(0x03a8));
1733 addAccents("\\Psi", getutf8(0x03a8));
1734 addAccents("\\textOmega", getutf8(0x03a9));
1735 addAccents("\\Omega", getutf8(0x03a9));
1736 addAccents("\\textalpha", getutf8(0x03b1));
1737 addAccents("\\alpha", getutf8(0x03b1));
1738 addAccents("\\textbeta", getutf8(0x03b2));
1739 addAccents("\\beta", getutf8(0x03b2));
1740 addAccents("\\textgamma", getutf8(0x03b3));
1741 addAccents("\\gamma", getutf8(0x03b3));
1742 addAccents("\\textdelta", getutf8(0x03b4));
1743 addAccents("\\delta", getutf8(0x03b4));
1744 addAccents("\\textepsilon", getutf8(0x03b5));
1745 addAccents("\\varepsilon", getutf8(0x03b5));
1746 addAccents("\\textzeta", getutf8(0x03b6));
1747 addAccents("\\zeta", getutf8(0x03b6));
1748 addAccents("\\texteta", getutf8(0x03b7));
1749 addAccents("\\eta", getutf8(0x03b7));
1750 addAccents("\\texttheta", getutf8(0x03b8));
1751 addAccents("\\theta", getutf8(0x03b8));
1752 addAccents("\\textiota", getutf8(0x03b9));
1753 addAccents("\\iota", getutf8(0x03b9));
1754 addAccents("\\textkappa", getutf8(0x03ba));
1755 addAccents("\\kappa", getutf8(0x03ba));
1756 addAccents("\\textlambda", getutf8(0x03bb));
1757 addAccents("\\lambda", getutf8(0x03bb));
1758 addAccents("\\textmu", getutf8(0x03bc));
1759 addAccents("\\mu", getutf8(0x03bc));
1760 addAccents("\\textnu", getutf8(0x03bd));
1761 addAccents("\\nu", getutf8(0x03bd));
1762 addAccents("\\textxi", getutf8(0x03be));
1763 addAccents("\\xi", getutf8(0x03be));
1764 addAccents("\\textpi", getutf8(0x03c0));
1765 addAccents("\\pi", getutf8(0x03c0));
1766 addAccents("\\textrho", getutf8(0x03c1));
1767 addAccents("\\rho", getutf8(0x03c1));
1768 addAccents("\\textfinalsigma", getutf8(0x03c2));
1769 addAccents("\\varsigma", getutf8(0x03c2));
1770 addAccents("\\textsigma", getutf8(0x03c3));
1771 addAccents("\\sigma", getutf8(0x03c3));
1772 addAccents("\\texttau", getutf8(0x03c4));
1773 addAccents("\\tau", getutf8(0x03c4));
1774 addAccents("\\textupsilon", getutf8(0x03c5));
1775 addAccents("\\upsilon", getutf8(0x03c5));
1776 addAccents("\\textphi", getutf8(0x03c6));
1777 addAccents("\\varphi", getutf8(0x03c6));
1778 addAccents("\\textchi", getutf8(0x03c7));
1779 addAccents("\\chi", getutf8(0x03c7));
1780 addAccents("\\textpsi", getutf8(0x03c8));
1781 addAccents("\\psi", getutf8(0x03c8));
1782 addAccents("\\textomega", getutf8(0x03c9));
1783 addAccents("\\omega", getutf8(0x03c9));
1784 addAccents("\\textdigamma", getutf8(0x03dd));
1785 addAccents("\\digamma", getutf8(0x03dd));
1786 addAccents("\\hebalef", getutf8(0x05d0));
1787 addAccents("\\aleph", getutf8(0x05d0));
1788 addAccents("\\hebbet", getutf8(0x05d1));
1789 addAccents("\\beth", getutf8(0x05d1));
1790 addAccents("\\hebgimel", getutf8(0x05d2));
1791 addAccents("\\gimel", getutf8(0x05d2));
1792 addAccents("\\hebdalet", getutf8(0x05d3));
1793 addAccents("\\daleth", getutf8(0x05d3));
1794 addAccents("\\hebhe", getutf8(0x05d4));
1795 addAccents("\\hebvav", getutf8(0x05d5));
1796 addAccents("\\hebzayin", getutf8(0x05d6));
1797 addAccents("\\hebhet", getutf8(0x05d7));
1798 addAccents("\\hebtet", getutf8(0x05d8));
1799 addAccents("\\hebyod", getutf8(0x05d9));
1800 addAccents("\\hebfinalkaf", getutf8(0x05da));
1801 addAccents("\\hebkaf", getutf8(0x05db));
1802 addAccents("\\heblamed", getutf8(0x05dc));
1803 addAccents("\\hebfinalmem", getutf8(0x05dd));
1804 addAccents("\\hebmem", getutf8(0x05de));
1805 addAccents("\\hebfinalnun", getutf8(0x05df));
1806 addAccents("\\hebnun", getutf8(0x05e0));
1807 addAccents("\\hebsamekh", getutf8(0x05e1));
1808 addAccents("\\hebayin", getutf8(0x05e2));
1809 addAccents("\\hebfinalpe", getutf8(0x05e3));
1810 addAccents("\\hebpe", getutf8(0x05e4));
1811 addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1812 addAccents("\\hebtsadi", getutf8(0x05e6));
1813 addAccents("\\hebqof", getutf8(0x05e7));
1814 addAccents("\\hebresh", getutf8(0x05e8));
1815 addAccents("\\hebshin", getutf8(0x05e9));
1816 addAccents("\\hebtav", getutf8(0x05ea));
1819 addAccents("\\thaiKoKai", getutf8(0x0e01));
1820 addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1821 addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1822 addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1823 addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1824 addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1825 addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1826 addAccents("\\thaiChoChan", getutf8(0x0e08));
1827 addAccents("\\thaiChoChing", getutf8(0x0e09));
1828 addAccents("\\thaiChoChang", getutf8(0x0e0a));
1829 addAccents("\\thaiSoSo", getutf8(0x0e0b));
1830 addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1831 addAccents("\\thaiYoYing", getutf8(0x0e0d));
1832 addAccents("\\thaiDoChada", getutf8(0x0e0e));
1833 addAccents("\\thaiToPatak", getutf8(0x0e0f));
1834 addAccents("\\thaiThoThan", getutf8(0x0e10));
1835 addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1836 addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1837 addAccents("\\thaiNoNen", getutf8(0x0e13));
1838 addAccents("\\thaiDoDek", getutf8(0x0e14));
1839 addAccents("\\thaiToTao", getutf8(0x0e15));
1840 addAccents("\\thaiThoThung", getutf8(0x0e16));
1841 addAccents("\\thaiThoThahan", getutf8(0x0e17));
1842 addAccents("\\thaiThoThong", getutf8(0x0e18));
1843 addAccents("\\thaiNoNu", getutf8(0x0e19));
1844 addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1845 addAccents("\\thaiPoPla", getutf8(0x0e1b));
1846 addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1847 addAccents("\\thaiFoFa", getutf8(0x0e1d));
1848 addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1849 addAccents("\\thaiFoFan", getutf8(0x0e1f));
1850 addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1851 addAccents("\\thaiMoMa", getutf8(0x0e21));
1852 addAccents("\\thaiYoYak", getutf8(0x0e22));
1853 addAccents("\\thaiRoRua", getutf8(0x0e23));
1854 addAccents("\\thaiRu", getutf8(0x0e24));
1855 addAccents("\\thaiLoLing", getutf8(0x0e25));
1856 addAccents("\\thaiLu", getutf8(0x0e26));
1857 addAccents("\\thaiWoWaen", getutf8(0x0e27));
1858 addAccents("\\thaiSoSala", getutf8(0x0e28));
1859 addAccents("\\thaiSoRusi", getutf8(0x0e29));
1860 addAccents("\\thaiSoSua", getutf8(0x0e2a));
1861 addAccents("\\thaiHoHip", getutf8(0x0e2b));
1862 addAccents("\\thaiLoChula", getutf8(0x0e2c));
1863 addAccents("\\thaiOAng", getutf8(0x0e2d));
1864 addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1865 addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1866 addAccents("\\thaiSaraA", getutf8(0x0e30));
1867 addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1868 addAccents("\\thaiSaraAa", getutf8(0x0e32));
1869 addAccents("\\thaiSaraAm", getutf8(0x0e33));
1870 addAccents("\\thaiSaraI", getutf8(0x0e34));
1871 addAccents("\\thaiSaraIi", getutf8(0x0e35));
1872 addAccents("\\thaiSaraUe", getutf8(0x0e36));
1873 addAccents("\\thaiSaraUee", getutf8(0x0e37));
1874 addAccents("\\thaiSaraU", getutf8(0x0e38));
1875 addAccents("\\thaiSaraUu", getutf8(0x0e39));
1876 addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1877 addAccents("\\thaiSaraE", getutf8(0x0e40));
1878 addAccents("\\thaiSaraAe", getutf8(0x0e41));
1879 addAccents("\\thaiSaraO", getutf8(0x0e42));
1880 addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1881 addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1882 addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1883 addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1884 addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1885 addAccents("\\thaiMaiEk", getutf8(0x0e48));
1886 addAccents("\\thaiMaiTho", getutf8(0x0e49));
1887 addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1888 addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1889 addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1890 addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1891 addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1892 addAccents("\\thaiFongman", getutf8(0x0e4f));
1893 addAccents("\\thaizero", getutf8(0x0e50));
1894 addAccents("\\thaione", getutf8(0x0e51));
1895 addAccents("\\thaitwo", getutf8(0x0e52));
1896 addAccents("\\thaithree", getutf8(0x0e53));
1897 addAccents("\\thaifour", getutf8(0x0e54));
1898 addAccents("\\thaifive", getutf8(0x0e55));
1899 addAccents("\\thaisix", getutf8(0x0e56));
1900 addAccents("\\thaiseven", getutf8(0x0e57));
1901 addAccents("\\thaieight", getutf8(0x0e58));
1902 addAccents("\\thainine", getutf8(0x0e59));
1903 addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1904 addAccents("\\thaiKhomut", getutf8(0x0e5b));
1905 addAccents("\\dag", getutf8(0x2020));
1906 addAccents("\\dagger", getutf8(0x2020));
1907 addAccents("\\textdagger", getutf8(0x2020));
1908 addAccents("\\ddag", getutf8(0x2021));
1909 addAccents("\\ddagger", getutf8(0x2021));
1910 addAccents("\\textdaggerdbl", getutf8(0x2021));
1911 addAccents("\\textbullet", getutf8(0x2022));
1912 addAccents("\\bullet", getutf8(0x2022));
1913 addAccents("\\dots", getutf8(0x2026));
1914 addAccents("\\ldots", getutf8(0x2026));
1915 addAccents("\\textellipsis", getutf8(0x2026));
1916 addAccents("\\textasciiacute", getutf8(0x2032));
1917 addAccents("\\prime", getutf8(0x2032));
1918 addAccents("\\textacutedbl", getutf8(0x2033));
1919 addAccents("\\dprime", getutf8(0x2033));
1920 addAccents("\\textasciigrave", getutf8(0x2035));
1921 addAccents("\\backprime", getutf8(0x2035));
1922 addAccents("\\textsubcircum{ }", getutf8(0x2038));
1923 addAccents("\\caretinsert", getutf8(0x2038));
1924 addAccents("\\textasteriskcentered", getutf8(0x204e));
1925 addAccents("\\ast", getutf8(0x204e));
1926 addAccents("\\textmho", getutf8(0x2127));
1927 addAccents("\\mho", getutf8(0x2127));
1928 addAccents("\\textleftarrow", getutf8(0x2190));
1929 addAccents("\\leftarrow", getutf8(0x2190));
1930 addAccents("\\textuparrow", getutf8(0x2191));
1931 addAccents("\\uparrow", getutf8(0x2191));
1932 addAccents("\\textrightarrow", getutf8(0x2192));
1933 addAccents("\\rightarrow", getutf8(0x2192));
1934 addAccents("\\textdownarrow", getutf8(0x2193));
1935 addAccents("\\downarrow", getutf8(0x2193));
1936 addAccents("\\textglobrise", getutf8(0x2197));
1937 addAccents("\\nearrow", getutf8(0x2197));
1938 addAccents("\\textglobfall", getutf8(0x2198));
1939 addAccents("\\searrow", getutf8(0x2198));
1940 addAccents("\\textsurd", getutf8(0x221a));
1941 addAccents("\\surd", getutf8(0x221a));
1942 addAccents("\\textbigcircle", getutf8(0x25ef));
1943 addAccents("\\bigcirc", getutf8(0x25ef));
1944 addAccents("\\FiveStar", getutf8(0x2605));
1945 addAccents("\\bigstar", getutf8(0x2605));
1946 addAccents("\\FiveStarOpen", getutf8(0x2606));
1947 addAccents("\\bigwhitestar", getutf8(0x2606));
1948 addAccents("\\Checkmark", getutf8(0x2713));
1949 addAccents("\\checkmark", getutf8(0x2713));
1950 addAccents("\\CrossMaltese", getutf8(0x2720));
1951 addAccents("\\maltese", getutf8(0x2720));
1952 addAccents("\\textlangle", getutf8(0x27e8));
1953 addAccents("\\langle", getutf8(0x27e8));
1954 addAccents("\\textrangle", getutf8(0x27e9));
1955 addAccents("\\rangle", getutf8(0x27e9));
1958 static void buildAccentsMap()
1960 accents["imath"] = "ı";
1962 accents["jmath"] = "ȷ";
1963 accents["cdot"] = "·";
1964 accents["textasciicircum"] = "^";
1965 accents["mathcircumflex"] = "^";
1966 accents["guillemotright"] = "»";
1967 accents["guillemotleft"] = "«";
1968 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1969 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1970 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1971 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1972 accents["negmedspace"] = getutf8(0xf0005);
1973 accents["thickspace"] = getutf8(0xf0006);
1974 accents["negthickspace"] = getutf8(0xf0007);
1975 accents["lyx"] = getutf8(0xf0010); // Used logos
1976 accents["LyX"] = getutf8(0xf0010);
1977 accents["tex"] = getutf8(0xf0011);
1978 accents["TeX"] = getutf8(0xf0011);
1979 accents["latex"] = getutf8(0xf0012);
1980 accents["LaTeX"] = getutf8(0xf0012);
1981 accents["latexe"] = getutf8(0xf0013);
1982 accents["LaTeXe"] = getutf8(0xf0013);
1983 accents["lyxarrow"] = getutf8(0xf0020);
1984 accents["braceleft"] = getutf8(0xf0030);
1985 accents["braceright"] = getutf8(0xf0031);
1986 accents["lyxtilde"] = getutf8(0xf0032);
1987 accents["sim"] = getutf8(0xf0032);
1988 accents["lyxdollar"] = getutf8(0xf0033);
1989 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1990 accents["backslash LyX"] = getutf8(0xf0010);
1991 accents["backslash tex"] = getutf8(0xf0011);
1992 accents["backslash TeX"] = getutf8(0xf0011);
1993 accents["backslash latex"] = getutf8(0xf0012);
1994 accents["backslash LaTeX"] = getutf8(0xf0012);
1995 accents["backslash latexe"] = getutf8(0xf0013);
1996 accents["backslash LaTeXe"] = getutf8(0xf0013);
1997 accents["backslash lyxarrow"] = getutf8(0xf0020);
1998 accents["ddot{\\imath}"] = "ï";
1999 buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
2000 "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ"); // umlaut
2001 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
2002 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
2003 accents["acute{\\imath}"] = "í";
2004 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2005 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2006 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
2007 buildaccent("mathring|r", "aAuUwy",
2009 accents["check{\\imath}"] = "ǐ";
2010 accents["check{\\jmath}"] = "ǰ";
2011 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2012 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
2013 accents["hat{\\imath}"] = "î";
2014 accents["hat{\\jmath}"] = "ĵ";
2015 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2016 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
2017 accents["bar{\\imath}"] = "ī";
2018 buildaccent("bar|=", "aAeEiIoOuUyY",
2019 "āĀēĒīĪōŌūŪȳȲ"); // macron
2020 accents["tilde{\\imath}"] = "ĩ";
2021 buildaccent("tilde", "aAeEiInNoOuUvVyY",
2022 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
2023 accents["breve{\\imath}"] = "ĭ";
2024 buildaccent("breve|u", "aAeEgGiIoOuU",
2025 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
2026 accents["grave{\\imath}"] = "ì";
2027 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2028 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
2029 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2030 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
2031 buildaccent("ogonek|k", "AaEeIiUuOo",
2032 "ĄąĘęĮįŲųǪǫ"); // ogonek
2033 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2034 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
2035 buildaccent("subring|textsubring", "Aa",
2037 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2038 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
2039 buildaccent("subtilde|textsubtilde", "EeIiUu",
2040 "ḚḛḬḭṴṵ"); // subtilde
2041 accents["dgrave{\\imath}"] = "ȉ";
2042 accents["textdoublegrave{\\i}"] = "ȉ";
2043 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2044 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2045 accents["rcap{\\imath}"] = "ȋ";
2046 accents["textroundcap{\\i}"] = "ȋ";
2047 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2048 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2049 buildaccent("slashed", "oO",
2051 fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2052 // LYXERR0("Number of accents " << accents.size());
2056 * Created accents in math or regexp environment
2057 * are macros, but we need the utf8 equivalent
2059 void Intervall::removeAccents()
2061 if (accents.empty())
2063 static regex const accre("\\\\("
2064 "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]+\\}"
2065 "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2067 "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2072 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2074 string key = sub.str(1);
2075 AccentsIterator it_ac = accents.find(key);
2076 if (it_ac != accents.end()) {
2077 string val = it_ac->second;
2078 size_t pos = sub.position(size_t(0));
2079 for (size_t i = 0; i < val.size(); i++) {
2080 par[pos+i] = val[i];
2082 // Remove possibly following space too
2083 if (par[pos+sub.str(0).size()] == ' ')
2084 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2086 addIntervall(pos+val.size(), pos + sub.str(0).size());
2087 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2088 // remove traces of any remaining chars
2093 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2098 void Intervall::handleOpenP(int i)
2101 if ((size_t) actualdeptindex >= depts.size()) {
2102 depts.resize(actualdeptindex + 30);
2103 closes.resize(actualdeptindex + 30);
2105 depts[actualdeptindex] = i+1;
2106 closes[actualdeptindex] = -1;
2107 // checkDepthIndex(actualdeptindex);
2110 void Intervall::handleCloseP(int i, bool closingAllowed)
2112 if (actualdeptindex <= 0) {
2113 if (! closingAllowed)
2114 LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
2115 // if we are at the very end
2116 addIntervall(i, i+1);
2119 closes[actualdeptindex] = i+1;
2124 void Intervall::resetOpenedP(int openPos)
2126 // Used as initializer for foreignlanguage entry
2127 actualdeptindex = 1;
2128 depts[1] = openPos+1;
2132 int Intervall::previousNotIgnored(int start) const
2134 int idx = 0; /* int intervalls */
2135 for (idx = ignoreidx; idx >= 0; --idx) {
2136 if (start > borders[idx].upper)
2138 if (start >= borders[idx].low)
2139 start = borders[idx].low-1;
2144 int Intervall::nextNotIgnored(int start) const
2146 int idx = 0; /* int intervalls */
2147 for (idx = 0; idx <= ignoreidx; idx++) {
2148 if (start < borders[idx].low)
2150 if (start < borders[idx].upper)
2151 start = borders[idx].upper;
2156 typedef unordered_map<string, KeyInfo> KeysMap;
2157 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2158 typedef vector< KeyInfo> Entries;
2159 static KeysMap keys = unordered_map<string, KeyInfo>();
2165 Intervall interval_;
2166 void buildKeys(bool);
2167 void buildEntries(bool);
2168 void makeKey(const string &, KeyInfo, bool isPatternString);
2169 void processRegion(int start, int region_end); /* remove {} parts */
2170 void removeHead(KeyInfo const &, int count=0);
2173 LatexInfo(string const & par, bool isPatternString)
2174 : entidx_(-1), interval_(isPatternString, par)
2176 buildKeys(isPatternString);
2177 entries_ = vector<KeyInfo>();
2178 buildEntries(isPatternString);
2182 if (entries_.empty()) {
2185 if (entries_[0].keytype == KeyInfo::isTitle) {
2186 interval_.hasTitle = true;
2187 if (! entries_[0].disabled) {
2188 interval_.titleValue = entries_[0].head;
2191 interval_.titleValue = "";
2193 removeHead(entries_[0]);
2194 if (entries_.size() > 1)
2203 if (int(entries_.size()) > entidx_) {
2210 bool setNextKey(int idx) {
2211 if ((idx == entidx_) && (entidx_ >= 0)) {
2218 int find(int start, KeyInfo::KeyType keytype) const {
2222 while (tmpIdx < int(entries_.size())) {
2223 if (entries_[tmpIdx].keytype == keytype)
2229 int process(ostringstream & os, KeyInfo const & actual);
2230 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2231 // string show(int lastpos) { return interval.show(lastpos);}
2232 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2233 KeyInfo &getKeyInfo(int keyinfo) {
2234 static KeyInfo invalidInfo = KeyInfo();
2235 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2238 return entries_[keyinfo];
2240 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2241 void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2245 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2249 for (int i = start; i < end; i += 1 + skip) {
2253 if (c == '\\') skip = 1;
2257 else if (c == down) {
2260 if ((repeat <= 0) || (par[i+1] != up))
2269 void Intervall::removeInvalidClosings(void)
2271 // this can happen, if there are deleted parts
2274 for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2277 if (c == '\\') skip = 1;
2280 else if (c == '}') {
2282 addIntervall(i, i+1);
2283 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2295 size_t mathpostfixsize;
2297 size_t mathprefixsize;
2301 vector<MathEntry> entries_;
2306 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2307 MathEntry m = MathEntry();
2309 m.mathStart = start;
2310 m.mathprefixsize = prefixsize;
2311 m.mathEnd = end + postfixsize;
2312 m.mathpostfixsize = postfixsize;
2313 m.mathSize = m.mathEnd - m.mathStart;
2314 entries_.push_back(m);
2316 bool empty() const { return entries_.empty(); }
2317 size_t getEndPos() const {
2318 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2321 return entries_[actualIdx_].mathEnd;
2323 size_t getStartPos() const {
2324 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2325 return 100000; /* definitely enough? */
2327 return entries_[actualIdx_].mathStart;
2329 size_t getPrefixSize() const {
2330 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2333 return entries_[actualIdx_].mathprefixsize;
2335 size_t getPostfixSize() const {
2336 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2339 return entries_[actualIdx_].mathpostfixsize;
2341 size_t getFirstPos() {
2343 return getStartPos();
2345 size_t getSize() const {
2346 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2349 return entries_[actualIdx_].mathSize;
2351 void incrEntry() { actualIdx_++; }
2354 void LatexInfo::buildEntries(bool isPatternString)
2356 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2357 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2358 static bool disableLanguageOverride = false;
2359 smatch sub, submath;
2360 bool evaluatingRegexp = false;
2362 bool evaluatingMath = false;
2363 bool evaluatingCode = false;
2365 bool evaluatingOptional = false;
2366 size_t optionalEnd = 0;
2369 bool math_end_waiting = false;
2370 size_t math_pos = 10000;
2371 size_t math_prefix_size = 1;
2373 static vector<string> usedText = vector<string>();
2374 static bool removeMathHull = false;
2376 interval_.removeAccents();
2377 interval_.removeInvalidClosings();
2379 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2381 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2382 // prefixed by odd count of '\\'
2385 if (math_end_waiting) {
2386 size_t pos = submath.position(size_t(2));
2387 if ((math_end == "$") &&
2388 (submath.str(2) == "$")) {
2389 mi.insert("$", math_pos, 1, pos, 1);
2390 math_end_waiting = false;
2392 else if ((math_end == "\\]") &&
2393 (submath.str(2) == "\\]")) {
2394 mi.insert("\\]", math_pos, 2, pos, 2);
2395 math_end_waiting = false;
2397 else if ((submath.str(3).compare("end") == 0) &&
2398 (submath.str(5).compare(math_end) == 0)) {
2399 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2400 math_end_waiting = false;
2406 if (submath.str(3).compare("begin") == 0) {
2407 math_end_waiting = true;
2408 math_end = submath.str(5);
2409 math_pos = submath.position(size_t(2));
2410 math_prefix_size = submath.str(2).length();
2412 else if (submath.str(2).compare("\\[") == 0) {
2413 math_end_waiting = true;
2415 math_pos = submath.position(size_t(2));
2417 else if (submath.str(2) == "$") {
2418 size_t pos = submath.position(size_t(2));
2419 math_end_waiting = true;
2425 // Ignore language if there is math somewhere in pattern-string
2426 if (isPatternString) {
2427 for (auto s: usedText) {
2428 // Remove entries created in previous search runs
2431 usedText = vector<string>();
2434 keys["foreignlanguage"].disabled = true;
2435 disableLanguageOverride = true;
2436 removeMathHull = false;
2439 removeMathHull = true; // used later if not isPatternString
2440 disableLanguageOverride = false;
2444 if (disableLanguageOverride) {
2445 keys["foreignlanguage"].disabled = true;
2448 math_pos = mi.getFirstPos();
2449 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2451 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2452 // prefixed by odd count of '\\'
2455 string key = sub.str(5);
2457 if (sub.str(2)[0] == '\\')
2458 key = sub.str(2)[1];
2463 KeysIterator it_key = keys.find(key);
2464 if (it_key != keys.end()) {
2465 if (it_key->second.keytype == KeyInfo::headRemove) {
2466 KeyInfo found1 = it_key->second;
2467 found1.disabled = true;
2468 found1.head = "\\" + key + "{";
2469 found1._tokenstart = sub.position(size_t(2));
2470 found1._tokensize = found1.head.length();
2471 found1._dataStart = found1._tokenstart + found1.head.length();
2472 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2473 found1._dataEnd = endpos;
2478 if (evaluatingRegexp) {
2479 if (sub.str(3).compare("endregexp") == 0) {
2480 evaluatingRegexp = false;
2481 // found._tokenstart already set
2482 found._dataEnd = sub.position(size_t(2)) + 13;
2483 found._dataStart = found._dataEnd;
2484 found._tokensize = found._dataEnd - found._tokenstart;
2485 found.parenthesiscount = 0;
2486 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2493 if (evaluatingMath) {
2494 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2496 evaluatingMath = false;
2498 math_pos = mi.getStartPos();
2500 if (it_key == keys.end()) {
2501 found = KeyInfo(KeyInfo::isStandard, 0, true);
2502 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2503 found = KeyInfo(KeyInfo::isText, 0, false);
2504 if (isPatternString) {
2505 found.keytype = KeyInfo::isChar;
2506 found.disabled = false;
2510 usedText.push_back(key);
2514 if (key.compare("regexp") == 0) {
2515 evaluatingRegexp = true;
2516 found._tokenstart = sub.position(size_t(2));
2517 found._tokensize = 0;
2521 // Handle the other params of key
2522 if (found.keytype == KeyInfo::isIgnored)
2524 else if (found.keytype == KeyInfo::isMath) {
2525 if (size_t(sub.position(size_t(2))) == math_pos) {
2527 found._tokenstart = sub.position(size_t(2));
2528 found._tokensize = mi.getSize();
2529 found._dataEnd = found._tokenstart + found._tokensize;
2530 found._dataStart = found._dataEnd;
2531 found.parenthesiscount = 0;
2532 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2533 if (removeMathHull) {
2534 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2535 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2538 // Treate all math constructs as simple math
2539 interval_.par[found._tokenstart] = '$';
2540 interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2541 interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2542 interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2544 evaluatingMath = true;
2547 // begin|end of unknown env, discard
2548 // First handle tables
2549 // longtable|tabular
2550 bool discardComment;
2552 found.keytype = KeyInfo::doRemove;
2553 if ((sub.str(7).compare("longtable") == 0) ||
2554 (sub.str(7).compare("tabular") == 0)) {
2555 discardComment = true; /* '%' */
2558 discardComment = false;
2559 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2561 string token = sub.str(7);
2562 if (regex_match(token, sub2, removeArgs)) {
2563 found.keytype = KeyInfo::removeWithArg;
2566 // discard spaces before pos(2)
2567 int pos = sub.position(size_t(2));
2569 for (count = 0; pos - count > 0; count++) {
2570 char c = interval_.par[pos-count-1];
2571 if (discardComment) {
2572 if ((c != ' ') && (c != '%'))
2578 found._tokenstart = pos - count;
2579 if (sub.str(3).compare(0, 5, "begin") == 0) {
2580 size_t pos1 = pos + sub.str(2).length();
2581 if (sub.str(7).compare("cjk") == 0) {
2582 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2583 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2585 found.keytype = KeyInfo::isMain;
2586 found._dataStart = pos1;
2587 found._dataEnd = interval_.par.length();
2588 found.disabled = keys["foreignlanguage"].disabled;
2589 found.used = keys["foreignlanguage"].used;
2590 found._tokensize = pos1 - found._tokenstart;
2591 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2594 // Swallow possible optional params
2595 while (interval_.par[pos1] == '[') {
2596 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2598 // Swallow also the eventual parameter
2599 if (interval_.par[pos1] == '{') {
2600 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2603 found._dataEnd = pos1;
2605 found._dataStart = found._dataEnd;
2606 found._tokensize = count + found._dataEnd - pos;
2607 found.parenthesiscount = 0;
2608 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2609 found.disabled = true;
2613 // Handle "\end{...}"
2614 found._dataStart = pos + sub.str(2).length();
2615 found._dataEnd = found._dataStart;
2616 found._tokensize = count + found._dataEnd - pos;
2617 found.parenthesiscount = 0;
2618 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2619 found.disabled = true;
2623 else if (found.keytype != KeyInfo::isRegex) {
2624 found._tokenstart = sub.position(size_t(2));
2625 if (found.parenthesiscount == 0) {
2626 // Probably to be discarded
2627 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2628 char following = interval_.par[following_pos];
2629 if (following == ' ')
2630 found.head = "\\" + sub.str(5) + " ";
2631 else if (following == '=') {
2632 // like \uldepth=1000pt
2633 found.head = sub.str(2);
2636 found.head = "\\" + key;
2637 found._tokensize = found.head.length();
2638 found._dataEnd = found._tokenstart + found._tokensize;
2639 found._dataStart = found._dataEnd;
2642 int params = found._tokenstart + key.length() + 1;
2643 if (evaluatingOptional) {
2644 if (size_t(found._tokenstart) > optionalEnd) {
2645 evaluatingOptional = false;
2648 found.disabled = true;
2651 int optend = params;
2652 while (interval_.par[optend] == '[') {
2653 // discard optional parameters
2654 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2656 if (optend > params) {
2657 key += interval_.par.substr(params, optend-params);
2658 evaluatingOptional = true;
2659 optionalEnd = optend;
2660 if (found.keytype == KeyInfo::isSectioning) {
2661 // Remove optional values (but still keep in header)
2662 interval_.addIntervall(params, optend);
2665 string token = sub.str(7);
2667 if (interval_.par[optend] != '{') {
2669 found.parenthesiscount = 0;
2670 found.head = "\\" + key;
2673 closings = found.parenthesiscount;
2674 if (found.parenthesiscount == 1) {
2675 found.head = "\\" + key + "{";
2677 else if (found.parenthesiscount > 1) {
2679 found.head = sub.str(2) + "{";
2680 closings = found.parenthesiscount - 1;
2683 found.head = "\\" + key + "{";
2686 found._tokensize = found.head.length();
2687 found._dataStart = found._tokenstart + found.head.length();
2688 if (found.keytype == KeyInfo::doRemove) {
2690 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2691 if (endpar >= interval_.par.length())
2692 found._dataStart = interval_.par.length();
2694 found._dataStart = endpar;
2695 found._tokensize = found._dataStart - found._tokenstart;
2698 found._dataStart = found._tokenstart + found._tokensize;
2702 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2703 found._dataStart += 15;
2707 endpos = found._dataStart - 1;
2709 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2710 if (found.keytype == KeyInfo::isList) {
2711 // Check if it really is list env
2712 static regex const listre("^([a-z]+)$");
2714 if (!regex_match(token, sub2, listre)) {
2715 // Change the key of this entry. It is not in a list/item environment
2716 found.keytype = KeyInfo::endArguments;
2719 if (found.keytype == KeyInfo::noMain) {
2720 evaluatingCode = true;
2722 codeStart = found._dataStart;
2724 else if (evaluatingCode) {
2725 if (size_t(found._dataStart) > codeEnd)
2726 evaluatingCode = false;
2727 else if (found.keytype == KeyInfo::isMain) {
2728 // Disable this key, treate it as standard
2729 found.keytype = KeyInfo::isStandard;
2730 found.disabled = true;
2731 if ((codeEnd +1 >= interval_.par.length()) &&
2732 (found._tokenstart == codeStart)) {
2733 // trickery, because the code inset starts
2734 // with \selectlanguage ...
2736 if (entries_.size() > 1) {
2737 entries_[entries_.size()-1]._dataEnd = codeEnd;
2742 if ((endpos == interval_.par.length()) &&
2743 (found.keytype == KeyInfo::doRemove)) {
2744 // Missing closing => error in latex-input?
2745 // therefore do not delete remaining data
2746 found._dataStart -= 1;
2747 found._dataEnd = found._dataStart;
2750 found._dataEnd = endpos;
2752 if (isPatternString) {
2753 keys[key].used = true;
2756 entries_.push_back(found);
2760 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2762 stringstream s(keysstring);
2764 const char delim = '|';
2765 while (getline(s, key, delim)) {
2766 KeyInfo keyII(keyI);
2767 if (isPatternString) {
2770 else if ( !keys[key].used)
2771 keyII.disabled = true;
2776 void LatexInfo::buildKeys(bool isPatternString)
2779 static bool keysBuilt = false;
2780 if (keysBuilt && !isPatternString) return;
2782 // Keys to ignore in any case
2783 makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2784 makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2785 // Known standard keys with 1 parameter.
2786 // Split is done, if not at start of region
2787 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2788 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2789 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2790 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2791 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2792 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2794 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2795 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2796 makeKey("section*|subsection*|subsubsection*|paragraph*",
2797 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2798 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2799 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2801 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2803 // Split is done, if not at start of region
2804 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2805 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2807 // Split is done always.
2808 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2812 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2813 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2814 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2815 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2817 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2818 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2819 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2820 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2822 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2823 // Custom space/skip, remove the content (== length value)
2824 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2825 // Found in fr/UserGuide.lyx
2826 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2828 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2829 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2830 // Known macros to remove (including their parameter)
2832 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2833 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2834 // handle like standard keys with 1 parameter.
2835 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2837 if (ignoreFormats.getDeleted()) {
2838 // Ignore deleted text
2839 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2842 // but preserve added text
2843 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2845 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2847 // Macros to remove, but let the parameter survive
2849 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2851 // Remove language spec from content of these insets
2852 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2854 // Same effect as previous, parameter will survive (because there is no one anyway)
2856 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2857 // Remove table decorations
2858 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2859 // Discard shape-header.
2860 // For footnote or shortcut too, because of lang settings
2861 // and wrong handling if used 'KeyInfo::noMain'
2862 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2863 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2864 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2865 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2866 makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2867 makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2868 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2869 // like ('tiny{}' or '\tiny ' ... )
2870 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2872 // Survives, like known character
2873 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2874 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2875 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2877 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2878 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2879 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2881 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2882 // Remove RTL/LTR marker
2883 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2884 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2885 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2886 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2887 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2888 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2889 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2890 if (isPatternString) {
2891 // Allow the first searched string to rebuild the keys too
2895 // no need to rebuild again
2901 * Keep the list of actual opened parentheses actual
2902 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2904 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2907 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2911 if (c == '\\') skip = 1;
2912 else if (c == '{') {
2915 else if (c == '}') {
2916 handleCloseP(i, closingAllowed);
2922 string Intervall::show(int lastpos)
2924 int idx = 0; /* int intervalls */
2927 if ((unsigned) lastpos > par.size())
2928 lastpos = par.size();
2929 for (idx = 0; idx <= ignoreidx; idx++) {
2930 while (i < lastpos) {
2932 if (i <= borders[idx].low) {
2933 if (borders[idx].low > lastpos)
2934 printsize = lastpos - i;
2936 printsize = borders[idx].low - i;
2937 s += par.substr(i, printsize);
2939 if (i >= borders[idx].low)
2940 i = borders[idx].upper;
2943 i = borders[idx].upper;
2949 s += par.substr(i, lastpos-i);
2955 void Intervall::output(ostringstream &os, int lastpos)
2957 // get number of chars to output
2958 int idx = 0; /* int intervalls */
2961 string startTitle = titleValue;
2962 for (idx = 0; idx <= ignoreidx; idx++) {
2964 if (i <= borders[idx].low) {
2966 if (borders[idx].low > lastpos)
2967 printsize = lastpos - i;
2969 printsize = borders[idx].low - i;
2970 if (printsize > 0) {
2971 os << startTitle << par.substr(i, printsize);
2973 printed += printsize;
2976 handleParentheses(i, false);
2977 if (i >= borders[idx].low)
2978 i = borders[idx].upper;
2981 i = borders[idx].upper;
2988 os << startTitle << par.substr(i, lastpos-i);
2989 printed += lastpos-i;
2991 handleParentheses(lastpos, false);
2993 if (keys["foreignlanguage"].disabled)
2994 startindex = actualdeptindex-langcount;
2996 startindex = actualdeptindex;
2997 for (int i = startindex; i > 0; --i) {
3000 if (hasTitle && (printed > 0))
3002 if (! isPatternString_)
3004 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3007 void LatexInfo::processRegion(int start, int region_end)
3009 while (start < region_end) { /* Let {[} and {]} survive */
3010 int cnt = interval_.isOpeningPar(start);
3012 // Closing is allowed past the region
3013 int closing = interval_.findclosing(start+1, interval_.par.length());
3014 interval_.addIntervall(start, start+1);
3015 interval_.addIntervall(closing, closing+1);
3019 start = interval_.nextNotIgnored(start+1);
3023 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3025 if (actual.parenthesiscount == 0) {
3026 // "{\tiny{} ...}" ==> "{{} ...}"
3027 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3030 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3031 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3032 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3036 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3039 switch (actual.keytype)
3041 case KeyInfo::isTitle: {
3043 nextKeyIdx = getNextKey();
3046 case KeyInfo::cleanToStart: {
3047 actual._dataEnd = actual._dataStart;
3048 nextKeyIdx = getNextKey();
3049 // Search for end of arguments
3050 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3052 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3053 entries_[i].disabled = true;
3055 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3057 while (interval_.par[actual._dataEnd] == ' ')
3059 interval_.addIntervall(0, actual._dataEnd+1);
3060 interval_.actualdeptindex = 0;
3061 interval_.depts[0] = actual._dataEnd+1;
3062 interval_.closes[0] = -1;
3065 case KeyInfo::isText:
3066 interval_.par[actual._tokenstart] = '#';
3067 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3068 nextKeyIdx = getNextKey();
3070 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
3071 if (actual.disabled)
3072 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3074 interval_.addIntervall(actual._dataStart, actual._dataEnd);
3077 case KeyInfo::isChar: {
3078 nextKeyIdx = getNextKey();
3081 case KeyInfo::isSize: {
3082 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3083 if (actual.parenthesiscount == 0)
3084 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3086 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3088 nextKeyIdx = getNextKey();
3090 // Here _dataStart points to '{', so correct it
3091 actual._dataStart += 1;
3092 actual._tokensize += 1;
3093 actual.parenthesiscount = 1;
3094 if (interval_.par[actual._dataStart] == '}') {
3095 // Determine the end if used like '{\tiny{}...}'
3096 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3097 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3100 // Determine the end if used like '\tiny{...}'
3101 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3103 // Split on this key if not at start
3104 int start = interval_.nextNotIgnored(previousStart);
3105 if (start < actual._tokenstart) {
3106 interval_.output(os, actual._tokenstart);
3107 interval_.addIntervall(start, actual._tokenstart);
3109 // discard entry if at end of actual
3110 nextKeyIdx = process(os, actual);
3114 case KeyInfo::endArguments: {
3115 // Remove trailing '{}' too
3116 actual._dataStart += 1;
3117 actual._dataEnd += 1;
3118 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3119 nextKeyIdx = getNextKey();
3122 case KeyInfo::noMain:
3124 case KeyInfo::isStandard: {
3125 if (actual.disabled) {
3127 processRegion(actual._dataStart, actual._dataStart+1);
3128 nextKeyIdx = getNextKey();
3130 // Split on this key if not at datastart of calling entry
3131 int start = interval_.nextNotIgnored(previousStart);
3132 if (start < actual._tokenstart) {
3133 interval_.output(os, actual._tokenstart);
3134 interval_.addIntervall(start, actual._tokenstart);
3136 // discard entry if at end of actual
3137 nextKeyIdx = process(os, actual);
3141 case KeyInfo::removeWithArg: {
3142 nextKeyIdx = getNextKey();
3143 // Search for end of arguments
3144 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3146 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3147 entries_[i].disabled = true;
3149 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3151 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3154 case KeyInfo::doRemove: {
3155 // Remove the key with all parameters and following spaces
3158 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3159 start = actual._dataEnd;
3161 start = actual._dataEnd+1;
3162 for (pos = start; pos < interval_.par.length(); pos++) {
3163 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3166 // Remove also enclosing parentheses [] and {}
3169 while (actual._tokenstart > numpars) {
3170 if (pos+numpars >= interval_.par.size())
3172 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3174 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3180 if (interval_.par[pos+numpars] == ' ')
3184 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3185 nextKeyIdx = getNextKey();
3188 case KeyInfo::isList: {
3189 // Discard space before _tokenstart
3191 for (count = 0; count < actual._tokenstart; count++) {
3192 if (interval_.par[actual._tokenstart-count-1] != ' ')
3195 nextKeyIdx = getNextKey();
3196 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3198 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3200 // How else can we catch this one?
3201 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3202 entries_[i].disabled = true;
3204 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3206 else if (nextKeyIdx > 0) {
3207 // Ignore any lang entries inside data region
3208 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3209 if (entries_[i].keytype == KeyInfo::isMain)
3210 entries_[i].disabled = true;
3213 if (actual.disabled) {
3214 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3217 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3219 if (interval_.par[actual._dataEnd+1] == '[') {
3220 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3221 if ((interval_.par[actual._dataEnd+2] == '{') &&
3222 (interval_.par[posdown-1] == '}')) {
3223 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3224 interval_.addIntervall(posdown-1, posdown+1);
3227 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3228 interval_.addIntervall(posdown, posdown+1);
3230 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3231 if (blk > posdown) {
3232 // Discard at most 1 space after empty item
3234 for (count = 0; count < 1; count++) {
3235 if (interval_.par[blk+count] != ' ')
3239 interval_.addIntervall(blk, blk+count);
3244 case KeyInfo::isSectioning: {
3245 // Discard spaces before _tokenstart
3247 int val = actual._tokenstart;
3248 for (count = 0; count < actual._tokenstart;) {
3249 val = interval_.previousNotIgnored(val-1);
3250 if (val < 0 || interval_.par[val] != ' ')
3253 count = actual._tokenstart - val;
3256 if (actual.disabled) {
3257 removeHead(actual, count);
3258 nextKeyIdx = getNextKey();
3260 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3261 nextKeyIdx = process(os, actual);
3265 case KeyInfo::isMath: {
3266 // Same as regex, use the content unchanged
3267 nextKeyIdx = getNextKey();
3270 case KeyInfo::isRegex: {
3271 // DO NOT SPLIT ON REGEX
3273 nextKeyIdx = getNextKey();
3276 case KeyInfo::isIgnored: {
3277 // Treat like a character for now
3278 nextKeyIdx = getNextKey();
3281 case KeyInfo::isMain: {
3282 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3283 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3284 if (actual._tokenstart > 0) {
3285 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3286 if ((prev >= 0) && interval_.par[prev] == '%')
3287 interval_.addIntervall(prev, prev+1);
3289 if (actual.disabled) {
3291 interval_.langcount++;
3292 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3293 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3294 // Discard also the space before math-equation
3295 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3297 nextKeyIdx = getNextKey();
3298 // interval.resetOpenedP(actual._dataStart-1);
3301 if (actual._tokenstart < 26) {
3302 // for the first (and maybe dummy) language
3303 interval_.setForDefaultLang(actual);
3305 interval_.resetOpenedP(actual._dataStart-1);
3309 case KeyInfo::invalid:
3310 case KeyInfo::headRemove:
3311 // These two cases cannot happen, already handled
3314 // LYXERR(Debug::INFO, "Unhandled keytype");
3315 nextKeyIdx = getNextKey();
3322 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3324 int end = interval_.nextNotIgnored(actual._dataEnd);
3325 int oldStart = actual._dataStart;
3326 int nextKeyIdx = getNextKey();
3328 if ((nextKeyIdx < 0) ||
3329 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3330 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3331 if (oldStart <= end) {
3332 processRegion(oldStart, end);
3337 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3339 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3340 (void) dispatch(os, actual._dataStart, nextKey);
3341 end = nextKey._tokenstart;
3344 processRegion(oldStart, nextKey._tokenstart);
3345 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3347 oldStart = nextKey._dataEnd+1;
3349 // now nextKey is either invalid or is outside of actual._dataEnd
3350 // output the remaining and discard myself
3351 if (oldStart <= end) {
3352 processRegion(oldStart, end);
3354 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3356 // This is the normal case.
3357 // But if using the firstlanguage, the closing may be missing
3359 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3361 if (actual._dataEnd < end)
3362 output_end = interval_.nextNotIgnored(actual._dataEnd);
3363 else if (interval_.par.size() > (size_t) end)
3364 output_end = interval_.nextNotIgnored(end);
3366 output_end = interval_.par.size();
3367 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3368 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3370 // Remove possible empty data
3371 int dstart = interval_.nextNotIgnored(actual._dataStart);
3372 while (interval_.isOpeningPar(dstart) == 1) {
3373 interval_.addIntervall(dstart, dstart+1);
3374 int dend = interval_.findclosing(dstart+1, output_end);
3375 interval_.addIntervall(dend, dend+1);
3376 dstart = interval_.nextNotIgnored(dstart+1);
3378 if (dstart < output_end)
3379 interval_.output(os, output_end);
3381 interval_.addIntervall(0, end);
3383 interval_.addIntervall(actual._tokenstart, end);
3387 string splitOnKnownMacros(string par, bool isPatternString)
3390 LatexInfo li(par, isPatternString);
3391 // LYXERR(Debug::INFO, "Berfore split: " << par);
3392 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3394 DummyKey._tokensize = 0;
3395 DummyKey._dataStart = 0;
3396 DummyKey._dataEnd = par.length();
3397 DummyKey.disabled = true;
3398 int firstkeyIdx = li.getFirstKey();
3400 if (firstkeyIdx >= 0) {
3401 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3402 DummyKey._tokenstart = firstKey._tokenstart;
3404 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3405 // Use dummy firstKey
3406 firstKey = DummyKey;
3407 (void) li.setNextKey(firstkeyIdx);
3410 if (par.substr(firstKey._dataStart, 2) == "% ")
3411 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3413 nextkeyIdx = li.process(os, firstKey);
3414 while (nextkeyIdx >= 0) {
3415 // Check for a possible gap between the last
3416 // entry and this one
3417 int datastart = li.nextNotIgnored(firstKey._dataStart);
3418 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3419 if ((nextKey._tokenstart > datastart)) {
3421 firstKey._dataStart = datastart;
3422 firstKey._dataEnd = par.length();
3423 (void) li.setNextKey(nextkeyIdx);
3424 // Fake the last opened parenthesis
3425 li.setForDefaultLang(firstKey);
3426 nextkeyIdx = li.process(os, firstKey);
3429 if (nextKey.keytype != KeyInfo::isMain) {
3430 firstKey._dataStart = datastart;
3431 firstKey._dataEnd = nextKey._dataEnd+1;
3432 (void) li.setNextKey(nextkeyIdx);
3433 li.setForDefaultLang(firstKey);
3434 nextkeyIdx = li.process(os, firstKey);
3437 nextkeyIdx = li.process(os, nextKey);
3441 // Handle the remaining
3442 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3443 firstKey._dataEnd = par.length();
3445 if ((firstKey._dataStart < firstKey._dataEnd) &&
3446 (par[firstKey._dataStart] != '}')) {
3447 li.setForDefaultLang(firstKey);
3448 (void) li.process(os, firstKey);
3451 // return string definitelly impossible to match, but should be known
3454 s = par; /* no known macros found */
3455 // LYXERR(Debug::INFO, "After split: " << s);
3460 * Try to unify the language specs in the latexified text.
3461 * Resulting modified string is set to "", if
3462 * the searched tex does not contain all the features in the search pattern
3464 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3466 static Features regex_f;
3467 static int missed = 0;
3468 static bool regex_with_format = false;
3470 int parlen = par.length();
3472 while ((parlen > 0) && (par[parlen-1] == '\n')) {
3476 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3477 // Happens to be there in case of description or labeling environment
3483 // Split the latex input into pieces which
3484 // can be digested by our search engine
3485 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3486 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3487 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3488 string doclang = pbuf->params().language->polyglossia();
3489 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3491 bool toIgnoreLang = true;
3492 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3494 if (sub.str(2) != doclang) {
3495 toIgnoreLang = false;
3499 setIgnoreFormat("language", toIgnoreLang, false);
3502 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3503 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3506 result = par.substr(0, parlen);
3507 if (isPatternString) {
3510 regex_f = identifyFeatures(result);
3511 string features = "";
3512 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3513 string a = it->first;
3514 regex_with_format = true;
3515 features += " " + a;
3516 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3518 LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3521 } else if (regex_with_format) {
3522 Features info = identifyFeatures(result);
3523 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3524 string a = it->first;
3525 bool b = it->second;
3526 if (b && ! info[a]) {
3528 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3535 // LYXERR(Debug::INFO, "No regex formats");
3541 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3542 static void identifyClosing(string & t, bool ignoreformat)
3545 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3546 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3548 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3550 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3552 if (! ignoreformat) {
3553 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3561 static int num_replaced = 0;
3562 static bool previous_single_replace = true;
3564 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3567 if (regexp_str.empty() || regexp2_str.empty()) {
3568 regexIsValid = false;
3569 regexError = "Invalid empty regex";
3572 // Handle \w properly
3573 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3574 if (! opt.casesensitive) {
3575 popts |= QRegularExpression::CaseInsensitiveOption;
3577 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3578 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3580 if (regexp.isValid() && regexp2.isValid()) {
3581 regexIsValid = true;
3582 // Check '{', '}' pairs inside the regex
3585 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3586 char c = par_as_string[i];
3593 else if (c == '}') {
3600 if (balanced != 0) {
3601 regexIsValid = false;
3602 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3606 regexIsValid = false;
3607 if (!regexp.isValid())
3608 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3610 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3613 (void)par_as_string;
3614 if (opt.casesensitive) {
3615 regexp = regex(regexp_str);
3616 regexp2 = regex(regexp2_str);
3619 regexp = regex(regexp_str, std::regex_constants::icase);
3620 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3625 static void modifyRegexForMatchWord(string &t)
3628 regex wordre("(\\\\)*((\\.|\\\\b))");
3631 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3633 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3636 else if (sub.str(2) == "\\\\b")
3638 if (lastpos < (size_t) sub.position(2))
3639 s += t.substr(lastpos, sub.position(2) - lastpos);
3641 lastpos = sub.position(2) + sub.length(2);
3644 s = "\\b" + t + "\\b";
3648 else if (lastpos < t.length())
3649 s += t.substr(lastpos, t.length() - lastpos);
3650 t = "\\b" + s + "\\b";
3653 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3654 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3656 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3657 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3659 CreateRegexp(opt, "", "", "");
3662 use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3663 if (opt.replace_all && previous_single_replace) {
3664 previous_single_replace = false;
3667 else if (!opt.replace_all) {
3668 num_replaced = 0; // count number of replaced strings
3669 previous_single_replace = true;
3671 // When using regexp, braces are hacked already by escape_for_regex()
3672 par_as_string = normalize(ds, opt.ignoreformat);
3674 close_wildcards = 0;
3676 size_t lead_size = 0;
3677 // correct the language settings
3678 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3679 if (par_as_string.empty()) {
3680 CreateRegexp(opt, "", "", "");
3683 opt.matchAtStart = false;
3685 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3686 if (opt.ignoreformat) {
3690 lead_size = identifyLeading(par_as_string);
3692 lead_as_string = par_as_string.substr(0, lead_size);
3693 string lead_as_regex_string = string2regex(lead_as_string);
3694 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3695 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3696 /* Handle whole words too in this case
3698 if (opt.matchword) {
3699 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3700 opt.matchword = false;
3702 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3703 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3704 CreateRegexp(opt, regexp_str, regexp2_str);
3706 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3707 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3711 if (!opt.ignoreformat) {
3712 lead_size = identifyLeading(par_as_string);
3713 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3714 lead_as_string = par_as_string.substr(0, lead_size);
3715 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3718 // Here we are using regexp
3719 LASSERT(use_regexp, /**/);
3721 string lead_as_regexp;
3722 if (lead_size > 0) {
3723 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3724 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3725 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3726 par_as_string = par_as_string_nolead;
3727 LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3728 LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3730 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3731 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3732 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3733 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3735 size_t lng = par_as_string.size();
3736 if (!opt.ignoreformat) {
3737 // Remove extra '\}' at end if not part of \{\.\}
3739 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3741 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3750 if (lng < par_as_string.size())
3751 par_as_string.resize(lng);
3753 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3754 if ((lng > 0) && (par_as_string[0] == '^')) {
3755 par_as_string = par_as_string.substr(1);
3757 opt.matchAtStart = true;
3759 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3760 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3761 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3763 // If entered regexp must match at begin of searched string buffer
3764 // Kornel: Added parentheses to use $1 for size of the leading string
3768 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3769 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3770 // so the convert has no effect in that case
3771 for (int i = 7; i > 0; --i) {
3772 string orig = "\\\\" + std::to_string(i);
3773 string dest = "\\" + std::to_string(i+2);
3774 while (regex_replace(par_as_string, par_as_string, orig, dest));
3776 if (opt.matchword) {
3777 modifyRegexForMatchWord(par_as_string);
3778 // opt.matchword = false;
3780 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3781 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3783 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3784 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3785 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3789 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3793 mres.searched_size = len;
3795 docstring docstr = stringifyFromForSearch(opt, cur, len);
3797 str = normalize(docstr, opt.ignoreformat);
3798 if (!opt.ignoreformat) {
3799 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3800 // remove closing '}' and '\n' to allow for use of '$' in regex
3801 size_t lng = str.size();
3802 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3804 if (lng != str.size()) {
3805 str = str.substr(0, lng);
3807 // Replace occurences of '~' to ' '
3808 static std::regex specialChars { R"(~)" };
3809 str = std::regex_replace(str, specialChars, R"( )" );
3812 mres.match_len = -1;
3815 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3817 LASSERT(use_regexp, /**/);
3819 // use_regexp always true
3820 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3822 QString qstr = QString::fromStdString(str);
3823 QRegularExpression const *p_regexp;
3824 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3825 if (at_begin == MatchStringAdv::MatchFromStart) {
3828 p_regexp = ®exp2;
3830 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3831 if (!match.hasMatch())
3834 regex const *p_regexp;
3835 regex_constants::match_flag_type flags;
3836 if (at_begin == MatchStringAdv::MatchFromStart) {
3837 flags = regex_constants::match_continuous;
3840 flags = regex_constants::match_default;
3841 p_regexp = ®exp2;
3843 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3844 if (re_it == sregex_iterator())
3846 match_results<string::const_iterator> const & m = *re_it;
3848 // Whole found string, including the leading
3849 // std: m[0].second - m[0].first
3850 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3852 // Size of the leading string
3853 // std: m[1].second - m[1].first
3854 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3855 int leadingsize = 0;
3857 if (match.lastCapturedIndex() > 0) {
3858 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3863 leadingsize = m[1].second - m[1].first;
3867 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3868 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3869 // because of different number of closing at end of string
3870 // we have to 'unify' the length of the post-match.
3871 // Done by ignoring closing parenthesis and linefeeds at string end
3872 int matchend = match.capturedEnd(0);
3873 size_t strsize = qstr.size();
3874 if (!opt.ignoreformat) {
3875 while (mres.match_len > 1) {
3876 QChar c = qstr.at(matchend - 1);
3877 if ((c == '\n') || (c == '}') || (c == '{')) {
3884 while (strsize > (size_t) match.capturedEnd(0)) {
3885 QChar c = qstr.at(strsize-1);
3886 if ((c == '\n') || (c == '}')) {
3893 // LYXERR0(qstr.toStdString());
3894 mres.match2end = strsize - matchend;
3895 mres.pos = match.capturedStart(2);
3897 mres.match_prefix = m[2].second - m[2].first;
3898 mres.match_len = m[0].second - m[2].second;
3899 // ignore closing parenthesis and linefeeds at string end
3900 size_t strend = m[0].second - m[0].first;
3901 int matchend = strend;
3902 size_t strsize = str.size();
3903 if (!opt.ignoreformat) {
3904 while (mres.match_len > 1) {
3905 char c = str.at(matchend - 1);
3906 if ((c == '\n') || (c == '}') || (c == '{')) {
3913 while (strsize > strend) {
3914 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3922 mres.match2end = strsize - matchend;
3923 mres.pos = m[2].first - m[0].first;;
3925 if (mres.match2end < 0)
3927 mres.leadsize = leadingsize;
3929 if (mres.match_len > 0) {
3930 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3931 mres.result.push_back(a0);
3932 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3933 mres.result.push_back(match.captured(i).toStdString());
3937 if (mres.match_len > 0) {
3938 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3939 mres.result.push_back(a0);
3940 for (size_t i = 3; i < m.size(); i++) {
3941 mres.result.push_back(m[i]);
3950 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3952 MatchResult mres = findAux(cur, len, at_begin);
3953 LYXERR(Debug::FINDVERBOSE,
3954 "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3955 << ", matchAtStart=" << opt.matchAtStart
3956 << ", inTexted=" << cur.inTexted());
3957 if (mres.match_len > 0) {
3958 if (opt.matchAtStart) {
3959 if (cur.pos() > 0 || mres.match_prefix > 0)
3967 static bool simple_replace(string &t, string from, string to)
3969 regex repl("(\\\\)*(" + from + ")");
3973 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3975 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3977 if (lastpos < (size_t) sub.position(2))
3978 s += t.substr(lastpos, sub.position(2) - lastpos);
3980 lastpos = sub.position(2) + sub.length(2);
3984 else if (lastpos < t.length())
3985 s += t.substr(lastpos, t.length() - lastpos);
3992 static string convertLF2Space(docstring const &s, bool ignore_format)
3994 // Using original docstring to handle '\n'
3996 if (s.size() == 0) return "";
4000 size_t end = s.size() - 1;
4001 if (!ignore_format) {
4002 while (s[start] == '\n' && start <= end)
4004 while (end >= start && s[end] == '\n')
4006 if (start >= end + 1)
4010 bool dospace = true;
4012 pos = s.find('\n', start);
4014 t << lyx::to_utf8(s.substr(start, end + 1 - start));
4017 if (!ignore_format) {
4018 if ((pos > start + 1) &&
4022 if ((pos > start + 2) &&
4023 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4024 s[pos-3] == '~' || isSpace(s[pos-3]))) {
4025 // discard "\\\\\n", do not replace with space
4029 else if (pos > start) {
4030 if (s[pos-1] == '%') {
4032 while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4034 if ((pos > start+skip) &&
4035 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4036 s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4037 // discard '%%%%%\n'
4041 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4043 skip = 0; // remove the '\n' only
4051 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4055 } while (start <= end);
4060 static string convertLF2Space(docstring const & s, bool ignore_format)
4062 // Using utf8-converted string to handle '\n'
4065 t = lyx::to_utf8(s);
4066 // Remove \n at begin
4067 while (!t.empty() && t[0] == '\n')
4069 // Remove \n* at end
4070 while (!t.empty() && t[t.size() - 1] == '\n') {
4071 t = t.substr(0, t.size() - 1);
4074 // Handle all other '\n'
4075 while ((pos = t.find("\n")) != string::npos) {
4076 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
4078 if (isPrintableNonspace(t[pos+1]) && ((pos < 3) || isPrintableNonspace(t[pos-3]))) {
4079 t.replace(pos-2, 3, " ");
4082 // Already a space there
4083 t.replace(pos-2, 3, "");
4087 if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
4088 // '\n' adjacent to non-alpha-numerics, discard
4089 t.replace(pos, 1, "");
4092 // Replace all other \n with spaces
4093 t.replace(pos, 1, " ");
4095 if (!ignore_format) {
4097 while ((pos > count + 1) && (t[pos - 1 -count] == '%')) {
4101 t.replace(pos - count, count, "");
4111 string MatchStringAdv::normalize(docstring const & s, bool ignore_format) const
4113 string t = convertLF2Space(s, ignore_format);
4115 // The following replaces are not appropriate in non-format-search mode
4116 if (!ignore_format) {
4117 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
4118 // Kornel: Added textsl, textsf, textit, texttt and noun
4119 // + allow to seach for colored text too
4120 LYXERR(Debug::FINDVERBOSE, "Removing stale empty macros from: " << t);
4121 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
4122 LYXERR(Debug::FINDVERBOSE, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
4123 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
4124 LYXERR(Debug::FINDVERBOSE, " further removing stale empty \\section{}, \\part{}, \\paragraph{} macros from: " << t);
4125 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
4130 docstring stringifyFromCursor(DocIterator const & cur, int len)
4132 LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4133 if (cur.inTexted()) {
4134 Paragraph const & par = cur.paragraph();
4135 // TODO what about searching beyond/across paragraph breaks ?
4136 // TODO Try adding a AS_STR_INSERTS as last arg
4137 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4138 int(par.size()) : cur.pos() + len;
4139 // OutputParams runparams(&cur.buffer()->params().encoding());
4140 OutputParams runparams(encodings.fromLyXName("utf8"));
4141 runparams.nice = true;
4142 setFindParams(runparams);
4143 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4144 if (ignoreFormats.getDeleted()) {
4145 option |= AS_STR_SKIPDELETE;
4146 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4149 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4151 if (ignoreFormats.getNonContent()) {
4152 runparams.find_add_feature(OutputParams::SearchNonOutput);
4154 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4155 << cur << ", from pos: " << cur.pos() << ", end: " << end);
4156 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4158 &runparams), false));
4159 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4161 } else if (cur.inMathed()) {
4162 CursorSlice cs = cur.top();
4163 MathData md = cs.cell();
4164 MathData::const_iterator it_end =
4165 (( len == -1 || cs.pos() + len > int(md.size()))
4167 : md.begin() + cs.pos() + len );
4169 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4171 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4172 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4175 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4179 /** Computes the LaTeX export of buf starting from cur and ending len positions
4180 * after cur, if len is positive, or at the paragraph or innermost inset end
4183 docstring latexifyFromCursor(DocIterator const & cur, int len)
4186 LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4187 LYXERR(Debug::FINDVERBOSE, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4188 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4190 Buffer const & buf = *cur.buffer();
4192 odocstringstream ods;
4194 //OutputParams runparams(&buf.params().encoding());
4195 OutputParams runparams(encodings.fromLyXName("utf8"));
4196 runparams.nice = false;
4197 setFindParams(runparams);
4198 if (ignoreFormats.getDeleted()) {
4199 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4202 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4204 if (ignoreFormats.getNonContent()) {
4205 runparams.find_add_feature(OutputParams::SearchNonOutput);
4208 if (cur.inTexted()) {
4209 // @TODO what about searching beyond/across paragraph breaks ?
4210 pos_type endpos = cur.paragraph().size();
4211 if (len != -1 && endpos > cur.pos() + len)
4212 endpos = cur.pos() + len;
4213 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4214 string(), cur.pos(), endpos, true);
4215 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4217 } else if (cur.inMathed()) {
4218 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4219 for (int s = cur.depth() - 1; s >= 0; --s) {
4220 CursorSlice const & cs = cur[s];
4221 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4222 TeXMathStream ws(os);
4223 cs.asInsetMath()->asHullInset()->header_write(ws);
4228 CursorSlice const & cs = cur.top();
4229 MathData md = cs.cell();
4230 MathData::const_iterator it_end =
4231 ((len == -1 || cs.pos() + len > int(md.size()))
4233 : md.begin() + cs.pos() + len);
4235 for (MathData::const_iterator it = md.begin() + cs.pos();
4239 ods << asString(md2);
4240 // Retrieve the math environment type, and add '$' or '$]'
4241 // or others (\end{equation}) accordingly
4242 for (int s = cur.depth() - 1; s >= 0; --s) {
4243 CursorSlice const & cs2 = cur[s];
4244 InsetMath * inset = cs2.asInsetMath();
4245 if (inset && inset->asHullInset()) {
4246 TeXMathStream ws(os);
4247 inset->asHullInset()->footer_write(ws);
4251 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4253 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4258 #if defined(ResultsDebug)
4260 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4262 LYXERR0( "from:\t\t\t" << from);
4264 if (mres.pos_len > 0) {
4266 status = "FINALSEARCH";
4269 if (mres.match_len > 0) {
4270 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4271 status = "Good Match";
4273 status = "Matched in";
4276 status = "MissedSearch";
4279 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4280 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4281 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4282 if ((mres.pos > 0) || (mres.match_prefix > 0))
4283 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4284 for (size_t i = 0; i < mres.result.size(); i++)
4285 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4287 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4289 #define displayMres(s, txt, cur)
4292 /** Finalize an advanced find operation, advancing the cursor to the innermost
4293 ** position that matches, plus computing the length of the matching text to
4295 ** Return the cur.pos() difference between start and end of found match
4297 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4299 // Search the foremost position that matches (avoids find of entire math
4300 // inset when match at start of it)
4301 DocIterator old_cur(cur.buffer());
4303 static MatchResult fail = MatchResult();
4304 MatchResult max_match;
4305 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4306 // Happens with e.g. hyperlinks
4307 // either one sees "http://www.bla.bla" or nothing
4308 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4309 // and although we search for only 3 chars, we find the whole hyperlink inset
4310 MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4311 if (!match.opt.forward && match.opt.ignoreformat) {
4312 if (expected.pos > 0)
4315 LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4316 if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4317 // Search for deepest match
4319 max_match = expected;
4321 size_t d = cur.depth();
4325 if (cur.depth() < d)
4327 if (cur.depth() == d)
4330 while (cur && cur.depth() > lastd) {
4331 lastd = cur.depth();
4332 mres = match(cur, -1, at_begin);
4333 displayMres(mres, "Checking innermost", cur);
4334 if (mres.match_len > 0)
4339 if (mres.match_len < expected.match_len)
4347 // (expected.match_len <= 0)
4348 mres = match(cur, -1, MatchStringAdv::MatchFromStart); /* match valid only if not searching whole words */
4349 displayMres(mres, "Start with negative match", cur);
4352 // Only now we are really at_begin
4353 if ((max_match.match_len <= 0) ||
4354 (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4356 LYXERR(Debug::FINDVERBOSE, "Ok");
4358 // Compute the match length
4360 if (cur.pos() + len > cur.lastpos())
4363 LASSERT(match.use_regexp, /**/);
4366 int maxl = cur.lastpos() - cur.pos();
4367 // Greedy behaviour while matching regexps
4368 while (maxl > minl) {
4370 mres2 = match(cur, len, at_begin);
4371 displayMres(mres2, "Finalize loop", cur);
4372 int actual_match_len = mres2.match_len;
4373 if (actual_match_len >= max_match.match_len) {
4374 // actual_match_len > max_match _can_ happen,
4375 // if the search area splits
4376 // some following word so that the regex
4377 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4379 // This means, the len value is too big
4380 actual_match_len = max_match.match_len;
4382 max_match.match_len = actual_match_len;
4384 if (maxl - minl < 4)
4385 len = (maxl + minl)/2;
4387 len = minl + (maxl - minl + 3)/4;
4390 // (actual_match_len < max_match.match_len)
4392 len = (maxl + minl)/2;
4397 // Search for real start of matched characters
4399 MatchResult actual_match;
4402 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4403 if (cur.depth() < old_cur.depth()) {
4405 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4408 if (cur.pos() != old_cur.pos()) {
4409 // OK, forwarded 1 pos in actual inset
4410 actual_match = match(cur, len-1, at_begin);
4411 if (actual_match.match_len == max_match.match_len) {
4412 // Ha, got it! The shorter selection has the same match length
4415 max_match = actual_match;
4418 // OK, the shorter selection matches less chars, revert to previous value
4424 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4425 actual_match = match(cur, len, at_begin);
4426 if (actual_match.match_len == max_match.match_len) {
4428 max_match = actual_match;
4435 max_match.pos_len = len;
4436 displayMres(max_match, "SEARCH RESULT", cur)
4443 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4447 bool repeat = false;
4448 DocIterator orig_cur; // to be used if repeat not successful
4449 MatchResult orig_mres;
4450 while (!theApp()->longOperationCancelled() && cur) {
4451 //(void) findAdvForwardInnermost(cur);
4452 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4453 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4454 string msg = "Starting";
4457 displayMres(mres, msg + " findForwardAdv", cur)
4458 int match_len = mres.match_len;
4459 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4460 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4463 if (match_len <= 0) {
4464 // This should exit nested insets, if any, or otherwise undefine the currsor.
4465 cur.pos() = cur.lastpos();
4466 LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4469 else { // match_len > 0
4470 // Try to find the begin of searched string
4472 int firstInvalid = cur.lastpos() - cur.pos();
4474 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4475 int incrcur = (firstInvalid + 1 )*3/4;
4476 if (incrcur < incrmatch)
4477 increment = incrcur;
4479 increment = incrmatch;
4483 LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4484 while (increment > 0) {
4485 DocIterator old_cur = cur;
4486 if (cur.pos() + increment >= cur.lastpos()) {
4490 cur.pos() = cur.pos() + increment;
4491 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4492 displayMres(mres2, "findForwardAdv loop", cur)
4493 switch (interpretMatch(mres, mres2)) {
4494 case MatchResult::newIsTooFar:
4495 // behind the expected match
4496 firstInvalid = increment;
4500 case MatchResult::newIsBetter:
4501 // not reached yet, but cur.pos()+increment is bettert
4503 firstInvalid -= increment;
4504 if (increment > firstInvalid*3/4)
4505 increment = firstInvalid*3/4;
4506 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4507 if (increment >= mres2.match_prefix)
4508 increment = (mres2.match_prefix+1)*3/4;
4513 // Handle not like MatchResult::newIsTooFar
4514 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4516 increment = increment*3/4;
4521 if (mres.match_len > 0) {
4522 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4523 // The match seems to indicate some deeper level
4532 // should never be reached.
4536 // LYXERR0("Leaving first loop");
4537 LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4538 MatchResult found_match = findAdvFinalize(cur, match, mres);
4539 if (found_match.match_len > 0) {
4540 match.FillResults(found_match);
4541 return found_match.pos_len;
4544 // try next possible match
4555 /// Find the most backward consecutive match within same paragraph while searching backwards.
4556 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4558 DocIterator cur_begin = cur;
4559 cur_begin.pos() = 0;
4560 DocIterator tmp_cur = cur;
4561 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4562 Inset & inset = cur.inset();
4563 for (; cur != cur_begin; cur.backwardPos()) {
4564 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4565 DocIterator new_cur = cur;
4566 new_cur.backwardPos();
4567 if (new_cur == cur || &new_cur.inset() != &inset
4568 || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4570 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4571 if (new_mr.match_len == mr.match_len)
4575 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4581 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4585 // Backup of original position
4586 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4587 if (cur == cur_begin)
4590 DocIterator cur_orig(cur);
4591 bool pit_changed = false;
4594 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4596 if (found_match.match_len > 0) {
4598 cur.pos() = cur.lastpos();
4600 cur.pos() = cur_orig.pos();
4601 LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4602 DocIterator cur_prev_iter;
4604 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4605 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4606 << (found_match.match_len > 0) << ", cur: " << cur);
4607 if (found_match.match_len > 0) {
4608 MatchResult found_mr = findMostBackwards(cur, match, found_match);
4609 if (found_mr.pos_len > 0) {
4610 match.FillResults(found_mr);
4611 return found_mr.pos_len;
4615 // Stop if begin of document reached
4616 if (cur == cur_begin)
4618 cur_prev_iter = cur;
4622 if (cur == cur_begin)
4629 } while (!theApp()->longOperationCancelled());
4637 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4638 DocIterator const & cur, int len)
4640 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4642 if (!opt.ignoreformat)
4643 return latexifyFromCursor(cur, len);
4645 return stringifyFromCursor(cur, len);
4649 FindAndReplaceOptions::FindAndReplaceOptions(
4650 docstring const & _find_buf_name, bool _casesensitive,
4651 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4652 docstring const & _repl_buf_name, bool _keep_case,
4653 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4654 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4655 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4656 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4664 /** Check if 'len' letters following cursor are all non-lowercase */
4665 static bool allNonLowercase(Cursor const & cur, int len)
4667 pos_type beg_pos = cur.selectionBegin().pos();
4668 pos_type end_pos = cur.selectionBegin().pos() + len;
4669 if (len > cur.lastpos() + 1 - beg_pos) {
4670 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4671 len = cur.lastpos() + 1 - beg_pos;
4672 end_pos = beg_pos + len;
4674 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4675 if (isLowerCase(cur.paragraph().getChar(pos)))
4681 /** Check if first letter is upper case and second one is lower case */
4682 static bool firstUppercase(Cursor const & cur)
4685 pos_type pos = cur.selectionBegin().pos();
4686 if (pos >= cur.lastpos() - 1) {
4687 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4690 ch1 = cur.paragraph().getChar(pos);
4691 ch2 = cur.paragraph().getChar(pos + 1);
4692 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4693 LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4694 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4695 << ch2 << "(" << char(ch2) << ")"
4696 << ", result=" << result << ", cur=" << cur);
4701 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4703 ** \fixme What to do with possible further paragraphs in replace buffer ?
4705 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4707 ParagraphList::iterator pit = buffer.paragraphs().begin();
4708 LASSERT(!pit->empty(), /**/);
4709 pos_type right = pos_type(1);
4710 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4711 right = pit->size();
4712 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4716 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4718 // Should replace the string "$" + std::to_string(matchnum) with replacement
4719 // if the char '$' is not prefixed with odd number of char '\\'
4720 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4724 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4726 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4728 int num = stoi(sub.str(3), nullptr, 10);
4729 if (num >= maxmatchnum)
4731 if (lastpos < (size_t) sub.position(2))
4732 s += t.substr(lastpos, sub.position(2) - lastpos);
4733 s += replacements[num];
4734 lastpos = sub.position(2) + sub.length(2);
4738 else if (lastpos < t.length())
4739 s += t.substr(lastpos, t.length() - lastpos);
4745 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4747 Cursor & cur = bv->cursor();
4748 if (opt.repl_buf_name.empty()
4749 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4750 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4753 DocIterator sel_beg = cur.selectionBegin();
4754 DocIterator sel_end = cur.selectionEnd();
4755 if (&sel_beg.inset() != &sel_end.inset()
4756 || sel_beg.pit() != sel_end.pit()
4757 || sel_beg.idx() != sel_end.idx())
4759 int sel_len = sel_end.pos() - sel_beg.pos();
4760 LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4761 << ", sel_len: " << sel_len << endl);
4764 LASSERT(sel_len > 0, return 0);
4766 if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4769 // Build a copy of the replace buffer, adapted to the KeepCase option
4770 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4772 repl_buffer_orig.write(oss);
4773 string lyx = oss.str();
4774 if (matchAdv.valid_matches > 0)
4775 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4776 Buffer repl_buffer(string(), false);
4777 repl_buffer.setInternal(true);
4778 repl_buffer.setUnnamed(true);
4779 LASSERT(repl_buffer.readString(lyx), return 0);
4780 if (opt.keep_case && sel_len >= 2) {
4781 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4782 if (cur.inTexted()) {
4783 if (firstUppercase(cur))
4784 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4785 else if (allNonLowercase(cur, sel_len))
4786 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4789 cap::cutSelection(cur, false);
4790 if (cur.inTexted()) {
4791 repl_buffer.changeLanguage(
4792 repl_buffer.language(),
4793 cur.getFont().language());
4794 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4795 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4796 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4797 repl_buffer.params().documentClassPtr(),
4798 repl_buffer.params().authors(),
4799 bv->buffer().errorList("Paste"));
4800 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4801 sel_len = repl_buffer.paragraphs().begin()->size();
4802 } else if (cur.inMathed()) {
4803 odocstringstream ods;
4805 // OutputParams runparams(&repl_buffer.params().encoding());
4806 OutputParams runparams(encodings.fromLyXName("utf8"));
4807 runparams.nice = false;
4808 setFindParams(runparams);
4809 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4810 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4811 docstring repl_latex = ods.str();
4812 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4814 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4815 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4816 repl_latex = from_utf8(s);
4817 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4818 MathData ar(cur.buffer());
4819 asArray(repl_latex, ar, Parse::NORMAL);
4821 sel_len = ar.size();
4822 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4824 if (cur.pos() >= sel_len)
4825 cur.pos() -= sel_len;
4828 LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4829 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4830 bv->processUpdateFlags(Update::Force);
4834 static bool isWordChar(char_type c)
4836 return isLetterChar(c) || isNumberChar(c);
4839 /// Perform a FindAdv operation.
4840 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4845 // e.g., when invoking word-findadv from mini-buffer wither with
4846 // wrong options syntax or before ever opening advanced F&R pane
4847 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4851 MatchStringAdv matchAdv(bv->buffer(), opt);
4853 if (!matchAdv.regexIsValid) {
4854 bv->message(lyx::from_utf8(matchAdv.regexError));
4858 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4860 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4861 num_replaced += findAdvReplace(bv, opt, matchAdv);
4864 if (opt.matchword && cur.pos() > 0) { // Skip word-characters if we are in the mid of a word
4865 if (cur.inTexted()) {
4866 Paragraph const & par = cur.paragraph();
4867 int len_limit, new_pos;
4868 if (cur.lastpos() < par.size())
4869 len_limit = cur.lastpos();
4871 len_limit = par.size();
4872 for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4873 if (!isWordChar(par.getChar(new_pos)))
4876 if (new_pos > cur.pos())
4877 cur.pos() = new_pos;
4879 else if (cur.inMathed()) {
4880 // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4881 // I am not sure, we should consider the selection
4882 bool sel = bv->cursor().selection();
4883 if (!sel && cur.pos() < cur.lastpos()) {
4884 CursorSlice const & cs = cur.top();
4885 MathData md = cs.cell();
4887 MathData::const_iterator it_end = md.end();
4889 // Start the check with one character before actual cursor position
4890 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4893 docstring inp = asString(md2);
4894 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4895 if (!isWordChar(inp[len]))
4898 // len == 0 means previous char was a word separator
4899 // len == 1 search starts with a word separator
4900 // len == 2 ... we have to skip len -1 chars
4902 cur.pos() = cur.pos() + len - 1;
4905 opt.matchword = false;
4907 pos_len = findForwardAdv(cur, matchAdv);
4910 pos_len = findBackwardsAdv(cur, matchAdv);
4911 } catch (exception & ex) {
4912 bv->message(from_utf8(ex.what()));
4917 if (num_replaced > 0) {
4918 switch (num_replaced)
4921 bv->message(_("One match has been replaced."));
4924 bv->message(_("Two matches have been replaced."));
4927 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4933 bv->message(_("Match not found."));
4938 if (num_replaced > 0)
4939 bv->message(_("Match has been replaced."));
4941 bv->message(_("Match found."));
4943 if (cur.pos() + pos_len > cur.lastpos()) {
4944 // Prevent crash in bv->putSelectionAt()
4945 // Should never happen, maybe LASSERT() here?
4946 pos_len = cur.lastpos() - cur.pos();
4948 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4949 bv->putSelectionAt(cur, pos_len, !opt.forward);
4955 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4957 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4958 << opt.casesensitive << ' '
4959 << opt.matchword << ' '
4960 << opt.forward << ' '
4961 << opt.expandmacros << ' '
4962 << opt.ignoreformat << ' '
4963 << opt.replace_all << ' '
4964 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4965 << opt.keep_case << ' '
4966 << int(opt.scope) << ' '
4969 LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4975 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4977 // LYXERR(Debug::FINDVERBOSE, "parsing");
4981 while (line != "EOSS") {
4985 if (is.eof()) // Tolerate malformed request
4989 // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4990 opt.find_buf_name = from_utf8(s);
4991 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4992 is.get(); // Waste space before replace string
4995 while (line != "EOSS") {
4999 if (is.eof()) // Tolerate malformed request
5003 // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
5004 opt.repl_buf_name = from_utf8(s);
5005 is >> opt.keep_case;
5008 opt.scope = FindAndReplaceOptions::SearchScope(i);
5010 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
5013 LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
5014 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
5015 << opt.scope << ' ' << opt.restr);