3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
27 #include "CutAndPaste.h"
28 #include "FuncRequest.h"
30 #include "output_latex.h"
31 #include "OutputParams.h"
32 #include "Paragraph.h"
37 #include "frontends/Application.h"
38 #include "frontends/alert.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
54 #include <unordered_map>
57 //#define ResultsDebug
58 #define USE_QT_FOR_SEARCH
59 #if defined(USE_QT_FOR_SEARCH)
60 #include <QRegularExpression>
67 using namespace lyx::support;
71 typedef unordered_map<string, string> AccentsMap;
72 typedef unordered_map<string,string>::const_iterator AccentsIterator;
73 static AccentsMap accents = unordered_map<string, string>();
75 // Helper class for deciding what should be ignored
79 IgnoreFormats() = default;
81 bool getFamily() const { return ignoreFamily_; }
83 bool getSeries() const { return ignoreSeries_; }
85 bool getShape() const { return ignoreShape_; }
87 bool getSize() const { return ignoreSize_; }
89 bool getUnderline() const { return ignoreUnderline_; }
91 bool getMarkUp() const { return ignoreMarkUp_; }
93 bool getStrikeOut() const { return ignoreStrikeOut_; }
95 bool getSectioning() const { return ignoreSectioning_; }
97 bool getFrontMatter() const { return ignoreFrontMatter_; }
99 bool getColor() const { return ignoreColor_; }
101 bool getLanguage() const { return ignoreLanguage_; }
103 bool getDeleted() const { return ignoreDeleted_; }
105 void setIgnoreDeleted(bool value);
107 bool getNonContent() const { return searchNonContent_; }
109 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreSize_ = true;
121 bool ignoreUnderline_ = false;
123 bool ignoreMarkUp_ = false;
125 bool ignoreStrikeOut_ = false;
127 bool ignoreSectioning_ = false;
129 bool ignoreFrontMatter_ = false;
131 bool ignoreColor_ = false;
133 bool ignoreLanguage_ = false;
134 bool userSelectedIgnoreLanguage_ = false;
136 bool ignoreDeleted_ = true;
138 bool searchNonContent_ = true;
141 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
143 if (type == "color") {
144 ignoreColor_ = value;
146 else if (type == "language") {
148 userSelectedIgnoreLanguage_ = value;
149 ignoreLanguage_ = value;
152 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
154 else if (type == "sectioning") {
155 ignoreSectioning_ = value;
156 ignoreFrontMatter_ = value;
158 else if (type == "font") {
159 ignoreSeries_ = value;
160 ignoreShape_ = value;
161 ignoreFamily_ = value;
163 else if (type == "series") {
164 ignoreSeries_ = value;
166 else if (type == "shape") {
167 ignoreShape_ = value;
169 else if (type == "size") {
172 else if (type == "family") {
173 ignoreFamily_ = value;
175 else if (type == "markup") {
176 ignoreMarkUp_ = value;
178 else if (type == "underline") {
179 ignoreUnderline_ = value;
181 else if (type == "strike") {
182 ignoreStrikeOut_ = value;
184 else if (type == "deleted") {
185 ignoreDeleted_ = value;
187 else if (type == "non-output-content") {
188 searchNonContent_ = !value;
192 // The global variable that can be changed from outside
193 IgnoreFormats ignoreFormats;
196 void setIgnoreFormat(string const & type, bool value, bool fromUser)
198 ignoreFormats.setIgnoreFormat(type, value, fromUser);
204 bool parse_bool(docstring & howto, bool const defvalue = false)
209 howto = split(howto, var, ' ');
217 MatchString(docstring const & s, bool cs, bool mw)
218 : str(s), case_sens(cs), whole_words(mw)
221 // returns true if the specified string is at the specified position
222 // del specifies whether deleted strings in ct mode will be considered
223 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
225 return par.find(str, case_sens, whole_words, pos, del);
233 // match whole words only
238 int findForward(DocIterator & cur, DocIterator const endcur,
239 MatchString const & match,
240 bool find_del = true, bool onlysel = false)
242 for (; cur; cur.forwardChar()) {
243 if (onlysel && endcur.pit() == cur.pit()
244 && endcur.idx() == cur.idx() && endcur.pos() < cur.pos())
246 if (cur.inTexted()) {
247 int len = match(cur.paragraph(), cur.pos(), find_del);
256 int findBackwards(DocIterator & cur, DocIterator const endcur,
257 MatchString const & match,
258 bool find_del = true, bool onlysel = false)
262 if (onlysel && endcur.pit() == cur.pit()
263 && endcur.idx() == cur.idx() && endcur.pos() > cur.pos())
265 if (cur.inTexted()) {
266 int len = match(cur.paragraph(), cur.pos(), find_del);
275 bool searchAllowed(docstring const & str)
278 frontend::Alert::error(_("Search error"), _("Search string is empty"));
287 bool findOne(BufferView * bv, docstring const & searchstr,
288 bool case_sens, bool whole, bool forward,
289 bool find_del, bool check_wrap, bool const auto_wrap,
290 bool instant, bool onlysel)
292 // Clean up previous selections with empty searchstr on instant
293 if (searchstr.empty() && instant) {
294 if (bv->cursor().selection()) {
295 bv->setCursor(bv->cursor().selectionBegin());
296 bv->clearSelection();
301 if (!searchAllowed(searchstr))
304 DocIterator const endcur = forward ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin();
306 if (onlysel && bv->cursor().selection()) {
307 docstring const matchstring = bv->cursor().selectionAsString(false);
308 docstring const lcmatchsting = support::lowercase(matchstring);
309 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
310 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
311 "Continue search outside?");
312 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
313 q, 0, 1, _("&Yes"), _("&No"));
314 if (search_answer == 0) {
315 bv->clearSelection();
316 if (findOne(bv, searchstr, case_sens, whole, forward,
317 find_del, check_wrap, auto_wrap, false, false))
324 DocIterator cur = forward
325 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
326 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
328 MatchString const match(searchstr, case_sens, whole);
330 int match_len = forward
331 ? findForward(cur, endcur, match, find_del, onlysel)
332 : findBackwards(cur, endcur, match, find_del, onlysel);
335 bv->putSelectionAt(cur, match_len, !forward);
336 else if (onlysel && bv->cursor().selection()) {
337 docstring q = _("The search string was not found within the selection.\n"
338 "Continue search outside?");
339 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
340 q, 0, 1, _("&Yes"), _("&No"));
341 if (search_answer == 0) {
342 bv->clearSelection();
343 if (findOne(bv, searchstr, case_sens, whole, forward,
344 find_del, check_wrap, auto_wrap, false, false))
349 else if (check_wrap) {
350 DocIterator cur_orig(bv->cursor());
351 bool wrap = auto_wrap;
355 q = _("End of file reached while searching forward.\n"
356 "Continue searching from the beginning?");
358 q = _("Beginning of file reached while searching backward.\n"
359 "Continue searching from the end?");
360 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
361 q, 0, 1, _("&Yes"), _("&No"));
362 wrap = wrap_answer == 0;
366 bv->cursor().clear();
367 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
369 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
370 bv->cursor().backwardPos();
373 docstring const msg = forward
374 ? _("Search reached end of document, continuing from beginning.")
375 : _("Search reached beginning of document, continuing from end.");
378 bv->clearSelection();
379 if (findOne(bv, searchstr, case_sens, whole, forward,
380 find_del, false, false, false, false))
383 bv->cursor().setCursor(cur_orig);
387 return match_len > 0;
393 int replaceAll(BufferView * bv,
394 docstring const & searchstr, docstring const & replacestr,
395 bool case_sens, bool whole, bool onlysel)
397 Buffer & buf = bv->buffer();
399 if (!searchAllowed(searchstr) || buf.isReadonly())
402 DocIterator startcur = bv->cursor().selectionBegin();
403 DocIterator endcur = bv->cursor().selectionEnd();
404 bool const had_selection = bv->cursor().selection();
406 MatchString const match(searchstr, case_sens, whole);
409 int const rsize = replacestr.size();
410 int const ssize = searchstr.size();
413 cur.setCursor(doc_iterator_begin(&buf));
414 int match_len = findForward(cur, endcur, match, false, onlysel);
415 while (match_len > 0) {
416 // Backup current cursor position and font.
417 pos_type const pos = cur.pos();
418 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
420 int ct_deleted_text = ssize -
421 cur.paragraph().eraseChars(pos, pos + match_len,
422 buf.params().track_changes);
423 cur.paragraph().insert(pos, replacestr, font,
424 Change(buf.params().track_changes
426 : Change::UNCHANGED));
427 for (int i = 0; i < rsize + ct_deleted_text
428 && cur.pos() < cur.lastpos(); ++i)
430 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
431 // Adjust end of selection for replace-all in selection
433 int const offset = rsize - ssize;
434 for (int i = 0; i < offset + ct_deleted_text
435 && endcur.pos() < endcur.lastpos(); ++i)
438 int const offset = ssize - rsize;
439 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
440 endcur.backwardPos();
441 for (int i = 0; i < ct_deleted_text
442 && endcur.pos() < endcur.lastpos(); ++i)
447 match_len = findForward(cur, endcur, match, false, onlysel);
450 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
452 startcur.fixIfBroken();
453 bv->setCursor(startcur);
455 // Reset selection, accounting for changes in selection
457 endcur.fixIfBroken();
458 bv->cursor().resetAnchor();
459 bv->setCursorSelectionTo(endcur);
466 // the idea here is that we are going to replace the string that
467 // is selected IF it is the search string.
468 // if there is a selection, but it is not the search string, then
469 // we basically ignore it. (FIXME We ought to replace only within
471 // if there is no selection, then:
472 // (i) if some search string has been provided, then we find it.
473 // (think of how the dialog works when you hit "replace" the
475 // (ii) if no search string has been provided, then we treat the
476 // word the cursor is in as the search string. (why? i have no
477 // idea.) but this only works in text?
479 // returns the number of replacements made (one, if any) and
480 // whether anything at all was done.
481 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
482 docstring const & replacestr, bool case_sens,
483 bool whole, bool forward, bool findnext, bool wrap,
486 Cursor & cur = bv->cursor();
487 if (!cur.selection() || onlysel) {
488 // no selection, non-empty search string: find it
489 if (!searchstr.empty()) {
490 bool const found = findOne(bv, searchstr, case_sens, whole,
491 forward, true, findnext, wrap, false, onlysel);
492 return make_pair(found, 0);
494 // empty search string
497 return make_pair(false, 0);
498 // select current word and treat it as the search string.
499 // This causes a minor bug as undo will restore this selection,
500 // which the user did not create (#8986).
501 cur.innerText()->selectWord(cur, WHOLE_WORD);
502 searchstr = cur.selectionAsString(false, true);
505 // if we still don't have a search string, report the error
507 if (!searchAllowed(searchstr))
508 return make_pair(false, 0);
510 bool have_selection = cur.selection();
511 docstring const selected = cur.selectionAsString(false, true);
514 ? searchstr == selected
515 : compare_no_case(searchstr, selected) == 0;
517 // no selection or current selection is not search word:
518 // just find the search word
519 if (!have_selection || !match) {
520 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
521 true, findnext, wrap, false, onlysel);
522 return make_pair(found, 0);
525 // we're now actually ready to replace. if the buffer is
526 // read-only, we can't, though.
527 if (bv->buffer().isReadonly())
528 return make_pair(false, 0);
530 cap::replaceSelectionWithString(cur, replacestr);
532 cur.pos() += replacestr.length();
533 LASSERT(cur.pos() <= cur.lastpos(),
534 cur.pos() = cur.lastpos());
537 findOne(bv, searchstr, case_sens, whole,
538 forward, false, findnext, wrap, false, onlysel);
540 return make_pair(true, 1);
546 docstring const find2string(docstring const & search,
547 bool casesensitive, bool matchword,
548 bool forward, bool wrap, bool instant,
553 << int(casesensitive) << ' '
554 << int(matchword) << ' '
555 << int(forward) << ' '
557 << int(instant) << ' '
563 docstring const replace2string(docstring const & replace,
564 docstring const & search,
565 bool casesensitive, bool matchword,
566 bool all, bool forward, bool findnext,
567 bool wrap, bool onlysel)
570 ss << replace << '\n'
572 << int(casesensitive) << ' '
573 << int(matchword) << ' '
575 << int(forward) << ' '
576 << int(findnext) << ' '
583 docstring const string2find(docstring const & argument,
591 // data is of the form
593 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
595 docstring howto = split(argument, search, '\n');
597 casesensitive = parse_bool(howto);
598 matchword = parse_bool(howto);
599 forward = parse_bool(howto, true);
600 wrap = parse_bool(howto);
601 instant = parse_bool(howto);
602 onlysel = parse_bool(howto);
608 bool lyxfind(BufferView * bv, FuncRequest const & ev)
610 if (!bv || ev.action() != LFUN_WORD_FIND)
613 //lyxerr << "find called, cmd: " << ev << endl;
621 docstring search = string2find(ev.argument(), casesensitive,
622 matchword, forward, wrap, instant, onlysel);
624 return findOne(bv, search, casesensitive, matchword, forward,
625 false, true, wrap, instant, onlysel);
629 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
631 if (!bv || ev.action() != LFUN_WORD_REPLACE)
634 // data is of the form
637 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
640 docstring howto = split(ev.argument(), rplc, '\n');
641 howto = split(howto, search, '\n');
643 bool casesensitive = parse_bool(howto);
644 bool matchword = parse_bool(howto);
645 bool all = parse_bool(howto);
646 bool forward = parse_bool(howto, true);
647 bool findnext = parse_bool(howto, true);
648 bool wrap = parse_bool(howto);
649 bool onlysel = parse_bool(howto);
651 if (!bv->cursor().selection())
652 // only selection only makes sense with selection
657 int replace_count = 0;
659 replace_count = replaceAll(bv, search, rplc, casesensitive,
661 update = replace_count > 0;
664 replaceOne(bv, search, rplc, casesensitive, matchword,
665 forward, findnext, wrap, onlysel);
667 replace_count = rv.second;
670 Buffer const & buf = bv->buffer();
672 // emit message signal.
674 buf.message(_("String not found in selection."));
676 buf.message(_("String not found."));
678 if (replace_count == 0) {
679 buf.message(_("String found."));
680 } else if (replace_count == 1) {
681 buf.message(_("String has been replaced."));
683 docstring const str = onlysel
684 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
685 : bformat(_("%1$d strings have been replaced."), replace_count);
693 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
695 for (; cur; cur.forwardPos())
696 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
700 DocIterator cur_orig(bv->cursor());
701 docstring q = _("End of file reached while searching forward.\n"
702 "Continue searching from the beginning?");
703 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
704 q, 0, 1, _("&Yes"), _("&No"));
705 if (wrap_answer == 0) {
706 bv->cursor().clear();
707 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
708 bv->clearSelection();
709 cur.setCursor(bv->cursor().selectionBegin());
710 if (findNextChange(bv, cur, false))
713 bv->cursor().setCursor(cur_orig);
720 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
722 for (cur.backwardPos(); cur; cur.backwardPos()) {
723 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
728 DocIterator cur_orig(bv->cursor());
729 docstring q = _("Beginning of file reached while searching backward.\n"
730 "Continue searching from the end?");
731 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
732 q, 0, 1, _("&Yes"), _("&No"));
733 if (wrap_answer == 0) {
734 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
735 bv->cursor().backwardPos();
736 bv->clearSelection();
737 cur.setCursor(bv->cursor().selectionBegin());
738 if (findPreviousChange(bv, cur, false))
741 bv->cursor().setCursor(cur_orig);
748 bool selectChange(Cursor & cur, bool forward)
750 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
752 Change ch = cur.paragraph().lookupChange(cur.pos());
754 CursorSlice tip1 = cur.top();
755 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
756 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
757 if (!ch2.isSimilarTo(ch))
760 CursorSlice tip2 = cur.top();
761 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
763 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
764 if (!ch2.isSimilarTo(ch)) {
765 // take a step forward to correctly set the selection
773 cur.bv().mouseSetCursor(cur, false);
775 cur.bv().mouseSetCursor(cur, true);
783 bool findChange(BufferView * bv, bool forward)
786 cur.setCursor(forward ? bv->cursor().selectionEnd()
787 : bv->cursor().selectionBegin());
788 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
789 return selectChange(cur, forward);
794 bool findNextChange(BufferView * bv)
796 return findChange(bv, true);
800 bool findPreviousChange(BufferView * bv)
802 return findChange(bv, false);
809 typedef vector<pair<string, string> > Escapes;
811 static string getRegexSpaceCount(int count)
815 return "\\s{" + std::to_string(count) + "}";
822 string string2regex(string in)
824 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\$\\])" };
825 string tempx = std::regex_replace(in, specialChars, R"(\$&)" );
826 // Special handling for ' '
829 for (unsigned i = 0; i < tempx.size(); i++) {
830 if (tempx[i] == ' ' || tempx[i] == '~' ) {
834 else if (tempx[i] == '\302' && tempx[i+1] == '\240') {
839 else if (tempx[i] == '\342') {
840 if (tempx[i+1] == '\200') {
841 if ((tempx[i+2] == '\257')
842 || (tempx[i+2] == '\203')
843 || (tempx[i+2] == '\202')) {
844 // Non-breaking Thin (1/6 em)
845 // Quad(1 em), (Double quad counts as 2 blanks)
850 else if (tempx[i+2] == '\213') {
851 // Ignoring parts of Medium and Thick
855 else if ((tempx[i+2] == '\204') || (tempx[i+2] == '\205')) {
862 else if (tempx[i+1] == '\201') {
863 if (tempx[i+2] == '\240') {
864 // Ignoring parts of half quad
869 else if ((tempx[i+1] == '\220') && (tempx[i+2] == '\243')) {
877 temp += getRegexSpaceCount(blanks);
884 temp += getRegexSpaceCount(blanks);
891 while (fl_pos < temp.size()) {
892 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
893 if (fl_pos == string::npos)
896 temp2 += temp.substr(lastpos, fl_pos - lastpos);
902 if (lastpos < temp.size()) {
903 temp2 += temp.substr(lastpos, temp.size() - lastpos);
908 static void buildAccentsMap();
910 string correctRegex(string t, bool withformat)
912 /* Convert \backslash => \
913 * and \{, \}, \[, \] => {, }, [, ]
916 static std::regex wordre("(\\\\)*(\\\\(( |[A-Za-z]+|[\\{\\}%])( |\\{\\})?|[\\[\\]\\{\\}]))");
917 static std::regex protectedSpace { R"(~)" };
920 bool backslashed = false;
924 //LYXERR0("correctRegex input '" << t << "'");
926 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
929 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
933 if (sub.str(4) == "backslash") {
934 replace = string("\\");
936 // transforms '\backslash \{' into '\{'
937 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
938 if ((next == "\\{") || (next == "\\}") || (next == "\\ ")) {
942 else if (withformat && next[0] == '$') {
943 replace = accents["lyxdollar"];
944 skip = 1; // Skip following '$'
948 else if (sub.str(4) == "mathcircumflex")
950 else if ((sub.str(4) == "negthinspace") || (sub.str(4) == "negmedspace") || (sub.str(4) == "negthickspace")) {
951 replace = accents[sub.str(4)+"{}"];
953 else if (backslashed) {
956 if (sub.str(3) == "{")
957 replace = accents["braceleft"];
958 else if (sub.str(3) == "}")
959 replace = accents["braceright"];
960 else if (sub.str(3) == " ")
963 // else part should not exist
968 if (sub.str(3) == "{")
970 else if (sub.str(3) == "}")
972 else if (sub.str(3) == " ")
975 // else part should not exist
980 else if (sub.str(4) == "{") // transforms '\{' into '{'
982 else if (sub.str(4) == "}")
984 else if (sub.str(4) == "%")
986 else if (sub.str(4) == " ")
989 AccentsIterator it_ac = accents.find(sub.str(4));
990 if (it_ac == accents.end()) {
991 replace = sub.str(2);
994 replace = it_ac->second;
998 if (lastpos < (size_t) sub.position(2))
999 s += std::regex_replace(t.substr(lastpos, sub.position(2) - lastpos), protectedSpace, R"( )");
1001 lastpos = sub.position(2) + sub.length(2) + skip;
1005 s = std::regex_replace(t, protectedSpace, R"( )");
1006 else if (lastpos < t.length())
1007 s += std::regex_replace(t.substr(lastpos, t.length() - lastpos), protectedSpace, R"( )");
1008 // Handle quotes in regex
1009 // substitute all '„', '“', '»', '«' with '"'
1010 // and all '‚', '‘', '›', '‹' with "\'"
1011 static std::regex plainquotes { R"(„|“|»|«)" };
1012 static std::regex innerquotes { R"(‚|‘|›|‹)" };
1013 t = std::regex_replace(s, plainquotes, R"(")");
1014 s = std::regex_replace(t, innerquotes, R"(')");
1015 //LYXERR0("correctRegex output '" << s << "'");
1019 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
1020 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
1021 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
1022 string escape_for_regex(string s, bool withformat)
1026 while (lastpos < s.size()) {
1027 size_t regex_pos = s.find("\\regexp{", lastpos);
1028 if (regex_pos == string::npos) {
1029 regex_pos = s.size();
1031 if (regex_pos > lastpos) {
1032 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
1033 lastpos = regex_pos;
1034 if (lastpos == s.size())
1037 size_t end_pos = s.find("\\endregexp", regex_pos + 8);
1038 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
1039 lastpos = end_pos + 13;
1045 /// Wrapper for lyx::regex_replace with simpler interface
1046 bool regex_replace(string const & s, string & t, string const & searchstr,
1047 string const & replacestr)
1049 regex e(searchstr, regex_constants::ECMAScript);
1051 ostream_iterator<char, char> it(oss);
1052 regex_replace(it, s.begin(), s.end(), e, replacestr);
1053 // tolerate t and s be references to the same variable
1054 bool rv = (s != oss.str());
1073 vector <string> result = vector <string>();
1074 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {}
1077 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
1079 if (newres.match2end < oldres.match2end)
1080 return MatchResult::newIsTooFar;
1081 if (newres.match_len < oldres.match_len)
1082 return MatchResult::newIsTooFar;
1084 if (newres.match_len == oldres.match_len) {
1085 if (newres.match2end == oldres.match2end)
1086 return MatchResult::newIsBetter;
1088 return MatchResult::newIsInvalid;
1091 /** The class performing a match between a position in the document and the FindAdvOptions.
1094 class MatchStringAdv {
1096 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
1098 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
1099 ** constructor as opt.search, under the opt.* options settings.
1102 ** If set to MatchStringAdv::MatchFromStart,
1103 ** then match is searched only against beginning of text starting at cur.
1104 ** Otherwise the match is searched anywhere in text starting at cur.
1107 ** The length of the matching text, or zero if no match was found.
1113 string matchTypeAsString(matchType const x) const { return (x == MatchFromStart ? "MatchFromStart" : "MatchAnyPlace"); }
1114 MatchResult operator()(DocIterator const & cur, int len, matchType at_begin) const;
1122 lyx::Buffer * p_buf;
1123 /// first buffer on which search was started
1124 lyx::Buffer * const p_first_buf;
1126 FindAndReplaceOptions const & opt;
1129 /// Auxiliary find method (does not account for opt.matchword)
1130 MatchResult findAux(DocIterator const & cur, int len, matchType at_begin) const;
1131 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
1133 /** Normalize a stringified or latexified LyX paragraph.
1137 ** <li>if search is not casesensitive, then lowercase the string;
1138 ** <li>remove any newline at begin or end of the string;
1139 ** <li>replace any newline in the middle of the string with a simple space;
1140 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
1143 ** @todo Normalization should also expand macros, if the corresponding
1144 ** search option was checked.
1146 string convertLF2Space(docstring const & s, bool ignore_fomat) const;
1147 // normalized string to search
1148 string par_as_string;
1149 // regular expression to use for searching
1150 // regexp2 is same as regexp, but prefixed with a ".*?"
1152 QRegularExpression regexp;
1153 QRegularExpression regexp2;
1158 // leading format material as string
1159 string lead_as_string;
1160 // par_as_string after removal of lead_as_string
1161 string par_as_string_nolead;
1162 // unmatched open braces in the search string/regexp
1163 int open_braces = 0;
1164 // number of (.*?) subexpressions added at end of search regexp for closing
1165 // environments, math mode, styles, etc...
1166 int close_wildcards = 0;
1168 // Are we searching with regular expressions ?
1169 bool use_regexp = false;
1170 static int valid_matches;
1171 static vector <string> matches;
1172 void FillResults(MatchResult &found_mr);
1175 int MatchStringAdv::valid_matches = 0;
1176 vector <string> MatchStringAdv::matches = vector <string>(10);
1178 void MatchStringAdv::FillResults(MatchResult &found_mr)
1180 if (found_mr.match_len > 0) {
1181 valid_matches = found_mr.result.size();
1182 for (size_t i = 0; i < found_mr.result.size(); i++)
1183 matches[i] = found_mr.result[i];
1188 static void setFindParams(OutputParams &runparams)
1190 runparams.flavor = Flavor::XeTeX;
1191 //runparams.use_polyglossia = true;
1192 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1193 // No side effect of file copying and image conversion
1194 runparams.dryrun = true;
1197 static docstring buffer_to_latex(Buffer & buffer)
1199 //OutputParams runparams(&buffer.params().encoding());
1200 OutputParams runparams(encodings.fromLyXName("utf8"));
1201 odocstringstream ods;
1203 runparams.nice = true;
1204 setFindParams(runparams);
1205 if (ignoreFormats.getDeleted())
1206 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1208 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1209 if (ignoreFormats.getNonContent()) {
1210 runparams.find_add_feature(OutputParams::SearchNonOutput);
1212 pit_type const endpit = buffer.paragraphs().size();
1213 for (pit_type pit = 0; pit != endpit; ++pit) {
1214 TeXOnePar(buffer, buffer.text(), pit, os, runparams, string(), -1, -1, true);
1215 LYXERR(Debug::FINDVERBOSE, "searchString up to here: " << ods.str());
1220 static string latexNamesToUtf8(docstring strIn, bool withformat)
1222 string addtmp = to_utf8(strIn);
1223 static regex const rmAcc("(\\\\)*("
1224 "\\\\([A-Za-z]+\\{.\\})" // e.g. "ddot{A}" == sub.str(3)
1225 "|\\\\([A-Za-z]+)( |\\{\\})?" // e.g. "LyX", "LyX{}", "LyX " == sub.str(4)
1232 if (accents.empty())
1234 for (sregex_iterator it_add(addtmp.begin(), addtmp.end(), rmAcc), end; it_add != end; ++it_add) {
1236 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
1241 if (sub.length(3) > 0)
1245 AccentsIterator it_ac = accents.find(key);
1246 if (it_ac == accents.end()) {
1247 replace = sub.str(2);
1250 replace = it_ac->second;
1253 if (lastpos < (size_t) sub.position(2))
1254 add += addtmp.substr(lastpos, sub.position(2) - lastpos);
1256 lastpos = sub.position(2) + sub.length(2);
1260 else if (addtmp.length() > lastpos)
1261 add += addtmp.substr(lastpos, addtmp.length() - lastpos);
1263 static std::regex repltilde { R"(~)" };
1264 add = std::regex_replace(add, repltilde, accents["lyxtilde"]);
1266 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1271 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1274 if (!opt.ignoreformat) {
1275 str = buffer_to_latex(buffer);
1277 // OutputParams runparams(&buffer.params().encoding());
1278 OutputParams runparams(encodings.fromLyXName("utf8"));
1279 runparams.nice = true;
1280 setFindParams(runparams);
1281 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1282 if (ignoreFormats.getDeleted()) {
1283 option |= AS_STR_SKIPDELETE;
1284 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1287 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1289 if (ignoreFormats.getNonContent()) {
1290 runparams.find_add_feature(OutputParams::SearchNonOutput);
1293 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1294 Paragraph const & par = buffer.paragraphs().at(pit);
1295 string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1297 &runparams), !opt.ignoreformat);
1298 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1302 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1303 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1310 /// Return separation pos between the leading material and the rest
1311 static size_t identifyLeading(string const & s)
1314 // @TODO Support \item[text]
1315 // Kornel: Added textsl, textsf, textit, texttt and noun
1316 // + allow to search for colored text too
1317 while (regex_replace(t, t, "^\\\\(("
1318 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1319 "lyxaddress|lyxrightaddress|"
1320 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1321 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1322 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1323 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1324 || regex_replace(t, t, "^\\$", "")
1325 || regex_replace(t, t, "^\\\\\\[", "")
1326 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1327 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1329 LYXERR(Debug::FINDVERBOSE, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1330 return s.size() - t.size();
1334 * Given a latexified string, retrieve some handled features
1335 * The features of the regex will later be compared with the features
1336 * of the searched text. If the regex features are not a
1337 * subset of the analized, then, in not format ignoring search
1338 * we can early stop the search in the relevant inset.
1340 typedef map<string, bool> Features;
1342 static Features identifyFeatures(string const & s)
1344 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1345 static regex const valid("^("
1347 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1348 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1349 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1350 "(u|uu)line|(s|x)out|uwave|"
1351 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1352 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1357 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1360 if (sub.str(1).compare("regexp") == 0) {
1364 string token = sub.str(1);
1366 if (regex_match(token, sub2, valid)) {
1374 if (sub.str(1).compare("endregexp") == 0) {
1384 * defines values features of a key "\\[a-z]+{"
1389 /* Char type with content discarded
1390 * like \hspace{1cm} */
1392 /* Char, like \backslash */
1394 /* replace starting backslash with '#' */
1396 /* \part, \section*, ... */
1398 /* title, author etc */
1400 /* \foreignlanguage{ngerman}, ... */
1403 * to discard language in content */
1406 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1408 /* fonts, colors, markups, ... */
1410 /* footnotesize, ... large, ...
1411 * Ignore all of them */
1414 /* inputencoding, ...
1415 * Discard also content, because they do not help in search */
1418 * like remove, but also all arguments */
1420 /* item, listitem */
1422 /* tex, latex, ... like isChar */
1424 /* like \lettrine[lines=5]{}{} */
1426 // like isStandard, but always remove head
1428 /* End of arguments marker for lettrine,
1429 * so that they can be ignored */
1432 KeyInfo() = default;
1433 KeyInfo(KeyType type, int parcount, bool disable)
1435 parenthesiscount(parcount),
1436 disabled(disable) {}
1437 KeyType keytype = invalid;
1439 int _tokensize = -1;
1440 int _tokenstart = -1;
1441 int _dataStart = -1;
1443 int parenthesiscount = 1;
1444 bool disabled = false;
1445 bool used = false; /* by pattern */
1450 Border(int l=0, int u=0) : low(l), upper(u) {}
1455 #define MAXOPENED 30
1457 bool isPatternString_;
1459 explicit Intervall(bool isPattern, string const & p)
1460 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1461 actualdeptindex(0), hasTitle(false), langcount(0)
1469 static vector<Border> borders;
1470 static vector<int> depts;
1471 static vector<int> closes;
1472 int actualdeptindex;
1473 int previousNotIgnored(int) const;
1474 int nextNotIgnored(int) const;
1475 void handleOpenP(int i);
1476 void handleCloseP(int i, bool closingAllowed);
1477 void resetOpenedP(int openPos);
1478 void addIntervall(int upper);
1479 void addIntervall(int low, int upper); /* if explicit */
1480 void removeAccents();
1481 void setForDefaultLang(KeyInfo const & defLang) const;
1482 int findclosing(int start, int end, char up, char down, int repeat);
1483 void removeInvalidClosings(void);
1484 void handleParentheses(int lastpos, bool closingAllowed);
1486 // Number of disabled language specs up
1487 // to current position in actual interval
1489 int isOpeningPar(int pos) const;
1491 void output(ostringstream &os, int lastpos);
1492 // string show(int lastpos);
1495 vector<Border> Intervall::borders = vector<Border>(30);
1496 vector<int> Intervall::depts = vector<int>(30);
1497 vector<int> Intervall::closes = vector<int>(30);
1499 int Intervall::isOpeningPar(int pos) const
1501 if ((pos < 0) || (size_t(pos) >= par.size()))
1503 if (par[pos] != '{')
1505 if (size_t(pos) + 2 >= par.size())
1507 if (par[pos+2] != '}')
1509 if (par[pos+1] == '[' || par[pos+1] == ']')
1514 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1516 // Enable the use of first token again
1517 if (ignoreidx >= 0) {
1518 int value = defLang._tokenstart + defLang._tokensize;
1523 if (borders[borderidx].low < value)
1524 borders[borderidx].low = value;
1525 if (borders[borderidx].upper < value)
1526 borders[borderidx].upper = value;
1532 // Not needed, because dpts and closes are now dynamically expanded
1533 static void checkDepthIndex(int val)
1535 static int maxdepthidx = MAXOPENED-2;
1536 static int lastmaxdepth = 0;
1537 if (val > lastmaxdepth) {
1538 LYXERR(Debug::INFO, "Depth reached " << val);
1541 if (val > maxdepthidx) {
1543 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1549 // Not needed, because borders are now dynamically expanded
1550 static void checkIgnoreIdx(int val)
1552 static int lastmaxignore = -1;
1553 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1554 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1555 lastmaxignore = val;
1561 * Expand the region of ignored parts of the input latex string
1562 * The region is only relevant in output()
1564 void Intervall::addIntervall(int low, int upper)
1567 if (low == upper) return;
1568 for (idx = ignoreidx+1; idx > 0; --idx) {
1569 if (low > borders[idx-1].upper) {
1573 Border br(low, upper);
1574 if (idx > ignoreidx) {
1575 if (borders.size() <= size_t(idx)) {
1576 borders.push_back(br);
1582 // checkIgnoreIdx(ignoreidx);
1586 // Expand only if one of the new bound is inside the interwall
1587 // We know here that br.low > borders[idx-1].upper
1588 if (br.upper < borders[idx].low) {
1589 // We have to insert at this pos
1590 if (size_t(ignoreidx+1) >= borders.size()) {
1591 borders.push_back(borders[ignoreidx]);
1594 borders[ignoreidx+1] = borders[ignoreidx];
1596 for (int i = ignoreidx; i > idx; --i) {
1597 borders[i] = borders[i-1];
1601 // checkIgnoreIdx(ignoreidx);
1604 // Here we know, that we are overlapping
1605 if (br.low > borders[idx].low)
1606 br.low = borders[idx].low;
1607 // check what has to be concatenated
1609 for (int i = idx; i <= ignoreidx; i++) {
1610 if (br.upper >= borders[i].low) {
1612 if (br.upper < borders[i].upper)
1613 br.upper = borders[i].upper;
1619 // count should be >= 1 here
1622 for (int i = idx + count; i <= ignoreidx; i++) {
1623 borders[i-count+1] = borders[i];
1625 ignoreidx -= count - 1;
1631 static void buildaccent(string n, string param, string values)
1635 const char delim = '|';
1636 while (getline(s, name, delim)) {
1638 for (char c : param) {
1639 string key = name + "{" + c + "}";
1640 // get the corresponding utf8-value
1641 if ((values[start] & 0xc0) != 0xc0) {
1642 // should not happen, utf8 encoding starts at least with 11xxxxxx
1643 // but value for '\dot{i}' is 'i', which is ascii
1644 if ((values[start] & 0x80) == 0) {
1646 accents[key] = values.substr(start, 1);
1647 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1652 for (int j = 1; ;j++) {
1653 if (start + j >= values.size()) {
1654 accents[key] = values.substr(start, j);
1655 start = values.size() - 1;
1658 else if ((values[start+j] & 0xc0) != 0x80) {
1659 // This is the first byte of following utf8 char
1660 accents[key] = values.substr(start, j);
1662 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1671 static string getutf8(unsigned uchar)
1674 string ret = string();
1676 if (uchar <= 0x7f) {
1677 c[maxc-1] = uchar & 0x7f;
1680 unsigned char rest = 0x40;
1681 unsigned char first = 0x80;
1683 for (int i = start; i >=0; --i) {
1685 c[i] = first + uchar;
1688 c[i] = 0x80 | (uchar & 0x3f);
1695 for (int i = 0; i < maxc; i++) {
1696 if (c[i] == 0) continue;
1702 static void addAccents(string latex_in, string unicode_out)
1704 latex_in = latex_in.substr(1);
1705 AccentsIterator it_ac = accents.find(latex_in);
1706 if (it_ac == accents.end()) {
1707 accents[latex_in] = unicode_out;
1710 LYXERR0("Key " << latex_in << " already set");
1714 void static fillMissingUnicodesymbols()
1716 addAccents("\\pounds", getutf8(0x00a3));
1717 addAccents("\\textsterling", getutf8(0x00a3));
1718 addAccents("\\textyen", getutf8(0x00a5));
1719 addAccents("\\yen", getutf8(0x00a5));
1720 addAccents("\\textsection", getutf8(0x00a7));
1721 addAccents("\\mathsection", getutf8(0x00a7));
1722 addAccents("\\textcopyright", getutf8(0x00a9));
1723 addAccents("\\copyright", getutf8(0x00a9));
1724 addAccents("\\textlnot", getutf8(0x00ac));
1725 addAccents("\\neg", getutf8(0x00ac));
1726 addAccents("\\textregistered", getutf8(0x00ae));
1727 addAccents("\\circledR", getutf8(0x00ae));
1728 addAccents("\\textpm", getutf8(0x00b1));
1729 addAccents("\\pm", getutf8(0x00b1));
1730 addAccents("\\textparagraph", getutf8(0x00b6));
1731 addAccents("\\mathparagraph", getutf8(0x00b6));
1732 addAccents("\\textperiodcentered", getutf8(0x00b7));
1733 addAccents("\\texttimes", getutf8(0x00d7));
1734 addAccents("\\times", getutf8(0x00d7));
1735 addAccents("\\O", getutf8(0x00d8));
1736 addAccents("\\dh", getutf8(0x00f0));
1737 addAccents("\\eth", getutf8(0x00f0));
1738 addAccents("\\textdiv", getutf8(0x00f7));
1739 addAccents("\\div", getutf8(0x00f7));
1740 addAccents("\\o", getutf8(0x00f8));
1741 addAccents("\\textcrlambda", getutf8(0x019b));
1742 addAccents("\\j", getutf8(0x0237));
1743 addAccents("\\textrevepsilon", getutf8(0x025c));
1744 addAccents("\\textbaru", getutf8(0x0289));
1745 addAccents("\\textquoteleft", getutf8(0x02bb));
1746 addAccents("\\textGamma", getutf8(0x0393));
1747 addAccents("\\Gamma", getutf8(0x0393));
1748 addAccents("\\textDelta", getutf8(0x0394));
1749 addAccents("\\Delta", getutf8(0x0394));
1750 addAccents("\\textTheta", getutf8(0x0398));
1751 addAccents("\\Theta", getutf8(0x0398));
1752 addAccents("\\textLambda", getutf8(0x039b));
1753 addAccents("\\Lambda", getutf8(0x039b));
1754 addAccents("\\textXi", getutf8(0x039e));
1755 addAccents("\\Xi", getutf8(0x039e));
1756 addAccents("\\textPi", getutf8(0x03a0));
1757 addAccents("\\Pi", getutf8(0x03a0));
1758 addAccents("\\textSigma", getutf8(0x03a3));
1759 addAccents("\\Sigma", getutf8(0x03a3));
1760 addAccents("\\textUpsilon", getutf8(0x03a5));
1761 addAccents("\\Upsilon", getutf8(0x03a5));
1762 addAccents("\\textPhi", getutf8(0x03a6));
1763 addAccents("\\Phi", getutf8(0x03a6));
1764 addAccents("\\textPsi", getutf8(0x03a8));
1765 addAccents("\\Psi", getutf8(0x03a8));
1766 addAccents("\\textOmega", getutf8(0x03a9));
1767 addAccents("\\Omega", getutf8(0x03a9));
1768 addAccents("\\textalpha", getutf8(0x03b1));
1769 addAccents("\\alpha", getutf8(0x03b1));
1770 addAccents("\\textbeta", getutf8(0x03b2));
1771 addAccents("\\beta", getutf8(0x03b2));
1772 addAccents("\\textgamma", getutf8(0x03b3));
1773 addAccents("\\gamma", getutf8(0x03b3));
1774 addAccents("\\textdelta", getutf8(0x03b4));
1775 addAccents("\\delta", getutf8(0x03b4));
1776 addAccents("\\textepsilon", getutf8(0x03b5));
1777 addAccents("\\varepsilon", getutf8(0x03b5));
1778 addAccents("\\textzeta", getutf8(0x03b6));
1779 addAccents("\\zeta", getutf8(0x03b6));
1780 addAccents("\\texteta", getutf8(0x03b7));
1781 addAccents("\\eta", getutf8(0x03b7));
1782 addAccents("\\texttheta", getutf8(0x03b8));
1783 addAccents("\\theta", getutf8(0x03b8));
1784 addAccents("\\textiota", getutf8(0x03b9));
1785 addAccents("\\iota", getutf8(0x03b9));
1786 addAccents("\\textkappa", getutf8(0x03ba));
1787 addAccents("\\kappa", getutf8(0x03ba));
1788 addAccents("\\textlambda", getutf8(0x03bb));
1789 addAccents("\\lambda", getutf8(0x03bb));
1790 addAccents("\\textmu", getutf8(0x03bc));
1791 addAccents("\\mu", getutf8(0x03bc));
1792 addAccents("\\textnu", getutf8(0x03bd));
1793 addAccents("\\nu", getutf8(0x03bd));
1794 addAccents("\\textxi", getutf8(0x03be));
1795 addAccents("\\xi", getutf8(0x03be));
1796 addAccents("\\textpi", getutf8(0x03c0));
1797 addAccents("\\pi", getutf8(0x03c0));
1798 addAccents("\\textrho", getutf8(0x03c1));
1799 addAccents("\\rho", getutf8(0x03c1));
1800 addAccents("\\textfinalsigma", getutf8(0x03c2));
1801 addAccents("\\varsigma", getutf8(0x03c2));
1802 addAccents("\\textsigma", getutf8(0x03c3));
1803 addAccents("\\sigma", getutf8(0x03c3));
1804 addAccents("\\texttau", getutf8(0x03c4));
1805 addAccents("\\tau", getutf8(0x03c4));
1806 addAccents("\\textupsilon", getutf8(0x03c5));
1807 addAccents("\\upsilon", getutf8(0x03c5));
1808 addAccents("\\textphi", getutf8(0x03c6));
1809 addAccents("\\varphi", getutf8(0x03c6));
1810 addAccents("\\textchi", getutf8(0x03c7));
1811 addAccents("\\chi", getutf8(0x03c7));
1812 addAccents("\\textpsi", getutf8(0x03c8));
1813 addAccents("\\psi", getutf8(0x03c8));
1814 addAccents("\\textomega", getutf8(0x03c9));
1815 addAccents("\\omega", getutf8(0x03c9));
1816 addAccents("\\textdigamma", getutf8(0x03dd));
1817 addAccents("\\digamma", getutf8(0x03dd));
1818 addAccents("\\hebalef", getutf8(0x05d0));
1819 addAccents("\\aleph", getutf8(0x05d0));
1820 addAccents("\\hebbet", getutf8(0x05d1));
1821 addAccents("\\beth", getutf8(0x05d1));
1822 addAccents("\\hebgimel", getutf8(0x05d2));
1823 addAccents("\\gimel", getutf8(0x05d2));
1824 addAccents("\\hebdalet", getutf8(0x05d3));
1825 addAccents("\\daleth", getutf8(0x05d3));
1826 addAccents("\\hebhe", getutf8(0x05d4));
1827 addAccents("\\hebvav", getutf8(0x05d5));
1828 addAccents("\\hebzayin", getutf8(0x05d6));
1829 addAccents("\\hebhet", getutf8(0x05d7));
1830 addAccents("\\hebtet", getutf8(0x05d8));
1831 addAccents("\\hebyod", getutf8(0x05d9));
1832 addAccents("\\hebfinalkaf", getutf8(0x05da));
1833 addAccents("\\hebkaf", getutf8(0x05db));
1834 addAccents("\\heblamed", getutf8(0x05dc));
1835 addAccents("\\hebfinalmem", getutf8(0x05dd));
1836 addAccents("\\hebmem", getutf8(0x05de));
1837 addAccents("\\hebfinalnun", getutf8(0x05df));
1838 addAccents("\\hebnun", getutf8(0x05e0));
1839 addAccents("\\hebsamekh", getutf8(0x05e1));
1840 addAccents("\\hebayin", getutf8(0x05e2));
1841 addAccents("\\hebfinalpe", getutf8(0x05e3));
1842 addAccents("\\hebpe", getutf8(0x05e4));
1843 addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1844 addAccents("\\hebtsadi", getutf8(0x05e6));
1845 addAccents("\\hebqof", getutf8(0x05e7));
1846 addAccents("\\hebresh", getutf8(0x05e8));
1847 addAccents("\\hebshin", getutf8(0x05e9));
1848 addAccents("\\hebtav", getutf8(0x05ea));
1851 addAccents("\\thaiKoKai", getutf8(0x0e01));
1852 addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1853 addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1854 addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1855 addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1856 addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1857 addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1858 addAccents("\\thaiChoChan", getutf8(0x0e08));
1859 addAccents("\\thaiChoChing", getutf8(0x0e09));
1860 addAccents("\\thaiChoChang", getutf8(0x0e0a));
1861 addAccents("\\thaiSoSo", getutf8(0x0e0b));
1862 addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1863 addAccents("\\thaiYoYing", getutf8(0x0e0d));
1864 addAccents("\\thaiDoChada", getutf8(0x0e0e));
1865 addAccents("\\thaiToPatak", getutf8(0x0e0f));
1866 addAccents("\\thaiThoThan", getutf8(0x0e10));
1867 addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1868 addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1869 addAccents("\\thaiNoNen", getutf8(0x0e13));
1870 addAccents("\\thaiDoDek", getutf8(0x0e14));
1871 addAccents("\\thaiToTao", getutf8(0x0e15));
1872 addAccents("\\thaiThoThung", getutf8(0x0e16));
1873 addAccents("\\thaiThoThahan", getutf8(0x0e17));
1874 addAccents("\\thaiThoThong", getutf8(0x0e18));
1875 addAccents("\\thaiNoNu", getutf8(0x0e19));
1876 addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1877 addAccents("\\thaiPoPla", getutf8(0x0e1b));
1878 addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1879 addAccents("\\thaiFoFa", getutf8(0x0e1d));
1880 addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1881 addAccents("\\thaiFoFan", getutf8(0x0e1f));
1882 addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1883 addAccents("\\thaiMoMa", getutf8(0x0e21));
1884 addAccents("\\thaiYoYak", getutf8(0x0e22));
1885 addAccents("\\thaiRoRua", getutf8(0x0e23));
1886 addAccents("\\thaiRu", getutf8(0x0e24));
1887 addAccents("\\thaiLoLing", getutf8(0x0e25));
1888 addAccents("\\thaiLu", getutf8(0x0e26));
1889 addAccents("\\thaiWoWaen", getutf8(0x0e27));
1890 addAccents("\\thaiSoSala", getutf8(0x0e28));
1891 addAccents("\\thaiSoRusi", getutf8(0x0e29));
1892 addAccents("\\thaiSoSua", getutf8(0x0e2a));
1893 addAccents("\\thaiHoHip", getutf8(0x0e2b));
1894 addAccents("\\thaiLoChula", getutf8(0x0e2c));
1895 addAccents("\\thaiOAng", getutf8(0x0e2d));
1896 addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1897 addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1898 addAccents("\\thaiSaraA", getutf8(0x0e30));
1899 addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1900 addAccents("\\thaiSaraAa", getutf8(0x0e32));
1901 addAccents("\\thaiSaraAm", getutf8(0x0e33));
1902 addAccents("\\thaiSaraI", getutf8(0x0e34));
1903 addAccents("\\thaiSaraIi", getutf8(0x0e35));
1904 addAccents("\\thaiSaraUe", getutf8(0x0e36));
1905 addAccents("\\thaiSaraUee", getutf8(0x0e37));
1906 addAccents("\\thaiSaraU", getutf8(0x0e38));
1907 addAccents("\\thaiSaraUu", getutf8(0x0e39));
1908 addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1909 addAccents("\\thaiSaraE", getutf8(0x0e40));
1910 addAccents("\\thaiSaraAe", getutf8(0x0e41));
1911 addAccents("\\thaiSaraO", getutf8(0x0e42));
1912 addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1913 addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1914 addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1915 addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1916 addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1917 addAccents("\\thaiMaiEk", getutf8(0x0e48));
1918 addAccents("\\thaiMaiTho", getutf8(0x0e49));
1919 addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1920 addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1921 addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1922 addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1923 addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1924 addAccents("\\thaiFongman", getutf8(0x0e4f));
1925 addAccents("\\thaizero", getutf8(0x0e50));
1926 addAccents("\\thaione", getutf8(0x0e51));
1927 addAccents("\\thaitwo", getutf8(0x0e52));
1928 addAccents("\\thaithree", getutf8(0x0e53));
1929 addAccents("\\thaifour", getutf8(0x0e54));
1930 addAccents("\\thaifive", getutf8(0x0e55));
1931 addAccents("\\thaisix", getutf8(0x0e56));
1932 addAccents("\\thaiseven", getutf8(0x0e57));
1933 addAccents("\\thaieight", getutf8(0x0e58));
1934 addAccents("\\thainine", getutf8(0x0e59));
1935 addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1936 addAccents("\\thaiKhomut", getutf8(0x0e5b));
1937 addAccents("\\dag", getutf8(0x2020));
1938 addAccents("\\dagger", getutf8(0x2020));
1939 addAccents("\\textdagger", getutf8(0x2020));
1940 addAccents("\\ddag", getutf8(0x2021));
1941 addAccents("\\ddagger", getutf8(0x2021));
1942 addAccents("\\textdaggerdbl", getutf8(0x2021));
1943 addAccents("\\textbullet", getutf8(0x2022));
1944 addAccents("\\bullet", getutf8(0x2022));
1945 addAccents("\\dots", getutf8(0x2026));
1946 addAccents("\\ldots", getutf8(0x2026));
1947 addAccents("\\textellipsis", getutf8(0x2026));
1948 addAccents("\\textasciiacute", getutf8(0x2032));
1949 addAccents("\\prime", getutf8(0x2032));
1950 addAccents("\\textacutedbl", getutf8(0x2033));
1951 addAccents("\\dprime", getutf8(0x2033));
1952 addAccents("\\textasciigrave", getutf8(0x2035));
1953 addAccents("\\backprime", getutf8(0x2035));
1954 addAccents("\\textsubcircum{ }", getutf8(0x2038));
1955 addAccents("\\caretinsert", getutf8(0x2038));
1956 addAccents("\\textasteriskcentered", getutf8(0x204e));
1957 addAccents("\\ast", getutf8(0x204e));
1958 addAccents("\\textmho", getutf8(0x2127));
1959 addAccents("\\mho", getutf8(0x2127));
1960 addAccents("\\textleftarrow", getutf8(0x2190));
1961 addAccents("\\leftarrow", getutf8(0x2190));
1962 addAccents("\\textuparrow", getutf8(0x2191));
1963 addAccents("\\uparrow", getutf8(0x2191));
1964 addAccents("\\textrightarrow", getutf8(0x2192));
1965 addAccents("\\rightarrow", getutf8(0x2192));
1966 addAccents("\\textdownarrow", getutf8(0x2193));
1967 addAccents("\\downarrow", getutf8(0x2193));
1968 addAccents("\\textglobrise", getutf8(0x2197));
1969 addAccents("\\nearrow", getutf8(0x2197));
1970 addAccents("\\textglobfall", getutf8(0x2198));
1971 addAccents("\\searrow", getutf8(0x2198));
1972 addAccents("\\textsurd", getutf8(0x221a));
1973 addAccents("\\surd", getutf8(0x221a));
1974 addAccents("\\textbigcircle", getutf8(0x25ef));
1975 addAccents("\\bigcirc", getutf8(0x25ef));
1976 addAccents("\\FiveStar", getutf8(0x2605));
1977 addAccents("\\bigstar", getutf8(0x2605));
1978 addAccents("\\FiveStarOpen", getutf8(0x2606));
1979 addAccents("\\bigwhitestar", getutf8(0x2606));
1980 addAccents("\\Checkmark", getutf8(0x2713));
1981 addAccents("\\checkmark", getutf8(0x2713));
1982 addAccents("\\CrossMaltese", getutf8(0x2720));
1983 addAccents("\\maltese", getutf8(0x2720));
1984 addAccents("\\textlangle", getutf8(0x27e8));
1985 addAccents("\\langle", getutf8(0x27e8));
1986 addAccents("\\textrangle", getutf8(0x27e9));
1987 addAccents("\\rangle", getutf8(0x27e9));
1990 static void buildAccentsMap()
1992 accents["imath"] = "ı";
1994 accents["jmath"] = "ȷ";
1995 accents["cdot"] = "·";
1996 accents["textasciicircum"] = "^";
1997 accents["mathcircumflex"] = "^";
1998 accents["guillemotright"] = "»";
1999 accents["guillemotleft"] = "«";
2000 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
2001 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
2002 accents["negthinspace{}"]= getutf8(0xf0003); // to omit backslashed latex macros
2003 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
2004 accents["negmedspace{}"] = getutf8(0xf0005);
2005 accents["thickspace"] = getutf8(0xf0006);
2006 accents["negthickspace{}"]= getutf8(0xf0007);
2007 accents["lyx"] = getutf8(0xf0010); // Used logos
2008 accents["LyX"] = getutf8(0xf0010);
2009 accents["tex"] = getutf8(0xf0011);
2010 accents["TeX"] = getutf8(0xf0011);
2011 accents["latex"] = getutf8(0xf0012);
2012 accents["LaTeX"] = getutf8(0xf0012);
2013 accents["latexe"] = getutf8(0xf0013);
2014 accents["LaTeXe"] = getutf8(0xf0013);
2015 accents["lyxarrow"] = getutf8(0xf0020);
2016 accents["braceleft"] = getutf8(0xf0030);
2017 accents["braceright"] = getutf8(0xf0031);
2018 accents["lyxtilde"] = getutf8(0xf0032);
2019 accents["sim"] = getutf8(0xf0032);
2020 accents["lyxdollar"] = getutf8(0xf0033);
2021 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
2022 accents["backslash LyX"] = getutf8(0xf0010);
2023 accents["backslash tex"] = getutf8(0xf0011);
2024 accents["backslash TeX"] = getutf8(0xf0011);
2025 accents["backslash latex"] = getutf8(0xf0012);
2026 accents["backslash LaTeX"] = getutf8(0xf0012);
2027 accents["backslash latexe"] = getutf8(0xf0013);
2028 accents["backslash LaTeXe"] = getutf8(0xf0013);
2029 accents["backslash lyxarrow"] = getutf8(0xf0020);
2030 accents["ddot{\\imath}"] = "ï";
2031 buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
2032 "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ"); // umlaut
2033 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
2034 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
2035 accents["acute{\\imath}"] = "í";
2036 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2037 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2038 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
2039 buildaccent("mathring|r", "aAuUwy",
2041 accents["check{\\imath}"] = "ǐ";
2042 accents["check{\\jmath}"] = "ǰ";
2043 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2044 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
2045 accents["hat{\\imath}"] = "î";
2046 accents["hat{\\jmath}"] = "ĵ";
2047 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2048 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
2049 accents["bar{\\imath}"] = "ī";
2050 buildaccent("bar|=", "aAeEiIoOuUyY",
2051 "āĀēĒīĪōŌūŪȳȲ"); // macron
2052 accents["tilde{\\imath}"] = "ĩ";
2053 buildaccent("tilde", "aAeEiInNoOuUvVyY",
2054 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
2055 accents["breve{\\imath}"] = "ĭ";
2056 buildaccent("breve|u", "aAeEgGiIoOuU",
2057 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
2058 accents["grave{\\imath}"] = "ì";
2059 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2060 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
2061 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2062 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
2063 buildaccent("ogonek|k", "AaEeIiUuOo",
2064 "ĄąĘęĮįŲųǪǫ"); // ogonek
2065 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2066 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
2067 buildaccent("subring|textsubring", "Aa",
2069 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2070 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
2071 buildaccent("subtilde|textsubtilde", "EeIiUu",
2072 "ḚḛḬḭṴṵ"); // subtilde
2073 accents["dgrave{\\imath}"] = "ȉ";
2074 accents["textdoublegrave{\\i}"] = "ȉ";
2075 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2076 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2077 accents["rcap{\\imath}"] = "ȋ";
2078 accents["textroundcap{\\i}"] = "ȋ";
2079 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2080 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2081 buildaccent("slashed", "oO",
2083 fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2084 // LYXERR0("Number of accents " << accents.size());
2088 * Created accents in math or regexp environment
2089 * are macros, but we need the utf8 equivalent
2091 void Intervall::removeAccents()
2093 if (accents.empty())
2095 static regex const accre("\\\\("
2096 "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]*\\}"
2097 "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2099 "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2104 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2106 string key = sub.str(1);
2107 AccentsIterator it_ac = accents.find(key);
2108 if (it_ac != accents.end()) {
2109 string val = it_ac->second;
2110 size_t pos = sub.position(size_t(0));
2111 for (size_t i = 0; i < val.size(); i++) {
2112 par[pos+i] = val[i];
2114 // Remove possibly following space too
2115 if (par[pos+sub.str(0).size()] == ' ')
2116 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2118 addIntervall(pos+val.size(), pos + sub.str(0).size());
2119 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2120 // remove traces of any remaining chars
2125 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2130 void Intervall::handleOpenP(int i)
2133 if ((size_t) actualdeptindex >= depts.size()) {
2134 depts.resize(actualdeptindex + 30);
2135 closes.resize(actualdeptindex + 30);
2137 depts[actualdeptindex] = i+1;
2138 closes[actualdeptindex] = -1;
2139 // checkDepthIndex(actualdeptindex);
2142 void Intervall::handleCloseP(int i, bool closingAllowed)
2144 if (actualdeptindex <= 0) {
2145 if (! closingAllowed)
2146 LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
2147 // if we are at the very end
2148 addIntervall(i, i+1);
2151 closes[actualdeptindex] = i+1;
2156 void Intervall::resetOpenedP(int openPos)
2158 // Used as initializer for foreignlanguage entry
2159 actualdeptindex = 1;
2160 depts[1] = openPos+1;
2164 int Intervall::previousNotIgnored(int start) const
2166 int idx = 0; /* int intervalls */
2167 for (idx = ignoreidx; idx >= 0; --idx) {
2168 if (start > borders[idx].upper)
2170 if (start >= borders[idx].low)
2171 start = borders[idx].low-1;
2176 int Intervall::nextNotIgnored(int start) const
2178 int idx = 0; /* int intervalls */
2179 for (idx = 0; idx <= ignoreidx; idx++) {
2180 if (start < borders[idx].low)
2182 if (start < borders[idx].upper)
2183 start = borders[idx].upper;
2188 typedef unordered_map<string, KeyInfo> KeysMap;
2189 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2190 typedef vector< KeyInfo> Entries;
2191 static KeysMap keys = unordered_map<string, KeyInfo>();
2197 Intervall interval_;
2198 void buildKeys(bool);
2199 void buildEntries(bool);
2200 void makeKey(const string &, KeyInfo, bool isPatternString);
2201 void processRegion(int start, int region_end); /* remove {} parts */
2202 void removeHead(KeyInfo const &, int count=0);
2205 LatexInfo(string const & par, bool isPatternString)
2206 : entidx_(-1), interval_(isPatternString, par)
2208 buildKeys(isPatternString);
2209 entries_ = vector<KeyInfo>();
2210 buildEntries(isPatternString);
2214 if (entries_.empty()) {
2217 if (entries_[0].keytype == KeyInfo::isTitle) {
2218 interval_.hasTitle = true;
2219 if (! entries_[0].disabled) {
2220 interval_.titleValue = entries_[0].head;
2223 interval_.titleValue = "";
2225 removeHead(entries_[0]);
2226 if (entries_.size() > 1)
2235 if (int(entries_.size()) > entidx_) {
2242 bool setNextKey(int idx) {
2243 if ((idx == entidx_) && (entidx_ >= 0)) {
2250 int find(int start, KeyInfo::KeyType keytype) const {
2254 while (tmpIdx < int(entries_.size())) {
2255 if (entries_[tmpIdx].keytype == keytype)
2261 int process(ostringstream & os, KeyInfo const & actual);
2262 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2263 // string show(int lastpos) { return interval.show(lastpos);}
2264 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2265 KeyInfo &getKeyInfo(int keyinfo) {
2266 static KeyInfo invalidInfo = KeyInfo();
2267 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2270 return entries_[keyinfo];
2272 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2273 void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2277 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2281 for (int i = start; i < end; i += 1 + skip) {
2285 if (c == '\\') skip = 1;
2289 else if (c == down) {
2292 if ((repeat <= 0) || (par[i+1] != up))
2301 void Intervall::removeInvalidClosings(void)
2303 // this can happen, if there are deleted parts
2306 for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2309 if (c == '\\') skip = 1;
2312 else if (c == '}') {
2314 addIntervall(i, i+1);
2315 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2327 size_t mathpostfixsize;
2329 size_t mathprefixsize;
2333 vector<MathEntry> entries_;
2338 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2339 MathEntry m = MathEntry();
2341 m.mathStart = start;
2342 m.mathprefixsize = prefixsize;
2343 m.mathEnd = end + postfixsize;
2344 m.mathpostfixsize = postfixsize;
2345 m.mathSize = m.mathEnd - m.mathStart;
2346 entries_.push_back(m);
2348 bool empty() const { return entries_.empty(); }
2349 size_t getEndPos() const {
2350 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2353 return entries_[actualIdx_].mathEnd;
2355 size_t getStartPos() const {
2356 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2357 return 100000; /* definitely enough? */
2359 return entries_[actualIdx_].mathStart;
2361 size_t getPrefixSize() const {
2362 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2365 return entries_[actualIdx_].mathprefixsize;
2367 size_t getPostfixSize() const {
2368 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2371 return entries_[actualIdx_].mathpostfixsize;
2373 size_t getFirstPos() {
2375 return getStartPos();
2377 size_t getSize() const {
2378 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2381 return entries_[actualIdx_].mathSize;
2383 void incrEntry() { actualIdx_++; }
2386 void LatexInfo::buildEntries(bool isPatternString)
2388 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2389 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2390 static bool disableLanguageOverride = false;
2391 smatch sub, submath;
2392 bool evaluatingRegexp = false;
2394 bool evaluatingMath = false;
2395 bool evaluatingCode = false;
2397 bool evaluatingOptional = false;
2398 size_t optionalEnd = 0;
2401 bool math_end_waiting = false;
2402 size_t math_pos = 10000;
2403 size_t math_prefix_size = 1;
2405 static vector<string> usedText = vector<string>();
2406 static bool removeMathHull = false;
2408 interval_.removeAccents();
2409 interval_.removeInvalidClosings();
2411 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2413 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2414 // prefixed by odd count of '\\'
2417 if (math_end_waiting) {
2418 size_t pos = submath.position(size_t(2));
2419 if ((math_end == "$") &&
2420 (submath.str(2) == "$")) {
2421 mi.insert("$", math_pos, 1, pos, 1);
2422 math_end_waiting = false;
2424 else if ((math_end == "\\]") &&
2425 (submath.str(2) == "\\]")) {
2426 mi.insert("\\]", math_pos, 2, pos, 2);
2427 math_end_waiting = false;
2429 else if ((submath.str(3).compare("end") == 0) &&
2430 (submath.str(5).compare(math_end) == 0)) {
2431 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2432 math_end_waiting = false;
2438 if (submath.str(3).compare("begin") == 0) {
2439 math_end_waiting = true;
2440 math_end = submath.str(5);
2441 math_pos = submath.position(size_t(2));
2442 math_prefix_size = submath.str(2).length();
2444 else if (submath.str(2).compare("\\[") == 0) {
2445 math_end_waiting = true;
2447 math_pos = submath.position(size_t(2));
2449 else if (submath.str(2) == "$") {
2450 size_t pos = submath.position(size_t(2));
2451 math_end_waiting = true;
2457 // Ignore language if there is math somewhere in pattern-string
2458 if (isPatternString) {
2459 for (auto const & s: usedText) {
2460 // Remove entries created in previous search runs
2463 usedText = vector<string>();
2466 keys["foreignlanguage"].disabled = true;
2467 disableLanguageOverride = true;
2468 removeMathHull = false;
2471 removeMathHull = true; // used later if not isPatternString
2472 disableLanguageOverride = false;
2476 if (disableLanguageOverride) {
2477 keys["foreignlanguage"].disabled = true;
2480 math_pos = mi.getFirstPos();
2481 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2483 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2484 // prefixed by odd count of '\\'
2487 string key = sub.str(5);
2489 if (sub.str(2)[0] == '\\')
2490 key = sub.str(2)[1];
2495 KeysIterator it_key = keys.find(key);
2496 if (it_key != keys.end()) {
2497 if (it_key->second.keytype == KeyInfo::headRemove) {
2498 KeyInfo found1 = it_key->second;
2499 found1.disabled = true;
2500 found1.head = "\\" + key + "{";
2501 found1._tokenstart = sub.position(size_t(2));
2502 found1._tokensize = found1.head.length();
2503 found1._dataStart = found1._tokenstart + found1.head.length();
2504 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2505 found1._dataEnd = endpos;
2510 if (evaluatingRegexp) {
2511 if (sub.str(3).compare("endregexp") == 0) {
2512 evaluatingRegexp = false;
2513 // found._tokenstart already set
2514 found._dataEnd = sub.position(size_t(2)) + 13;
2515 found._dataStart = found._dataEnd;
2516 found._tokensize = found._dataEnd - found._tokenstart;
2517 found.parenthesiscount = 0;
2518 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2525 if (evaluatingMath) {
2526 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2528 evaluatingMath = false;
2530 math_pos = mi.getStartPos();
2532 if (it_key == keys.end()) {
2533 found = KeyInfo(KeyInfo::isStandard, 0, true);
2534 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2535 found = KeyInfo(KeyInfo::isText, 0, false);
2536 if (isPatternString) {
2537 found.keytype = KeyInfo::isChar;
2538 found.disabled = false;
2542 usedText.push_back(key);
2546 if (key.compare("regexp") == 0) {
2547 evaluatingRegexp = true;
2548 found._tokenstart = sub.position(size_t(2));
2549 found._tokensize = 0;
2553 // Handle the other params of key
2554 if (found.keytype == KeyInfo::isIgnored)
2556 else if (found.keytype == KeyInfo::isMath) {
2557 if (size_t(sub.position(size_t(2))) == math_pos) {
2559 found._tokenstart = sub.position(size_t(2));
2560 found._tokensize = mi.getSize();
2561 found._dataEnd = found._tokenstart + found._tokensize;
2562 found._dataStart = found._dataEnd;
2563 found.parenthesiscount = 0;
2564 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2565 if (removeMathHull) {
2566 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2567 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2570 // Treate all math constructs as simple math
2571 interval_.par[found._tokenstart] = '$';
2572 interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2573 interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2574 interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2576 evaluatingMath = true;
2579 // begin|end of unknown env, discard
2580 // First handle tables
2581 // longtable|tabular
2582 bool discardComment;
2584 found.keytype = KeyInfo::doRemove;
2585 if ((sub.str(7).compare("longtable") == 0) ||
2586 (sub.str(7).compare("tabular") == 0)) {
2587 discardComment = true; /* '%' */
2590 discardComment = false;
2591 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2593 string token = sub.str(7);
2594 if (regex_match(token, sub2, removeArgs)) {
2595 found.keytype = KeyInfo::removeWithArg;
2598 // discard spaces before pos(2)
2599 int pos = sub.position(size_t(2));
2601 for (count = 0; pos - count > 0; count++) {
2602 char c = interval_.par[pos-count-1];
2603 if (discardComment) {
2604 if ((c != ' ') && (c != '%'))
2610 found._tokenstart = pos - count;
2611 if (sub.str(3).compare(0, 5, "begin") == 0) {
2612 size_t pos1 = pos + sub.str(2).length();
2613 if (sub.str(7).compare("cjk") == 0) {
2614 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2615 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2617 found.keytype = KeyInfo::isMain;
2618 found._dataStart = pos1;
2619 found._dataEnd = interval_.par.length();
2620 found.disabled = keys["foreignlanguage"].disabled;
2621 found.used = keys["foreignlanguage"].used;
2622 found._tokensize = pos1 - found._tokenstart;
2623 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2626 // Swallow possible optional params
2627 while (interval_.par[pos1] == '[') {
2628 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2630 // Swallow also the eventual parameter
2631 if (interval_.par[pos1] == '{') {
2632 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2635 found._dataEnd = pos1;
2637 found._dataStart = found._dataEnd;
2638 found._tokensize = count + found._dataEnd - pos;
2639 found.parenthesiscount = 0;
2640 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2641 found.disabled = true;
2645 // Handle "\end{...}"
2646 found._dataStart = pos + sub.str(2).length();
2647 found._dataEnd = found._dataStart;
2648 found._tokensize = count + found._dataEnd - pos;
2649 found.parenthesiscount = 0;
2650 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2651 found.disabled = true;
2655 else if (found.keytype != KeyInfo::isRegex) {
2656 found._tokenstart = sub.position(size_t(2));
2657 if (found.parenthesiscount == 0) {
2658 // Probably to be discarded
2659 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2660 char following = interval_.par[following_pos];
2661 if (following == ' ')
2662 found.head = "\\" + sub.str(5) + " ";
2663 else if (following == '=') {
2664 // like \uldepth=1000pt
2665 found.head = sub.str(2);
2668 found.head = "\\" + key;
2669 found._tokensize = found.head.length();
2670 found._dataEnd = found._tokenstart + found._tokensize;
2671 found._dataStart = found._dataEnd;
2674 int params = found._tokenstart + key.length() + 1;
2675 if (evaluatingOptional) {
2676 if (size_t(found._tokenstart) > optionalEnd) {
2677 evaluatingOptional = false;
2680 found.disabled = true;
2683 int optend = params;
2684 while (interval_.par[optend] == '[') {
2685 // discard optional parameters
2686 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2688 if (optend > params) {
2689 key += interval_.par.substr(params, optend-params);
2690 evaluatingOptional = true;
2691 optionalEnd = optend;
2692 if (found.keytype == KeyInfo::isSectioning) {
2693 // Remove optional values (but still keep in header)
2694 interval_.addIntervall(params, optend);
2697 string token = sub.str(7);
2699 if (interval_.par[optend] != '{') {
2701 found.parenthesiscount = 0;
2702 found.head = "\\" + key;
2705 closings = found.parenthesiscount;
2706 if (found.parenthesiscount == 1) {
2707 found.head = "\\" + key + "{";
2709 else if (found.parenthesiscount > 1) {
2711 found.head = sub.str(2) + "{";
2712 closings = found.parenthesiscount - 1;
2715 found.head = "\\" + key + "{";
2718 found._tokensize = found.head.length();
2719 found._dataStart = found._tokenstart + found.head.length();
2720 if (found.keytype == KeyInfo::doRemove) {
2722 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2723 if (endpar >= interval_.par.length())
2724 found._dataStart = interval_.par.length();
2726 found._dataStart = endpar;
2727 found._tokensize = found._dataStart - found._tokenstart;
2730 found._dataStart = found._tokenstart + found._tokensize;
2734 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2735 found._dataStart += 15;
2739 endpos = found._dataStart - 1;
2741 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2742 if (found.keytype == KeyInfo::isList) {
2743 // Check if it really is list env
2744 static regex const listre("^([a-z]+)$");
2746 if (!regex_match(token, sub2, listre)) {
2747 // Change the key of this entry. It is not in a list/item environment
2748 found.keytype = KeyInfo::endArguments;
2751 if (found.keytype == KeyInfo::noMain) {
2752 evaluatingCode = true;
2754 codeStart = found._dataStart;
2756 else if (evaluatingCode) {
2757 if (size_t(found._dataStart) > codeEnd)
2758 evaluatingCode = false;
2759 else if (found.keytype == KeyInfo::isMain) {
2760 // Disable this key, treate it as standard
2761 found.keytype = KeyInfo::isStandard;
2762 found.disabled = true;
2763 if ((codeEnd +1 >= interval_.par.length()) &&
2764 (found._tokenstart == codeStart)) {
2765 // trickery, because the code inset starts
2766 // with \selectlanguage ...
2768 if (entries_.size() > 1) {
2769 entries_[entries_.size()-1]._dataEnd = codeEnd;
2774 if ((endpos == interval_.par.length()) &&
2775 (found.keytype == KeyInfo::doRemove)) {
2776 // Missing closing => error in latex-input?
2777 // therefore do not delete remaining data
2778 found._dataStart -= 1;
2779 found._dataEnd = found._dataStart;
2782 found._dataEnd = endpos;
2784 if (isPatternString) {
2785 keys[key].used = true;
2788 entries_.push_back(found);
2792 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2794 stringstream s(keysstring);
2796 const char delim = '|';
2797 while (getline(s, key, delim)) {
2798 KeyInfo keyII(keyI);
2799 if (isPatternString) {
2802 else if ( !keys[key].used)
2803 keyII.disabled = true;
2808 void LatexInfo::buildKeys(bool isPatternString)
2811 static bool keysBuilt = false;
2812 if (keysBuilt && !isPatternString) return;
2814 // Keys to ignore in any case
2815 makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2816 makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2817 // Known standard keys with 1 parameter.
2818 // Split is done, if not at start of region
2819 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2820 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2821 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2822 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2823 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2824 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2826 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2827 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2828 makeKey("section*|subsection*|subsubsection*|paragraph*",
2829 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2830 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2831 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2833 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2835 // Split is done, if not at start of region
2836 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2837 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2839 // Split is done always.
2840 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2844 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2845 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2846 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2847 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2849 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2850 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2851 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2852 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2854 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2855 // Custom space/skip, remove the content (== length value)
2856 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2857 // Found in fr/UserGuide.lyx
2858 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2860 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2861 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2862 // Known macros to remove (including their parameter)
2864 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2865 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2866 // handle like standard keys with 1 parameter.
2867 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2869 if (ignoreFormats.getDeleted()) {
2870 // Ignore deleted text
2871 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2874 // but preserve added text
2875 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2877 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2879 // Macros to remove, but let the parameter survive
2881 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2883 // Remove language spec from content of these insets
2884 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2886 // Same effect as previous, parameter will survive (because there is no one anyway)
2888 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2889 // Remove table decorations
2890 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2891 // Discard shape-header.
2892 // For footnote or shortcut too, because of lang settings
2893 // and wrong handling if used 'KeyInfo::noMain'
2894 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2895 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2896 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2897 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2898 makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2899 makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2900 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2901 // like ('tiny{}' or '\tiny ' ... )
2902 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2904 // Survives, like known character
2905 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2906 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2907 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2909 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2910 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2911 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2913 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2914 // Remove RTL/LTR marker
2915 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2916 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2917 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2918 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2919 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2920 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2921 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2922 if (isPatternString) {
2923 // Allow the first searched string to rebuild the keys too
2927 // no need to rebuild again
2933 * Keep the list of actual opened parentheses actual
2934 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2936 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2939 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2943 if (c == '\\') skip = 1;
2944 else if (c == '{') {
2947 else if (c == '}') {
2948 handleCloseP(i, closingAllowed);
2954 string Intervall::show(int lastpos)
2956 int idx = 0; /* int intervalls */
2959 if ((unsigned) lastpos > par.size())
2960 lastpos = par.size();
2961 for (idx = 0; idx <= ignoreidx; idx++) {
2962 while (i < lastpos) {
2964 if (i <= borders[idx].low) {
2965 if (borders[idx].low > lastpos)
2966 printsize = lastpos - i;
2968 printsize = borders[idx].low - i;
2969 s += par.substr(i, printsize);
2971 if (i >= borders[idx].low)
2972 i = borders[idx].upper;
2975 i = borders[idx].upper;
2981 s += par.substr(i, lastpos-i);
2987 void Intervall::output(ostringstream &os, int lastpos)
2989 // get number of chars to output
2990 int idx = 0; /* int intervalls */
2993 string startTitle = titleValue;
2994 for (idx = 0; idx <= ignoreidx; idx++) {
2996 if (i <= borders[idx].low) {
2998 if (borders[idx].low > lastpos)
2999 printsize = lastpos - i;
3001 printsize = borders[idx].low - i;
3002 if (printsize > 0) {
3003 os << startTitle << par.substr(i, printsize);
3005 printed += printsize;
3008 handleParentheses(i, false);
3009 if (i >= borders[idx].low)
3010 i = borders[idx].upper;
3013 i = borders[idx].upper;
3020 os << startTitle << par.substr(i, lastpos-i);
3021 printed += lastpos-i;
3023 handleParentheses(lastpos, false);
3025 if (keys["foreignlanguage"].disabled)
3026 startindex = actualdeptindex-langcount;
3028 startindex = actualdeptindex;
3029 for (int i = startindex; i > 0; --i) {
3032 if (hasTitle && (printed > 0))
3034 if (! isPatternString_)
3036 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3039 void LatexInfo::processRegion(int start, int region_end)
3041 while (start < region_end) { /* Let {[} and {]} survive */
3042 int cnt = interval_.isOpeningPar(start);
3044 // Closing is allowed past the region
3045 int closing = interval_.findclosing(start+1, interval_.par.length());
3046 interval_.addIntervall(start, start+1);
3047 interval_.addIntervall(closing, closing+1);
3051 start = interval_.nextNotIgnored(start+1);
3055 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3057 if (actual.parenthesiscount == 0) {
3058 // "{\tiny{} ...}" ==> "{{} ...}"
3059 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3062 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3063 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3064 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3068 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3071 switch (actual.keytype)
3073 case KeyInfo::isTitle: {
3075 nextKeyIdx = getNextKey();
3078 case KeyInfo::cleanToStart: {
3079 actual._dataEnd = actual._dataStart;
3080 nextKeyIdx = getNextKey();
3081 // Search for end of arguments
3082 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3084 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3085 entries_[i].disabled = true;
3087 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3089 while (interval_.par[actual._dataEnd] == ' ')
3091 interval_.addIntervall(0, actual._dataEnd+1);
3092 interval_.actualdeptindex = 0;
3093 interval_.depts[0] = actual._dataEnd+1;
3094 interval_.closes[0] = -1;
3097 case KeyInfo::isText:
3098 interval_.par[actual._tokenstart] = '#';
3099 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3100 nextKeyIdx = getNextKey();
3102 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
3103 if (actual.disabled)
3104 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3106 interval_.addIntervall(actual._dataStart, actual._dataEnd);
3109 case KeyInfo::isChar: {
3110 nextKeyIdx = getNextKey();
3113 case KeyInfo::isSize: {
3114 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3115 if (actual.parenthesiscount == 0)
3116 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3118 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3120 nextKeyIdx = getNextKey();
3122 // Here _dataStart points to '{', so correct it
3123 actual._dataStart += 1;
3124 actual._tokensize += 1;
3125 actual.parenthesiscount = 1;
3126 if (interval_.par[actual._dataStart] == '}') {
3127 // Determine the end if used like '{\tiny{}...}'
3128 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3129 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3132 // Determine the end if used like '\tiny{...}'
3133 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3135 // Split on this key if not at start
3136 int start = interval_.nextNotIgnored(previousStart);
3137 if (start < actual._tokenstart) {
3138 interval_.output(os, actual._tokenstart);
3139 interval_.addIntervall(start, actual._tokenstart);
3141 // discard entry if at end of actual
3142 nextKeyIdx = process(os, actual);
3146 case KeyInfo::endArguments: {
3147 // Remove trailing '{}' too
3148 actual._dataStart += 1;
3149 actual._dataEnd += 1;
3150 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3151 nextKeyIdx = getNextKey();
3154 case KeyInfo::noMain:
3156 case KeyInfo::isStandard: {
3157 if (actual.disabled) {
3159 processRegion(actual._dataStart, actual._dataStart+1);
3160 nextKeyIdx = getNextKey();
3162 // Split on this key if not at datastart of calling entry
3163 int start = interval_.nextNotIgnored(previousStart);
3164 if (start < actual._tokenstart) {
3165 interval_.output(os, actual._tokenstart);
3166 interval_.addIntervall(start, actual._tokenstart);
3168 // discard entry if at end of actual
3169 nextKeyIdx = process(os, actual);
3173 case KeyInfo::removeWithArg: {
3174 nextKeyIdx = getNextKey();
3175 // Search for end of arguments
3176 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3178 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3179 entries_[i].disabled = true;
3181 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3183 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3186 case KeyInfo::doRemove: {
3187 // Remove the key with all parameters and following spaces
3190 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3191 start = actual._dataEnd;
3193 start = actual._dataEnd+1;
3194 for (pos = start; pos < interval_.par.length(); pos++) {
3195 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3198 // Remove also enclosing parentheses [] and {}
3201 while (actual._tokenstart > numpars) {
3202 if (pos+numpars >= interval_.par.size())
3204 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3206 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3212 if (interval_.par[pos+numpars] == ' ')
3216 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3217 nextKeyIdx = getNextKey();
3220 case KeyInfo::isList: {
3221 // Discard space before _tokenstart
3223 for (count = 0; count < actual._tokenstart; count++) {
3224 if (interval_.par[actual._tokenstart-count-1] != ' ')
3227 nextKeyIdx = getNextKey();
3228 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3230 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3232 // How else can we catch this one?
3233 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3234 entries_[i].disabled = true;
3236 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3238 else if (nextKeyIdx > 0) {
3239 // Ignore any lang entries inside data region
3240 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3241 if (entries_[i].keytype == KeyInfo::isMain)
3242 entries_[i].disabled = true;
3245 if (actual.disabled) {
3246 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3249 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3251 if (interval_.par[actual._dataEnd+1] == '[') {
3252 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3253 if ((interval_.par[actual._dataEnd+2] == '{') &&
3254 (interval_.par[posdown-1] == '}')) {
3255 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3256 interval_.addIntervall(posdown-1, posdown+1);
3259 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3260 interval_.addIntervall(posdown, posdown+1);
3262 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3263 if (blk > posdown) {
3264 // Discard at most 1 space after empty item
3266 for (count = 0; count < 1; count++) {
3267 if (interval_.par[blk+count] != ' ')
3271 interval_.addIntervall(blk, blk+count);
3276 case KeyInfo::isSectioning: {
3277 // Discard spaces before _tokenstart
3279 int val = actual._tokenstart;
3280 for (count = 0; count < actual._tokenstart;) {
3281 val = interval_.previousNotIgnored(val-1);
3282 if (val < 0 || interval_.par[val] != ' ')
3285 count = actual._tokenstart - val;
3288 if (actual.disabled) {
3289 removeHead(actual, count);
3290 nextKeyIdx = getNextKey();
3292 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3293 nextKeyIdx = process(os, actual);
3297 case KeyInfo::isMath: {
3298 // Same as regex, use the content unchanged
3299 nextKeyIdx = getNextKey();
3302 case KeyInfo::isRegex: {
3303 // DO NOT SPLIT ON REGEX
3305 nextKeyIdx = getNextKey();
3308 case KeyInfo::isIgnored: {
3309 // Treat like a character for now
3310 nextKeyIdx = getNextKey();
3313 case KeyInfo::isMain: {
3314 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3315 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3316 if (actual._tokenstart > 0) {
3317 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3318 if ((prev >= 0) && interval_.par[prev] == '%')
3319 interval_.addIntervall(prev, prev+1);
3321 if (actual.disabled) {
3323 interval_.langcount++;
3324 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3325 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3326 // Discard also the space before math-equation
3327 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3329 nextKeyIdx = getNextKey();
3330 // interval.resetOpenedP(actual._dataStart-1);
3333 if (actual._tokenstart < 26) {
3334 // for the first (and maybe dummy) language
3335 interval_.setForDefaultLang(actual);
3337 interval_.resetOpenedP(actual._dataStart-1);
3341 case KeyInfo::invalid:
3342 case KeyInfo::headRemove:
3343 // These two cases cannot happen, already handled
3346 // LYXERR(Debug::INFO, "Unhandled keytype");
3347 nextKeyIdx = getNextKey();
3354 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3356 int end = interval_.nextNotIgnored(actual._dataEnd);
3357 int oldStart = actual._dataStart;
3358 int nextKeyIdx = getNextKey();
3360 if ((nextKeyIdx < 0) ||
3361 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3362 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3363 if (oldStart <= end) {
3364 processRegion(oldStart, end);
3369 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3371 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3372 (void) dispatch(os, actual._dataStart, nextKey);
3373 end = nextKey._tokenstart;
3376 processRegion(oldStart, nextKey._tokenstart);
3377 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3379 oldStart = nextKey._dataEnd+1;
3381 // now nextKey is either invalid or is outside of actual._dataEnd
3382 // output the remaining and discard myself
3383 if (oldStart <= end) {
3384 processRegion(oldStart, end);
3386 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3388 // This is the normal case.
3389 // But if using the firstlanguage, the closing may be missing
3391 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3393 if (actual._dataEnd < end)
3394 output_end = interval_.nextNotIgnored(actual._dataEnd);
3395 else if (interval_.par.size() > (size_t) end)
3396 output_end = interval_.nextNotIgnored(end);
3398 output_end = interval_.par.size();
3399 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3400 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3402 // Remove possible empty data
3403 int dstart = interval_.nextNotIgnored(actual._dataStart);
3404 while (interval_.isOpeningPar(dstart) == 1) {
3405 interval_.addIntervall(dstart, dstart+1);
3406 int dend = interval_.findclosing(dstart+1, output_end);
3407 interval_.addIntervall(dend, dend+1);
3408 dstart = interval_.nextNotIgnored(dstart+1);
3410 if (dstart < output_end)
3411 interval_.output(os, output_end);
3413 interval_.addIntervall(0, end);
3415 interval_.addIntervall(actual._tokenstart, end);
3419 string splitOnKnownMacros(string par, bool isPatternString)
3422 LatexInfo li(par, isPatternString);
3423 // LYXERR(Debug::INFO, "Berfore split: " << par);
3424 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3426 DummyKey._tokensize = 0;
3427 DummyKey._dataStart = 0;
3428 DummyKey._dataEnd = par.length();
3429 DummyKey.disabled = true;
3430 int firstkeyIdx = li.getFirstKey();
3432 if (firstkeyIdx >= 0) {
3433 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3434 DummyKey._tokenstart = firstKey._tokenstart;
3436 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3437 // Use dummy firstKey
3438 firstKey = DummyKey;
3439 (void) li.setNextKey(firstkeyIdx);
3442 if (par.substr(firstKey._dataStart, 2) == "% ")
3443 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3445 nextkeyIdx = li.process(os, firstKey);
3446 while (nextkeyIdx >= 0) {
3447 // Check for a possible gap between the last
3448 // entry and this one
3449 int datastart = li.nextNotIgnored(firstKey._dataStart);
3450 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3451 if ((nextKey._tokenstart > datastart)) {
3453 firstKey._dataStart = datastart;
3454 firstKey._dataEnd = par.length();
3455 (void) li.setNextKey(nextkeyIdx);
3456 // Fake the last opened parenthesis
3457 li.setForDefaultLang(firstKey);
3458 nextkeyIdx = li.process(os, firstKey);
3461 if (nextKey.keytype != KeyInfo::isMain) {
3462 firstKey._dataStart = datastart;
3463 firstKey._dataEnd = nextKey._dataEnd+1;
3464 (void) li.setNextKey(nextkeyIdx);
3465 li.setForDefaultLang(firstKey);
3466 nextkeyIdx = li.process(os, firstKey);
3469 nextkeyIdx = li.process(os, nextKey);
3473 // Handle the remaining
3474 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3475 firstKey._dataEnd = par.length();
3477 if ((firstKey._dataStart < firstKey._dataEnd) &&
3478 (par[firstKey._dataStart] != '}')) {
3479 li.setForDefaultLang(firstKey);
3480 (void) li.process(os, firstKey);
3483 // return string definitelly impossible to match, but should be known
3486 s = par; /* no known macros found */
3487 // LYXERR(Debug::INFO, "After split: " << s);
3492 * Try to unify the language specs in the latexified text.
3493 * Resulting modified string is set to "", if
3494 * the searched tex does not contain all the features in the search pattern
3496 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3498 static Features regex_f;
3499 static int missed = 0;
3500 static bool regex_with_format = false;
3502 int parlen = par.length();
3504 while ((parlen > 0) && (par[parlen-1] == '\n')) {
3508 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3509 // Happens to be there in case of description or labeling environment
3515 // Split the latex input into pieces which
3516 // can be digested by our search engine
3517 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3518 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3519 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3520 string doclang = pbuf->params().language->polyglossia();
3521 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3523 bool toIgnoreLang = true;
3524 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3526 if (sub.str(2) != doclang) {
3527 toIgnoreLang = false;
3531 setIgnoreFormat("language", toIgnoreLang, false);
3534 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3535 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3538 result = par.substr(0, parlen);
3539 if (isPatternString) {
3542 regex_f = identifyFeatures(result);
3543 string features = "";
3544 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3545 string a = it->first;
3546 regex_with_format = true;
3547 features += " " + a;
3548 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3550 LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3553 } else if (regex_with_format) {
3554 Features info = identifyFeatures(result);
3555 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3556 string a = it->first;
3557 bool b = it->second;
3558 if (b && ! info[a]) {
3560 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3567 // LYXERR(Debug::INFO, "No regex formats");
3573 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3574 static void identifyClosing(string & t, bool ignoreformat)
3577 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3578 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3580 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3582 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3584 if (! ignoreformat) {
3585 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3593 static int num_replaced = 0;
3594 static bool previous_single_replace = true;
3596 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3599 if (regexp_str.empty() || regexp2_str.empty()) {
3600 regexIsValid = false;
3601 regexError = "Invalid empty regex";
3604 // Handle \w properly
3605 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3606 if (! opt.casesensitive) {
3607 popts |= QRegularExpression::CaseInsensitiveOption;
3609 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3610 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3612 if (regexp.isValid() && regexp2.isValid()) {
3613 regexIsValid = true;
3614 // Check '{', '}' pairs inside the regex
3617 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3618 char c = par_as_string[i];
3625 else if (c == '}') {
3632 if (balanced != 0) {
3633 regexIsValid = false;
3634 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3638 regexIsValid = false;
3639 if (!regexp.isValid())
3640 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3642 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3645 (void)par_as_string;
3646 if (opt.casesensitive) {
3647 regexp = regex(regexp_str);
3648 regexp2 = regex(regexp2_str);
3651 regexp = regex(regexp_str, std::regex_constants::icase);
3652 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3657 static void modifyRegexForMatchWord(string &t)
3660 regex wordre("(\\\\)*((\\.|\\\\b))");
3663 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3665 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3668 else if (sub.str(2) == "\\\\b")
3670 if (lastpos < (size_t) sub.position(2))
3671 s += t.substr(lastpos, sub.position(2) - lastpos);
3673 lastpos = sub.position(2) + sub.length(2);
3676 s = "\\b" + t + "\\b";
3680 else if (lastpos < t.length())
3681 s += t.substr(lastpos, t.length() - lastpos);
3682 t = "\\b" + s + "\\b";
3685 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3686 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3688 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3689 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3691 CreateRegexp(opt, "", "", "");
3694 use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3695 if (opt.replace_all && previous_single_replace) {
3696 previous_single_replace = false;
3699 else if (!opt.replace_all) {
3700 num_replaced = 0; // count number of replaced strings
3701 previous_single_replace = true;
3703 // When using regexp, braces are hacked already by escape_for_regex()
3704 par_as_string = convertLF2Space(ds, opt.ignoreformat);
3706 size_t lead_size = 0;
3707 // correct the language settings
3708 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3709 if (par_as_string.empty()) {
3710 CreateRegexp(opt, "", "", "");
3713 opt.matchAtStart = false;
3715 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3716 if (opt.ignoreformat) {
3720 lead_size = identifyLeading(par_as_string);
3722 lead_as_string = par_as_string.substr(0, lead_size);
3723 string lead_as_regex_string = string2regex(lead_as_string);
3724 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3725 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3726 /* Handle whole words too in this case
3728 if (opt.matchword) {
3729 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3730 opt.matchword = false;
3732 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3733 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3734 CreateRegexp(opt, regexp_str, regexp2_str);
3736 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3737 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3741 if (!opt.ignoreformat) {
3742 lead_size = identifyLeading(par_as_string);
3743 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3744 lead_as_string = par_as_string.substr(0, lead_size);
3745 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3748 // Here we are using regexp
3749 LASSERT(use_regexp, /**/);
3751 string lead_as_regexp;
3752 if (lead_size > 0) {
3753 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3754 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3755 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3756 par_as_string = par_as_string_nolead;
3757 LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3758 LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3760 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3761 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3762 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3763 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3765 size_t lng = par_as_string.size();
3766 if (!opt.ignoreformat) {
3767 // Remove extra '\}' at end if not part of \{\.\}
3769 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3771 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3780 if (lng < par_as_string.size())
3781 par_as_string.resize(lng);
3783 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3784 if ((lng > 0) && (par_as_string[0] == '^')) {
3785 par_as_string = par_as_string.substr(1);
3787 opt.matchAtStart = true;
3789 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3790 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3791 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3793 // If entered regexp must match at begin of searched string buffer
3794 // Kornel: Added parentheses to use $1 for size of the leading string
3798 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3799 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3800 // so the convert has no effect in that case
3801 for (int i = 7; i > 0; --i) {
3802 string orig = "\\\\" + std::to_string(i);
3803 string dest = "\\" + std::to_string(i+2);
3804 while (regex_replace(par_as_string, par_as_string, orig, dest));
3806 if (opt.matchword) {
3807 modifyRegexForMatchWord(par_as_string);
3808 // opt.matchword = false;
3810 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3811 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3813 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3814 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3815 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3819 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3823 mres.searched_size = len;
3825 docstring docstr = stringifyFromForSearch(opt, cur, len);
3827 str = convertLF2Space(docstr, opt.ignoreformat);
3828 if (!opt.ignoreformat) {
3829 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3830 // remove closing '}' and '\n' to allow for use of '$' in regex
3831 size_t lng = str.size();
3832 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3834 if (lng != str.size()) {
3835 str = str.substr(0, lng);
3837 // Replace occurences of '~' to ' '
3838 static std::regex specialChars { R"(~)" };
3839 str = std::regex_replace(str, specialChars, R"( )" );
3842 mres.match_len = -1;
3845 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3847 LASSERT(use_regexp, /**/);
3849 // use_regexp always true
3850 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3852 QString qstr = QString::fromStdString(str);
3853 QRegularExpression const *p_regexp;
3854 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3855 if (at_begin == MatchStringAdv::MatchFromStart) {
3858 p_regexp = ®exp2;
3860 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3861 if (!match.hasMatch())
3864 regex const *p_regexp;
3865 regex_constants::match_flag_type flags;
3866 if (at_begin == MatchStringAdv::MatchFromStart) {
3867 flags = regex_constants::match_continuous;
3870 flags = regex_constants::match_default;
3871 p_regexp = ®exp2;
3873 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3874 if (re_it == sregex_iterator())
3876 match_results<string::const_iterator> const & m = *re_it;
3878 // Whole found string, including the leading
3879 // std: m[0].second - m[0].first
3880 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3882 // Size of the leading string
3883 // std: m[1].second - m[1].first
3884 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3885 int leadingsize = 0;
3887 if (match.lastCapturedIndex() > 0) {
3888 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3893 leadingsize = m[1].second - m[1].first;
3897 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3898 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3899 // because of different number of closing at end of string
3900 // we have to 'unify' the length of the post-match.
3901 // Done by ignoring closing parenthesis and linefeeds at string end
3902 int matchend = match.capturedEnd(0);
3903 size_t strsize = qstr.size();
3904 if (!opt.ignoreformat) {
3905 while (mres.match_len > 1) {
3906 QChar c = qstr.at(matchend - 1);
3907 if ((c == '\n') || (c == '}') || (c == '{')) {
3914 while (strsize > (size_t) match.capturedEnd(0)) {
3915 QChar c = qstr.at(strsize-1);
3916 if ((c == '\n') || (c == '}')) {
3923 // LYXERR0(qstr.toStdString());
3924 mres.match2end = strsize - matchend;
3925 mres.pos = match.capturedStart(2);
3927 mres.match_prefix = m[2].second - m[2].first;
3928 mres.match_len = m[0].second - m[2].second;
3929 // ignore closing parenthesis and linefeeds at string end
3930 size_t strend = m[0].second - m[0].first;
3931 int matchend = strend;
3932 size_t strsize = str.size();
3933 if (!opt.ignoreformat) {
3934 while (mres.match_len > 1) {
3935 char c = str.at(matchend - 1);
3936 if ((c == '\n') || (c == '}') || (c == '{')) {
3943 while (strsize > strend) {
3944 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3952 mres.match2end = strsize - matchend;
3953 mres.pos = m[2].first - m[0].first;;
3955 if (mres.match2end < 0)
3957 mres.leadsize = leadingsize;
3959 if (mres.match_len > 0) {
3960 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3961 mres.result.push_back(a0);
3962 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3963 mres.result.push_back(match.captured(i).toStdString());
3967 if (mres.match_len > 0) {
3968 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3969 mres.result.push_back(a0);
3970 for (size_t i = 3; i < m.size(); i++) {
3971 mres.result.push_back(m[i]);
3980 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3982 MatchResult mres = findAux(cur, len, at_begin);
3983 LYXERR(Debug::FINDVERBOSE,
3984 "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3985 << ", matchAtStart=" << opt.matchAtStart
3986 << ", inTexted=" << cur.inTexted());
3987 if (mres.match_len > 0) {
3988 if (opt.matchAtStart) {
3989 if (cur.pos() > 0 || mres.match_prefix > 0)
3997 static bool simple_replace(string &t, string from, string to)
3999 regex repl("(\\\\)*(" + from + ")");
4003 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
4005 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4007 if (lastpos < (size_t) sub.position(2))
4008 s += t.substr(lastpos, sub.position(2) - lastpos);
4010 lastpos = sub.position(2) + sub.length(2);
4014 else if (lastpos < t.length())
4015 s += t.substr(lastpos, t.length() - lastpos);
4021 string MatchStringAdv::convertLF2Space(docstring const &s, bool ignore_format) const
4023 // Using original docstring to handle '\n'
4025 if (s.size() == 0) return "";
4029 size_t end = s.size() - 1;
4030 if (!ignore_format) {
4031 while (s[start] == '\n' && start <= end)
4033 while (end >= start && s[end] == '\n')
4035 if (start >= end + 1)
4039 bool dospace = true;
4041 pos = s.find('\n', start);
4043 t << lyx::to_utf8(s.substr(start, end + 1 - start));
4046 if (!ignore_format) {
4047 if ((pos > start + 1) &&
4051 if ((pos > start + 2) &&
4052 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4053 s[pos-3] == '~' || isSpace(s[pos-3]))) {
4054 // discard "\\\\\n", do not replace with space
4058 else if (pos > start) {
4059 if (s[pos-1] == '%') {
4061 while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4063 if ((pos > start+skip) &&
4064 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4065 s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4066 // discard '%%%%%\n'
4070 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4072 skip = 0; // remove the '\n' only
4080 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4084 } while (start <= end);
4088 docstring stringifyFromCursor(DocIterator const & cur, int len)
4090 LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4091 if (cur.inTexted()) {
4092 Paragraph const & par = cur.paragraph();
4093 // TODO what about searching beyond/across paragraph breaks ?
4094 // TODO Try adding a AS_STR_INSERTS as last arg
4095 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4096 int(par.size()) : cur.pos() + len;
4097 // OutputParams runparams(&cur.buffer()->params().encoding());
4098 OutputParams runparams(encodings.fromLyXName("utf8"));
4099 runparams.nice = true;
4100 setFindParams(runparams);
4101 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4102 if (ignoreFormats.getDeleted()) {
4103 option |= AS_STR_SKIPDELETE;
4104 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4107 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4109 if (ignoreFormats.getNonContent()) {
4110 runparams.find_add_feature(OutputParams::SearchNonOutput);
4112 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4113 << cur << ", from pos: " << cur.pos() << ", end: " << end);
4114 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4116 &runparams), false));
4117 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4119 } else if (cur.inMathed()) {
4120 CursorSlice cs = cur.top();
4121 MathData md = cs.cell();
4122 MathData::const_iterator it_end =
4123 (( len == -1 || cs.pos() + len > int(md.size()))
4125 : md.begin() + cs.pos() + len );
4127 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4129 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4130 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4133 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4137 /** Computes the LaTeX export of buf starting from cur and ending len positions
4138 * after cur, if len is positive, or at the paragraph or innermost inset end
4141 docstring latexifyFromCursor(DocIterator const & cur, int len)
4144 LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4145 LYXERR(Debug::FINDVERBOSE, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4146 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4148 Buffer const & buf = *cur.buffer();
4150 odocstringstream ods;
4152 //OutputParams runparams(&buf.params().encoding());
4153 OutputParams runparams(encodings.fromLyXName("utf8"));
4154 runparams.nice = false;
4155 setFindParams(runparams);
4156 if (ignoreFormats.getDeleted()) {
4157 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4160 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4162 if (ignoreFormats.getNonContent()) {
4163 runparams.find_add_feature(OutputParams::SearchNonOutput);
4166 if (cur.inTexted()) {
4167 // @TODO what about searching beyond/across paragraph breaks ?
4168 pos_type endpos = cur.paragraph().size();
4169 if (len != -1 && endpos > cur.pos() + len)
4170 endpos = cur.pos() + len;
4171 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4172 string(), cur.pos(), endpos, true);
4173 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4175 } else if (cur.inMathed()) {
4176 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4177 for (int s = cur.depth() - 1; s >= 0; --s) {
4178 CursorSlice const & cs = cur[s];
4179 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4180 TeXMathStream ws(os);
4181 cs.asInsetMath()->asHullInset()->header_write(ws);
4186 CursorSlice const & cs = cur.top();
4187 MathData md = cs.cell();
4188 MathData::const_iterator it_end =
4189 ((len == -1 || cs.pos() + len > int(md.size()))
4191 : md.begin() + cs.pos() + len);
4193 for (MathData::const_iterator it = md.begin() + cs.pos();
4197 ods << asString(md2);
4198 // Retrieve the math environment type, and add '$' or '$]'
4199 // or others (\end{equation}) accordingly
4200 for (int s = cur.depth() - 1; s >= 0; --s) {
4201 CursorSlice const & cs2 = cur[s];
4202 InsetMath * inset = cs2.asInsetMath();
4203 if (inset && inset->asHullInset()) {
4204 TeXMathStream ws(os);
4205 inset->asHullInset()->footer_write(ws);
4209 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4211 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4216 #if defined(ResultsDebug)
4218 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4220 LYXERR0( "from:\t\t\t" << from);
4222 if (mres.pos_len > 0) {
4224 status = "FINALSEARCH";
4227 if (mres.match_len > 0) {
4228 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4229 status = "Good Match";
4231 status = "Matched in";
4234 status = "MissedSearch";
4237 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4238 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4239 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4240 if ((mres.pos > 0) || (mres.match_prefix > 0))
4241 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4242 for (size_t i = 0; i < mres.result.size(); i++)
4243 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4245 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4247 #define displayMres(s, txt, cur)
4250 /** Finalize an advanced find operation, advancing the cursor to the innermost
4251 ** position that matches, plus computing the length of the matching text to
4253 ** Return the cur.pos() difference between start and end of found match
4255 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4257 // Search the foremost position that matches (avoids find of entire math
4258 // inset when match at start of it)
4259 DocIterator old_cur(cur.buffer());
4261 static MatchResult fail = MatchResult();
4262 MatchResult max_match;
4263 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4264 // Happens with e.g. hyperlinks
4265 // either one sees "http://www.bla.bla" or nothing
4266 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4267 // and although we search for only 3 chars, we find the whole hyperlink inset
4268 MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4269 if (!match.opt.forward && match.opt.ignoreformat) {
4270 if (expected.pos > 0)
4273 LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4274 if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4275 // Search for deepest match
4277 max_match = expected;
4279 size_t d = cur.depth();
4283 if (cur.depth() < d)
4285 if (cur.depth() == d)
4288 while (cur && cur.depth() > lastd) {
4289 lastd = cur.depth();
4290 mres = match(cur, -1, at_begin);
4291 displayMres(mres, "Checking innermost", cur);
4292 if (mres.match_len > 0)
4297 if (mres.match_len < expected.match_len)
4305 // (expected.match_len <= 0)
4306 mres = match(cur, -1, MatchStringAdv::MatchFromStart); /* match valid only if not searching whole words */
4307 displayMres(mres, "Start with negative match", cur);
4310 // Only now we are really at_begin
4311 if ((max_match.match_len <= 0) ||
4312 (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4314 LYXERR(Debug::FINDVERBOSE, "Ok");
4316 // Compute the match length
4318 if (cur.pos() + len > cur.lastpos())
4321 LASSERT(match.use_regexp, /**/);
4324 int maxl = cur.lastpos() - cur.pos();
4325 // Greedy behaviour while matching regexps
4326 while (maxl > minl) {
4328 mres2 = match(cur, len, at_begin);
4329 displayMres(mres2, "Finalize loop", cur);
4330 int actual_match_len = mres2.match_len;
4331 if (actual_match_len >= max_match.match_len) {
4332 // actual_match_len > max_match _can_ happen,
4333 // if the search area splits
4334 // some following word so that the regex
4335 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4337 // This means, the len value is too big
4338 actual_match_len = max_match.match_len;
4340 max_match.match_len = actual_match_len;
4342 if (maxl - minl < 4)
4343 len = (maxl + minl)/2;
4345 len = minl + (maxl - minl + 3)/4;
4348 // (actual_match_len < max_match.match_len)
4350 len = (maxl + minl)/2;
4355 // Search for real start of matched characters
4357 MatchResult actual_match;
4360 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4361 if (cur.depth() < old_cur.depth()) {
4363 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4366 if (cur.pos() != old_cur.pos()) {
4367 // OK, forwarded 1 pos in actual inset
4368 actual_match = match(cur, len-1, at_begin);
4369 if (actual_match.match_len == max_match.match_len) {
4370 // Ha, got it! The shorter selection has the same match length
4373 max_match = actual_match;
4376 // OK, the shorter selection matches less chars, revert to previous value
4382 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4383 actual_match = match(cur, len, at_begin);
4384 if (actual_match.match_len == max_match.match_len) {
4386 max_match = actual_match;
4393 max_match.pos_len = len;
4394 displayMres(max_match, "SEARCH RESULT", cur)
4401 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4406 DocIterator orig_cur; // to be used if repeat not successful
4407 MatchResult orig_mres;
4411 } while (cur.depth() > orig_cur.depth());
4413 while (!theApp()->longOperationCancelled() && cur) {
4414 //(void) findAdvForwardInnermost(cur);
4415 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4416 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4417 string msg = "Starting";
4420 displayMres(mres, msg + " findForwardAdv", cur)
4421 int match_len = mres.match_len;
4422 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4423 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4426 if (match_len <= 0) {
4431 // This should exit nested insets, if any, or otherwise undefine the currsor.
4432 cur.pos() = cur.lastpos();
4434 LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4437 else { // match_len > 0
4438 // Try to find the begin of searched string
4440 int firstInvalid = cur.lastpos() - cur.pos();
4442 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4443 int incrcur = (firstInvalid + 1 )*3/4;
4444 if (incrcur < incrmatch)
4445 increment = incrcur;
4447 increment = incrmatch;
4451 LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4452 while (increment > 0) {
4453 DocIterator old_cur = cur;
4454 if (cur.pos() + increment >= cur.lastpos()) {
4458 cur.pos() = cur.pos() + increment;
4459 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4460 displayMres(mres2, "findForwardAdv loop", cur)
4461 switch (interpretMatch(mres, mres2)) {
4462 case MatchResult::newIsTooFar:
4463 // behind the expected match
4464 firstInvalid = increment;
4468 case MatchResult::newIsBetter:
4469 // not reached yet, but cur.pos()+increment is better
4471 firstInvalid -= increment;
4472 if (increment > firstInvalid*3/4)
4473 increment = firstInvalid*3/4;
4474 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4475 if (increment >= mres2.match_prefix)
4476 increment = (mres2.match_prefix+1)*3/4;
4481 // Handle not like MatchResult::newIsTooFar
4482 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4484 increment = increment*3/4;
4489 if (mres.match_len > 0) {
4490 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4491 // The match seems to indicate some deeper level
4499 else if (repeat > 0) {
4500 // should never be reached.
4504 // LYXERR0("Leaving first loop");
4505 LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4506 MatchResult found_match = findAdvFinalize(cur, match, mres);
4507 if (found_match.match_len > 0) {
4508 match.FillResults(found_match);
4509 return found_match.pos_len;
4512 // try next possible match
4523 /// Find the most backward consecutive match within same paragraph while searching backwards.
4524 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4526 DocIterator cur_begin = cur;
4527 cur_begin.pos() = 0;
4528 DocIterator tmp_cur = cur;
4529 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4530 Inset & inset = cur.inset();
4531 for (; cur != cur_begin; cur.backwardPos()) {
4532 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4533 DocIterator new_cur = cur;
4534 new_cur.backwardPos();
4535 if (new_cur == cur || &new_cur.inset() != &inset
4536 || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4538 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4539 if (new_mr.match_len == mr.match_len)
4543 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4549 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4553 // Backup of original position
4554 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4555 if (cur == cur_begin)
4558 DocIterator cur_orig(cur);
4559 bool pit_changed = false;
4562 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4564 if (found_match.match_len > 0) {
4566 cur.pos() = cur.lastpos();
4568 cur.pos() = cur_orig.pos();
4569 LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4570 DocIterator cur_prev_iter;
4572 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4573 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4574 << (found_match.match_len > 0) << ", cur: " << cur);
4575 if (found_match.match_len > 0) {
4576 MatchResult found_mr = findMostBackwards(cur, match, found_match);
4577 if (found_mr.pos_len > 0) {
4578 match.FillResults(found_mr);
4579 return found_mr.pos_len;
4583 // Stop if begin of document reached
4584 if (cur == cur_begin)
4586 cur_prev_iter = cur;
4590 if (cur == cur_begin)
4597 } while (!theApp()->longOperationCancelled());
4605 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4606 DocIterator const & cur, int len)
4608 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4610 if (!opt.ignoreformat)
4611 return latexifyFromCursor(cur, len);
4613 return stringifyFromCursor(cur, len);
4617 FindAndReplaceOptions::FindAndReplaceOptions(
4618 docstring const & _find_buf_name, bool _casesensitive,
4619 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4620 docstring const & _repl_buf_name, bool _keep_case,
4621 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4622 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4623 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4624 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4632 /** Check if 'len' letters following cursor are all non-lowercase */
4633 static bool allNonLowercase(Cursor const & cur, int len)
4635 pos_type beg_pos = cur.selectionBegin().pos();
4636 pos_type end_pos = cur.selectionBegin().pos() + len;
4637 if (len > cur.lastpos() + 1 - beg_pos) {
4638 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4639 len = cur.lastpos() + 1 - beg_pos;
4640 end_pos = beg_pos + len;
4642 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4643 if (isLowerCase(cur.paragraph().getChar(pos)))
4649 /** Check if first letter is upper case and second one is lower case */
4650 static bool firstUppercase(Cursor const & cur)
4653 pos_type pos = cur.selectionBegin().pos();
4654 if (pos >= cur.lastpos() - 1) {
4655 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4658 ch1 = cur.paragraph().getChar(pos);
4659 ch2 = cur.paragraph().getChar(pos + 1);
4660 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4661 LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4662 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4663 << ch2 << "(" << char(ch2) << ")"
4664 << ", result=" << result << ", cur=" << cur);
4669 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4671 ** \fixme What to do with possible further paragraphs in replace buffer ?
4673 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4675 ParagraphList::iterator pit = buffer.paragraphs().begin();
4676 LASSERT(!pit->empty(), /**/);
4677 pos_type right = pos_type(1);
4678 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4679 right = pit->size();
4680 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4684 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4686 // Should replace the string "$" + std::to_string(matchnum) with replacement
4687 // if the char '$' is not prefixed with odd number of char '\\'
4688 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4692 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4694 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4696 int num = stoi(sub.str(3), nullptr, 10);
4697 if (num >= maxmatchnum)
4699 if (lastpos < (size_t) sub.position(2))
4700 s += t.substr(lastpos, sub.position(2) - lastpos);
4701 s += replacements[num];
4702 lastpos = sub.position(2) + sub.length(2);
4706 else if (lastpos < t.length())
4707 s += t.substr(lastpos, t.length() - lastpos);
4713 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4715 Cursor & cur = bv->cursor();
4716 if (opt.repl_buf_name.empty()
4717 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4718 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4721 DocIterator sel_beg = cur.selectionBegin();
4722 DocIterator sel_end = cur.selectionEnd();
4723 if (&sel_beg.inset() != &sel_end.inset()
4724 || sel_beg.pit() != sel_end.pit()
4725 || sel_beg.idx() != sel_end.idx())
4727 int sel_len = sel_end.pos() - sel_beg.pos();
4728 LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4729 << ", sel_len: " << sel_len << endl);
4732 LASSERT(sel_len > 0, return 0);
4734 if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4737 // Build a copy of the replace buffer, adapted to the KeepCase option
4738 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4740 repl_buffer_orig.write(oss);
4741 string lyx = oss.str();
4742 if (matchAdv.valid_matches > 0)
4743 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4744 Buffer repl_buffer(string(), false);
4745 repl_buffer.setInternal(true);
4746 repl_buffer.setUnnamed(true);
4747 LASSERT(repl_buffer.readString(lyx), return 0);
4748 if (opt.keep_case && sel_len >= 2) {
4749 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4750 if (cur.inTexted()) {
4751 if (firstUppercase(cur))
4752 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4753 else if (allNonLowercase(cur, sel_len))
4754 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4757 cap::cutSelection(cur, false);
4758 if (cur.inTexted()) {
4759 repl_buffer.changeLanguage(
4760 repl_buffer.language(),
4761 cur.getFont().language());
4762 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4763 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4764 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4765 repl_buffer.params().documentClassPtr(),
4766 repl_buffer.params().authors(),
4767 bv->buffer().errorList("Paste"));
4768 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4769 sel_len = repl_buffer.paragraphs().begin()->size();
4770 } else if (cur.inMathed()) {
4771 odocstringstream ods;
4773 // OutputParams runparams(&repl_buffer.params().encoding());
4774 OutputParams runparams(encodings.fromLyXName("utf8"));
4775 runparams.nice = false;
4776 setFindParams(runparams);
4777 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4778 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4779 docstring repl_latex = ods.str();
4780 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4782 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4783 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4784 repl_latex = from_utf8(s);
4785 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4786 MathData ar(cur.buffer());
4787 asArray(repl_latex, ar, Parse::NORMAL);
4789 sel_len = ar.size();
4790 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4792 if (cur.pos() >= sel_len)
4793 cur.pos() -= sel_len;
4796 LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4797 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4798 bv->processUpdateFlags(Update::Force);
4802 static bool isWordChar(char_type c)
4804 return isLetterChar(c) || isNumberChar(c);
4807 /// Perform a FindAdv operation.
4808 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4813 // e.g., when invoking word-findadv from mini-buffer wither with
4814 // wrong options syntax or before ever opening advanced F&R pane
4815 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4819 MatchStringAdv matchAdv(bv->buffer(), opt);
4821 if (!matchAdv.regexIsValid) {
4822 bv->message(lyx::from_utf8(matchAdv.regexError));
4826 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4828 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4829 num_replaced += findAdvReplace(bv, opt, matchAdv);
4832 if (opt.matchword && cur.pos() > 0) { // Skip word-characters if we are in the mid of a word
4833 if (cur.inTexted()) {
4834 Paragraph const & par = cur.paragraph();
4835 int len_limit, new_pos;
4836 if (cur.lastpos() < par.size())
4837 len_limit = cur.lastpos();
4839 len_limit = par.size();
4840 for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4841 if (!isWordChar(par.getChar(new_pos)))
4844 if (new_pos > cur.pos())
4845 cur.pos() = new_pos;
4847 else if (cur.inMathed()) {
4848 // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4849 // I am not sure, we should consider the selection
4850 bool sel = bv->cursor().selection();
4851 if (!sel && cur.pos() < cur.lastpos()) {
4852 CursorSlice const & cs = cur.top();
4853 MathData md = cs.cell();
4855 MathData::const_iterator it_end = md.end();
4857 // Start the check with one character before actual cursor position
4858 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4861 docstring inp = asString(md2);
4862 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4863 if (!isWordChar(inp[len]))
4866 // len == 0 means previous char was a word separator
4867 // len == 1 search starts with a word separator
4868 // len == 2 ... we have to skip len -1 chars
4870 cur.pos() = cur.pos() + len - 1;
4873 opt.matchword = false;
4875 pos_len = findForwardAdv(cur, matchAdv);
4878 pos_len = findBackwardsAdv(cur, matchAdv);
4879 } catch (exception & ex) {
4880 bv->message(from_utf8(ex.what()));
4885 if (num_replaced > 0) {
4886 switch (num_replaced)
4889 bv->message(_("One match has been replaced."));
4892 bv->message(_("Two matches have been replaced."));
4895 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4901 bv->message(_("Match not found."));
4906 if (num_replaced > 0)
4907 bv->message(_("Match has been replaced."));
4909 bv->message(_("Match found."));
4911 if (cur.pos() + pos_len > cur.lastpos()) {
4912 // Prevent crash in bv->putSelectionAt()
4913 // Should never happen, maybe LASSERT() here?
4914 pos_len = cur.lastpos() - cur.pos();
4916 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4917 bv->putSelectionAt(cur, pos_len, !opt.forward);
4923 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4925 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4926 << opt.casesensitive << ' '
4927 << opt.matchword << ' '
4928 << opt.forward << ' '
4929 << opt.expandmacros << ' '
4930 << opt.ignoreformat << ' '
4931 << opt.replace_all << ' '
4932 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4933 << opt.keep_case << ' '
4934 << int(opt.scope) << ' '
4937 LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4943 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4945 // LYXERR(Debug::FINDVERBOSE, "parsing");
4949 while (line != "EOSS") {
4953 if (is.eof()) // Tolerate malformed request
4957 // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4958 opt.find_buf_name = from_utf8(s);
4959 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4960 is.get(); // Waste space before replace string
4963 while (line != "EOSS") {
4967 if (is.eof()) // Tolerate malformed request
4971 // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
4972 opt.repl_buf_name = from_utf8(s);
4973 is >> opt.keep_case;
4976 opt.scope = FindAndReplaceOptions::SearchScope(i);
4978 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4981 LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4982 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4983 << opt.scope << ' ' << opt.restr);