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 bool const had_selection = bv->cursor().selection();
294 // Clean up previous selections with empty searchstr on instant
295 if (searchstr.empty() && instant) {
297 bv->setCursor(bv->cursor().selectionBegin());
298 bv->clearSelection();
303 if (!searchAllowed(searchstr))
306 DocIterator const startcur = bv->cursor().selectionBegin();
307 DocIterator const endcur = bv->cursor().selectionEnd();
309 if (onlysel && had_selection) {
310 docstring const matchstring = bv->cursor().selectionAsString(false);
311 docstring const lcmatchsting = support::lowercase(matchstring);
312 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
313 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
314 "Continue search outside?");
315 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
316 q, 0, 1, _("&Yes"), _("&No"));
317 if (search_answer == 0) {
318 bv->clearSelection();
319 if (findOne(bv, searchstr, case_sens, whole, forward,
320 find_del, check_wrap, auto_wrap, false, false))
327 DocIterator cur = forward
328 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
329 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
331 MatchString const match(searchstr, case_sens, whole);
333 int match_len = forward
334 ? findForward(cur, endcur, match, find_del, onlysel)
335 : findBackwards(cur, startcur, match, find_del, onlysel);
338 bv->putSelectionAt(cur, match_len, !forward);
339 else if (onlysel && had_selection) {
340 docstring q = _("The search string was not found within the selection.\n"
341 "Continue search outside?");
342 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
343 q, 0, 1, _("&Yes"), _("&No"));
344 if (search_answer == 0) {
345 bv->clearSelection();
346 if (findOne(bv, searchstr, case_sens, whole, forward,
347 find_del, check_wrap, auto_wrap, false, false))
352 else if (check_wrap) {
353 bool wrap = auto_wrap;
357 q = _("End of file reached while searching forward.\n"
358 "Continue searching from the beginning?");
360 q = _("Beginning of file reached while searching backward.\n"
361 "Continue searching from the end?");
362 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
363 q, 0, 1, _("&Yes"), _("&No"));
364 wrap = wrap_answer == 0;
368 bv->cursor().clear();
369 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
371 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
372 bv->cursor().backwardPos();
375 docstring const msg = forward
376 ? _("Search reached end of document, continuing from beginning.")
377 : _("Search reached beginning of document, continuing from end.");
380 bv->clearSelection();
381 if (findOne(bv, searchstr, case_sens, whole, forward,
382 find_del, false, false, false, false))
385 bv->setCursor(startcur);
387 // restore original selection
389 bv->cursor().resetAnchor();
390 bv->setSelection(startcur, endcur);
395 return match_len > 0;
401 int replaceAll(BufferView * bv,
402 docstring const & searchstr, docstring const & replacestr,
403 bool case_sens, bool whole, bool onlysel)
405 Buffer & buf = bv->buffer();
407 if (!searchAllowed(searchstr) || buf.isReadonly())
410 DocIterator startcur = bv->cursor().selectionBegin();
411 DocIterator endcur = bv->cursor().selectionEnd();
412 bool const had_selection = bv->cursor().selection();
414 MatchString const match(searchstr, case_sens, whole);
417 int const rsize = replacestr.size();
418 int const ssize = searchstr.size();
421 cur.setCursor(doc_iterator_begin(&buf));
422 int match_len = findForward(cur, endcur, match, false, onlysel);
423 while (match_len > 0) {
424 // Backup current cursor position and font.
425 pos_type const pos = cur.pos();
426 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
428 int ct_deleted_text = ssize -
429 cur.paragraph().eraseChars(pos, pos + match_len,
430 buf.params().track_changes);
431 cur.paragraph().insert(pos, replacestr, font,
432 Change(buf.params().track_changes
434 : Change::UNCHANGED));
435 for (int i = 0; i < rsize + ct_deleted_text
436 && cur.pos() < cur.lastpos(); ++i)
438 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
439 // Adjust end of selection for replace-all in selection
441 int const offset = rsize - ssize;
442 for (int i = 0; i < offset + ct_deleted_text
443 && endcur.pos() < endcur.lastpos(); ++i)
446 int const offset = ssize - rsize;
447 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
448 endcur.backwardPos();
449 for (int i = 0; i < ct_deleted_text
450 && endcur.pos() < endcur.lastpos(); ++i)
455 match_len = findForward(cur, endcur, match, false, onlysel);
458 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
460 startcur.fixIfBroken();
461 bv->setCursor(startcur);
463 // Reset selection, accounting for changes in selection
465 endcur.fixIfBroken();
466 bv->cursor().resetAnchor();
467 bv->setSelection(startcur, endcur);
474 // the idea here is that we are going to replace the string that
475 // is selected IF it is the search string.
476 // if there is a selection, but it is not the search string, then
477 // we basically ignore it. (FIXME We ought to replace only within
479 // if there is no selection, then:
480 // (i) if some search string has been provided, then we find it.
481 // (think of how the dialog works when you hit "replace" the
483 // (ii) if no search string has been provided, then we treat the
484 // word the cursor is in as the search string. (why? i have no
485 // idea.) but this only works in text?
487 // returns the number of replacements made (one, if any) and
488 // whether anything at all was done.
489 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
490 docstring const & replacestr, bool case_sens,
491 bool whole, bool forward, bool findnext, bool wrap,
494 Cursor & cur = bv->cursor();
495 if (!cur.selection() || onlysel) {
496 // no selection, non-empty search string: find it
497 if (!searchstr.empty()) {
498 bool const found = findOne(bv, searchstr, case_sens, whole,
499 forward, true, findnext, wrap, false, onlysel);
500 return make_pair(found, 0);
502 // empty search string
505 return make_pair(false, 0);
506 // select current word and treat it as the search string.
507 // This causes a minor bug as undo will restore this selection,
508 // which the user did not create (#8986).
509 cur.innerText()->selectWord(cur, WHOLE_WORD);
510 searchstr = cur.selectionAsString(false, true);
513 // if we still don't have a search string, report the error
515 if (!searchAllowed(searchstr))
516 return make_pair(false, 0);
518 bool have_selection = cur.selection();
519 docstring const selected = cur.selectionAsString(false, true);
522 ? searchstr == selected
523 : compare_no_case(searchstr, selected) == 0;
525 // no selection or current selection is not search word:
526 // just find the search word
527 if (!have_selection || !match) {
528 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
529 true, findnext, wrap, false, onlysel);
530 return make_pair(found, 0);
533 // we're now actually ready to replace. if the buffer is
534 // read-only, we can't, though.
535 if (bv->buffer().isReadonly())
536 return make_pair(false, 0);
538 cap::replaceSelectionWithString(cur, replacestr);
540 cur.pos() += replacestr.length();
541 LASSERT(cur.pos() <= cur.lastpos(),
542 cur.pos() = cur.lastpos());
545 findOne(bv, searchstr, case_sens, whole,
546 forward, false, findnext, wrap, false, onlysel);
548 return make_pair(true, 1);
554 docstring const find2string(docstring const & search,
555 bool casesensitive, bool matchword,
556 bool forward, bool wrap, bool instant,
561 << int(casesensitive) << ' '
562 << int(matchword) << ' '
563 << int(forward) << ' '
565 << int(instant) << ' '
571 docstring const replace2string(docstring const & replace,
572 docstring const & search,
573 bool casesensitive, bool matchword,
574 bool all, bool forward, bool findnext,
575 bool wrap, bool onlysel)
578 ss << replace << '\n'
580 << int(casesensitive) << ' '
581 << int(matchword) << ' '
583 << int(forward) << ' '
584 << int(findnext) << ' '
591 docstring const string2find(docstring const & argument,
599 // data is of the form
601 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
603 docstring howto = split(argument, search, '\n');
605 casesensitive = parse_bool(howto);
606 matchword = parse_bool(howto);
607 forward = parse_bool(howto, true);
608 wrap = parse_bool(howto);
609 instant = parse_bool(howto);
610 onlysel = parse_bool(howto);
616 bool lyxfind(BufferView * bv, FuncRequest const & ev)
618 if (!bv || ev.action() != LFUN_WORD_FIND)
621 //lyxerr << "find called, cmd: " << ev << endl;
629 docstring search = string2find(ev.argument(), casesensitive,
630 matchword, forward, wrap, instant, onlysel);
632 return findOne(bv, search, casesensitive, matchword, forward,
633 false, true, wrap, instant, onlysel);
637 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
639 if (!bv || ev.action() != LFUN_WORD_REPLACE)
642 // data is of the form
645 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
648 docstring howto = split(ev.argument(), rplc, '\n');
649 howto = split(howto, search, '\n');
651 bool casesensitive = parse_bool(howto);
652 bool matchword = parse_bool(howto);
653 bool all = parse_bool(howto);
654 bool forward = parse_bool(howto, true);
655 bool findnext = parse_bool(howto, true);
656 bool wrap = parse_bool(howto);
657 bool onlysel = parse_bool(howto);
659 if (!bv->cursor().selection())
660 // only selection only makes sense with selection
665 int replace_count = 0;
667 replace_count = replaceAll(bv, search, rplc, casesensitive,
669 update = replace_count > 0;
672 replaceOne(bv, search, rplc, casesensitive, matchword,
673 forward, findnext, wrap, onlysel);
675 replace_count = rv.second;
678 Buffer const & buf = bv->buffer();
680 // emit message signal.
682 buf.message(_("String not found in selection."));
684 buf.message(_("String not found."));
686 if (replace_count == 0) {
687 buf.message(_("String found."));
688 } else if (replace_count == 1) {
689 buf.message(_("String has been replaced."));
691 docstring const str = onlysel
692 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
693 : bformat(_("%1$d strings have been replaced."), replace_count);
701 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
703 for (; cur; cur.forwardPos())
704 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
708 DocIterator cur_orig(bv->cursor());
709 docstring q = _("End of file reached while searching forward.\n"
710 "Continue searching from the beginning?");
711 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
712 q, 0, 1, _("&Yes"), _("&No"));
713 if (wrap_answer == 0) {
714 bv->cursor().clear();
715 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
716 bv->clearSelection();
717 cur.setCursor(bv->cursor().selectionBegin());
718 if (findNextChange(bv, cur, false))
721 bv->cursor().setCursor(cur_orig);
728 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
730 for (cur.backwardPos(); cur; cur.backwardPos()) {
731 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
736 DocIterator cur_orig(bv->cursor());
737 docstring q = _("Beginning of file reached while searching backward.\n"
738 "Continue searching from the end?");
739 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
740 q, 0, 1, _("&Yes"), _("&No"));
741 if (wrap_answer == 0) {
742 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
743 bv->cursor().backwardPos();
744 bv->clearSelection();
745 cur.setCursor(bv->cursor().selectionBegin());
746 if (findPreviousChange(bv, cur, false))
749 bv->cursor().setCursor(cur_orig);
756 bool selectChange(Cursor & cur, bool forward)
758 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
760 Change ch = cur.paragraph().lookupChange(cur.pos());
762 CursorSlice tip1 = cur.top();
763 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
764 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
765 if (!ch2.isSimilarTo(ch))
768 CursorSlice tip2 = cur.top();
769 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
771 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
772 if (!ch2.isSimilarTo(ch)) {
773 // take a step forward to correctly set the selection
781 cur.bv().mouseSetCursor(cur, false);
783 cur.bv().mouseSetCursor(cur, true);
791 bool findChange(BufferView * bv, bool forward)
794 cur.setCursor(forward ? bv->cursor().selectionEnd()
795 : bv->cursor().selectionBegin());
796 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
797 return selectChange(cur, forward);
802 bool findNextChange(BufferView * bv)
804 return findChange(bv, true);
808 bool findPreviousChange(BufferView * bv)
810 return findChange(bv, false);
817 typedef vector<pair<string, string> > Escapes;
819 static string getRegexSpaceCount(int count)
823 return "\\s{" + std::to_string(count) + "}";
830 string string2regex(string in)
832 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\$\\])" };
833 string tempx = std::regex_replace(in, specialChars, R"(\$&)" );
834 // Special handling for ' '
837 for (unsigned i = 0; i < tempx.size(); i++) {
838 if (tempx[i] == ' ' || tempx[i] == '~' ) {
842 else if (tempx[i] == '\302' && tempx[i+1] == '\240') {
847 else if (tempx[i] == '\342') {
848 if (tempx[i+1] == '\200') {
849 if ((tempx[i+2] == '\257')
850 || (tempx[i+2] == '\203')
851 || (tempx[i+2] == '\202')) {
852 // Non-breaking Thin (1/6 em)
853 // Quad(1 em), (Double quad counts as 2 blanks)
858 else if (tempx[i+2] == '\213') {
859 // Ignoring parts of Medium and Thick
863 else if ((tempx[i+2] == '\204') || (tempx[i+2] == '\205')) {
870 else if (tempx[i+1] == '\201') {
871 if (tempx[i+2] == '\240') {
872 // Ignoring parts of half quad
877 else if ((tempx[i+1] == '\220') && (tempx[i+2] == '\243')) {
885 temp += getRegexSpaceCount(blanks);
892 temp += getRegexSpaceCount(blanks);
899 while (fl_pos < temp.size()) {
900 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
901 if (fl_pos == string::npos)
904 temp2 += temp.substr(lastpos, fl_pos - lastpos);
910 if (lastpos < temp.size()) {
911 temp2 += temp.substr(lastpos, temp.size() - lastpos);
916 static void buildAccentsMap();
918 string correctRegex(string t, bool withformat)
920 /* Convert \backslash => \
921 * and \{, \}, \[, \] => {, }, [, ]
924 static std::regex wordre("(\\\\)*(\\\\(( |[A-Za-z]+|[\\{\\}%])( |\\{\\})?|[\\[\\]\\{\\}]))");
925 static std::regex protectedSpace { R"(~)" };
928 bool backslashed = false;
932 //LYXERR0("correctRegex input '" << t << "'");
934 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
937 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
941 if (sub.str(4) == "backslash") {
942 replace = string("\\");
944 // transforms '\backslash \{' into '\{'
945 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
946 if ((next == "\\{") || (next == "\\}") || (next == "\\ ")) {
950 else if (withformat && next[0] == '$') {
951 replace = accents["lyxdollar"];
952 skip = 1; // Skip following '$'
956 else if (sub.str(4) == "mathcircumflex")
958 else if ((sub.str(4) == "negthinspace") || (sub.str(4) == "negmedspace") || (sub.str(4) == "negthickspace")) {
959 replace = accents[sub.str(4)+"{}"];
961 else if (backslashed) {
964 if (sub.str(3) == "{")
965 replace = accents["braceleft"];
966 else if (sub.str(3) == "}")
967 replace = accents["braceright"];
968 else if (sub.str(3) == " ")
971 // else part should not exist
976 if (sub.str(3) == "{")
978 else if (sub.str(3) == "}")
980 else if (sub.str(3) == " ")
983 // else part should not exist
988 else if (sub.str(4) == "{") // transforms '\{' into '{'
990 else if (sub.str(4) == "}")
992 else if (sub.str(4) == "%")
994 else if (sub.str(4) == " ")
997 AccentsIterator it_ac = accents.find(sub.str(4));
998 if (it_ac == accents.end()) {
999 replace = sub.str(2);
1002 replace = it_ac->second;
1006 if (lastpos < (size_t) sub.position(2))
1007 s += std::regex_replace(t.substr(lastpos, sub.position(2) - lastpos), protectedSpace, R"( )");
1009 lastpos = sub.position(2) + sub.length(2) + skip;
1013 s = std::regex_replace(t, protectedSpace, R"( )");
1014 else if (lastpos < t.length())
1015 s += std::regex_replace(t.substr(lastpos, t.length() - lastpos), protectedSpace, R"( )");
1016 // Handle quotes in regex
1017 // substitute all '„', '“', '»', '«' with '"'
1018 // and all '‚', '‘', '›', '‹' with "\'"
1019 static std::regex plainquotes { R"(„|“|»|«)" };
1020 static std::regex innerquotes { R"(‚|‘|›|‹)" };
1021 t = std::regex_replace(s, plainquotes, R"(")");
1022 s = std::regex_replace(t, innerquotes, R"(')");
1023 //LYXERR0("correctRegex output '" << s << "'");
1027 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
1028 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
1029 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
1030 string escape_for_regex(string s, bool withformat)
1034 while (lastpos < s.size()) {
1035 size_t regex_pos = s.find("\\regexp{", lastpos);
1036 if (regex_pos == string::npos) {
1037 regex_pos = s.size();
1039 if (regex_pos > lastpos) {
1040 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
1041 lastpos = regex_pos;
1042 if (lastpos == s.size())
1045 size_t end_pos = s.find("\\endregexp", regex_pos + 8);
1046 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
1047 lastpos = end_pos + 13;
1053 /// Wrapper for lyx::regex_replace with simpler interface
1054 bool regex_replace(string const & s, string & t, string const & searchstr,
1055 string const & replacestr)
1057 regex e(searchstr, regex_constants::ECMAScript);
1059 ostream_iterator<char, char> it(oss);
1060 regex_replace(it, s.begin(), s.end(), e, replacestr);
1061 // tolerate t and s be references to the same variable
1062 bool rv = (s != oss.str());
1081 vector <string> result = vector <string>();
1082 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {}
1085 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
1087 if (newres.match2end < oldres.match2end)
1088 return MatchResult::newIsTooFar;
1089 if (newres.match_len < oldres.match_len)
1090 return MatchResult::newIsTooFar;
1092 if (newres.match_len == oldres.match_len) {
1093 if (newres.match2end == oldres.match2end)
1094 return MatchResult::newIsBetter;
1096 return MatchResult::newIsInvalid;
1099 /** The class performing a match between a position in the document and the FindAdvOptions.
1102 class MatchStringAdv {
1104 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
1106 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
1107 ** constructor as opt.search, under the opt.* options settings.
1110 ** If set to MatchStringAdv::MatchFromStart,
1111 ** then match is searched only against beginning of text starting at cur.
1112 ** Otherwise the match is searched anywhere in text starting at cur.
1115 ** The length of the matching text, or zero if no match was found.
1121 string matchTypeAsString(matchType const x) const { return (x == MatchFromStart ? "MatchFromStart" : "MatchAnyPlace"); }
1122 MatchResult operator()(DocIterator const & cur, int len, matchType at_begin) const;
1130 lyx::Buffer * p_buf;
1131 /// first buffer on which search was started
1132 lyx::Buffer * const p_first_buf;
1134 FindAndReplaceOptions const & opt;
1137 /// Auxiliary find method (does not account for opt.matchword)
1138 MatchResult findAux(DocIterator const & cur, int len, matchType at_begin) const;
1139 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
1141 /** Normalize a stringified or latexified LyX paragraph.
1145 ** <li>if search is not casesensitive, then lowercase the string;
1146 ** <li>remove any newline at begin or end of the string;
1147 ** <li>replace any newline in the middle of the string with a simple space;
1148 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
1151 ** @todo Normalization should also expand macros, if the corresponding
1152 ** search option was checked.
1154 string convertLF2Space(docstring const & s, bool ignore_fomat) const;
1155 // normalized string to search
1156 string par_as_string;
1157 // regular expression to use for searching
1158 // regexp2 is same as regexp, but prefixed with a ".*?"
1160 QRegularExpression regexp;
1161 QRegularExpression regexp2;
1166 // leading format material as string
1167 string lead_as_string;
1168 // par_as_string after removal of lead_as_string
1169 string par_as_string_nolead;
1170 // unmatched open braces in the search string/regexp
1171 int open_braces = 0;
1172 // number of (.*?) subexpressions added at end of search regexp for closing
1173 // environments, math mode, styles, etc...
1174 int close_wildcards = 0;
1176 // Are we searching with regular expressions ?
1177 bool use_regexp = false;
1178 static int valid_matches;
1179 static vector <string> matches;
1180 void FillResults(MatchResult &found_mr);
1183 int MatchStringAdv::valid_matches = 0;
1184 vector <string> MatchStringAdv::matches = vector <string>(10);
1186 void MatchStringAdv::FillResults(MatchResult &found_mr)
1188 if (found_mr.match_len > 0) {
1189 valid_matches = found_mr.result.size();
1190 for (size_t i = 0; i < found_mr.result.size(); i++)
1191 matches[i] = found_mr.result[i];
1196 static void setFindParams(OutputParams &runparams)
1198 runparams.flavor = Flavor::XeTeX;
1199 //runparams.use_polyglossia = true;
1200 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1201 // No side effect of file copying and image conversion
1202 runparams.dryrun = true;
1205 static docstring buffer_to_latex(Buffer & buffer)
1207 //OutputParams runparams(&buffer.params().encoding());
1208 OutputParams runparams(encodings.fromLyXName("utf8"));
1209 odocstringstream ods;
1211 runparams.nice = true;
1212 setFindParams(runparams);
1213 if (ignoreFormats.getDeleted())
1214 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1216 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1217 if (ignoreFormats.getNonContent()) {
1218 runparams.find_add_feature(OutputParams::SearchNonOutput);
1220 pit_type const endpit = buffer.paragraphs().size();
1221 for (pit_type pit = 0; pit != endpit; ++pit) {
1222 TeXOnePar(buffer, buffer.text(), pit, os, runparams, string(), -1, -1, true);
1223 LYXERR(Debug::FINDVERBOSE, "searchString up to here: " << ods.str());
1228 static string latexNamesToUtf8(docstring strIn, bool withformat)
1230 string addtmp = to_utf8(strIn);
1231 static regex const rmAcc("(\\\\)*("
1232 "\\\\([A-Za-z]+\\{.\\})" // e.g. "ddot{A}" == sub.str(3)
1233 "|\\\\([A-Za-z]+)( |\\{\\})?" // e.g. "LyX", "LyX{}", "LyX " == sub.str(4)
1240 if (accents.empty())
1242 for (sregex_iterator it_add(addtmp.begin(), addtmp.end(), rmAcc), end; it_add != end; ++it_add) {
1244 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
1249 if (sub.length(3) > 0)
1253 AccentsIterator it_ac = accents.find(key);
1254 if (it_ac == accents.end()) {
1255 replace = sub.str(2);
1258 replace = it_ac->second;
1261 if (lastpos < (size_t) sub.position(2))
1262 add += addtmp.substr(lastpos, sub.position(2) - lastpos);
1264 lastpos = sub.position(2) + sub.length(2);
1268 else if (addtmp.length() > lastpos)
1269 add += addtmp.substr(lastpos, addtmp.length() - lastpos);
1271 static std::regex repltilde { R"(~)" };
1272 add = std::regex_replace(add, repltilde, accents["lyxtilde"]);
1274 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1279 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1282 if (!opt.ignoreformat) {
1283 str = buffer_to_latex(buffer);
1285 // OutputParams runparams(&buffer.params().encoding());
1286 OutputParams runparams(encodings.fromLyXName("utf8"));
1287 runparams.nice = true;
1288 setFindParams(runparams);
1289 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1290 if (ignoreFormats.getDeleted()) {
1291 option |= AS_STR_SKIPDELETE;
1292 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1295 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1297 if (ignoreFormats.getNonContent()) {
1298 runparams.find_add_feature(OutputParams::SearchNonOutput);
1301 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1302 Paragraph const & par = buffer.paragraphs().at(pit);
1303 string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1305 &runparams), !opt.ignoreformat);
1306 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1310 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1311 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1312 // remove trailing space, it may have been added by plaintext() in InsetMathHull.cpp
1313 size_t t_size = t.size();
1314 if (opt.ignoreformat && (t_size > 1) && (t[t_size-1] == ' '))
1315 str = from_utf8(t.substr(0, t_size-1));
1323 /// Return separation pos between the leading material and the rest
1324 static size_t identifyLeading(string const & s)
1327 // @TODO Support \item[text]
1328 // Kornel: Added textsl, textsf, textit, texttt and noun
1329 // + allow to search for colored text too
1330 while (regex_replace(t, t, "^\\\\(("
1331 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1332 "lyxaddress|lyxrightaddress|"
1333 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1334 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1335 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1336 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1337 || regex_replace(t, t, "^\\$", "")
1338 || regex_replace(t, t, "^\\\\\\[", "")
1339 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1340 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1342 LYXERR(Debug::FINDVERBOSE, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1343 return s.size() - t.size();
1347 * Given a latexified string, retrieve some handled features
1348 * The features of the regex will later be compared with the features
1349 * of the searched text. If the regex features are not a
1350 * subset of the analized, then, in not format ignoring search
1351 * we can early stop the search in the relevant inset.
1353 typedef map<string, bool> Features;
1355 static Features identifyFeatures(string const & s)
1357 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1358 static regex const valid("^("
1360 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1361 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1362 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1363 "(u|uu)line|(s|x)out|uwave|"
1364 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1365 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1370 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1373 if (sub.str(1).compare("regexp") == 0) {
1377 string token = sub.str(1);
1379 if (regex_match(token, sub2, valid)) {
1387 if (sub.str(1).compare("endregexp") == 0) {
1397 * defines values features of a key "\\[a-z]+{"
1402 /* Char type with content discarded
1403 * like \hspace{1cm} */
1405 /* Char, like \backslash */
1407 /* replace starting backslash with '#' */
1409 /* \part, \section*, ... */
1411 /* title, author etc */
1413 /* \foreignlanguage{ngerman}, ... */
1416 * to discard language in content */
1419 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1421 /* fonts, colors, markups, ... */
1423 /* footnotesize, ... large, ...
1424 * Ignore all of them */
1427 /* inputencoding, ...
1428 * Discard also content, because they do not help in search */
1431 * like remove, but also all arguments */
1433 /* item, listitem */
1435 /* tex, latex, ... like isChar */
1437 /* like \lettrine[lines=5]{}{} */
1439 // like isStandard, but always remove head
1441 /* End of arguments marker for lettrine,
1442 * so that they can be ignored */
1445 KeyInfo() = default;
1446 KeyInfo(KeyType type, int parcount, bool disable)
1448 parenthesiscount(parcount),
1449 disabled(disable) {}
1450 KeyType keytype = invalid;
1452 int _tokensize = -1;
1453 int _tokenstart = -1;
1454 int _dataStart = -1;
1456 int parenthesiscount = 1;
1457 bool disabled = false;
1458 bool used = false; /* by pattern */
1463 Border(int l=0, int u=0) : low(l), upper(u) {}
1468 #define MAXOPENED 30
1470 bool isPatternString_;
1472 explicit Intervall(bool isPattern, string const & p)
1473 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1474 actualdeptindex(0), hasTitle(false), langcount(0)
1482 static vector<Border> borders;
1483 static vector<int> depts;
1484 static vector<int> closes;
1485 int actualdeptindex;
1486 int previousNotIgnored(int) const;
1487 int nextNotIgnored(int) const;
1488 void handleOpenP(int i);
1489 void handleCloseP(int i, bool closingAllowed);
1490 void resetOpenedP(int openPos);
1491 void addIntervall(int upper);
1492 void addIntervall(int low, int upper); /* if explicit */
1493 void removeAccents();
1494 void setForDefaultLang(KeyInfo const & defLang) const;
1495 int findclosing(int start, int end, char up, char down, int repeat);
1496 void removeInvalidClosings(void);
1497 void handleParentheses(int lastpos, bool closingAllowed);
1499 // Number of disabled language specs up
1500 // to current position in actual interval
1502 int isOpeningPar(int pos) const;
1504 void output(ostringstream &os, int lastpos);
1505 // string show(int lastpos);
1508 vector<Border> Intervall::borders = vector<Border>(30);
1509 vector<int> Intervall::depts = vector<int>(30);
1510 vector<int> Intervall::closes = vector<int>(30);
1512 int Intervall::isOpeningPar(int pos) const
1514 if ((pos < 0) || (size_t(pos) >= par.size()))
1516 if (par[pos] != '{')
1518 if (size_t(pos) + 2 >= par.size())
1520 if (par[pos+2] != '}')
1522 if (par[pos+1] == '[' || par[pos+1] == ']')
1527 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1529 // Enable the use of first token again
1530 if (ignoreidx >= 0) {
1531 int value = defLang._tokenstart + defLang._tokensize;
1536 if (borders[borderidx].low < value)
1537 borders[borderidx].low = value;
1538 if (borders[borderidx].upper < value)
1539 borders[borderidx].upper = value;
1545 // Not needed, because dpts and closes are now dynamically expanded
1546 static void checkDepthIndex(int val)
1548 static int maxdepthidx = MAXOPENED-2;
1549 static int lastmaxdepth = 0;
1550 if (val > lastmaxdepth) {
1551 LYXERR(Debug::INFO, "Depth reached " << val);
1554 if (val > maxdepthidx) {
1556 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1562 // Not needed, because borders are now dynamically expanded
1563 static void checkIgnoreIdx(int val)
1565 static int lastmaxignore = -1;
1566 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1567 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1568 lastmaxignore = val;
1574 * Expand the region of ignored parts of the input latex string
1575 * The region is only relevant in output()
1577 void Intervall::addIntervall(int low, int upper)
1580 if (low == upper) return;
1581 for (idx = ignoreidx+1; idx > 0; --idx) {
1582 if (low > borders[idx-1].upper) {
1586 Border br(low, upper);
1587 if (idx > ignoreidx) {
1588 if (borders.size() <= size_t(idx)) {
1589 borders.push_back(br);
1595 // checkIgnoreIdx(ignoreidx);
1599 // Expand only if one of the new bound is inside the interwall
1600 // We know here that br.low > borders[idx-1].upper
1601 if (br.upper < borders[idx].low) {
1602 // We have to insert at this pos
1603 if (size_t(ignoreidx+1) >= borders.size()) {
1604 borders.push_back(borders[ignoreidx]);
1607 borders[ignoreidx+1] = borders[ignoreidx];
1609 for (int i = ignoreidx; i > idx; --i) {
1610 borders[i] = borders[i-1];
1614 // checkIgnoreIdx(ignoreidx);
1617 // Here we know, that we are overlapping
1618 if (br.low > borders[idx].low)
1619 br.low = borders[idx].low;
1620 // check what has to be concatenated
1622 for (int i = idx; i <= ignoreidx; i++) {
1623 if (br.upper >= borders[i].low) {
1625 if (br.upper < borders[i].upper)
1626 br.upper = borders[i].upper;
1632 // count should be >= 1 here
1635 for (int i = idx + count; i <= ignoreidx; i++) {
1636 borders[i-count+1] = borders[i];
1638 ignoreidx -= count - 1;
1644 static void buildaccent(string n, string param, string values)
1648 const char delim = '|';
1649 while (getline(s, name, delim)) {
1651 for (char c : param) {
1652 string key = name + "{" + c + "}";
1653 // get the corresponding utf8-value
1654 if ((values[start] & 0xc0) != 0xc0) {
1655 // should not happen, utf8 encoding starts at least with 11xxxxxx
1656 // but value for '\dot{i}' is 'i', which is ascii
1657 if ((values[start] & 0x80) == 0) {
1659 accents[key] = values.substr(start, 1);
1660 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1665 for (int j = 1; ;j++) {
1666 if (start + j >= values.size()) {
1667 accents[key] = values.substr(start, j);
1668 start = values.size() - 1;
1671 else if ((values[start+j] & 0xc0) != 0x80) {
1672 // This is the first byte of following utf8 char
1673 accents[key] = values.substr(start, j);
1675 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1684 static string getutf8(unsigned uchar)
1687 string ret = string();
1689 if (uchar <= 0x7f) {
1690 c[maxc-1] = uchar & 0x7f;
1693 unsigned char rest = 0x40;
1694 unsigned char first = 0x80;
1696 for (int i = start; i >=0; --i) {
1698 c[i] = first + uchar;
1701 c[i] = 0x80 | (uchar & 0x3f);
1708 for (int i = 0; i < maxc; i++) {
1709 if (c[i] == 0) continue;
1715 static void addAccents(string latex_in, string unicode_out)
1717 latex_in = latex_in.substr(1);
1718 AccentsIterator it_ac = accents.find(latex_in);
1719 if (it_ac == accents.end()) {
1720 accents[latex_in] = unicode_out;
1723 LYXERR0("Key " << latex_in << " already set");
1727 void static fillMissingUnicodesymbols()
1729 addAccents("\\pounds", getutf8(0x00a3));
1730 addAccents("\\textsterling", getutf8(0x00a3));
1731 addAccents("\\textyen", getutf8(0x00a5));
1732 addAccents("\\yen", getutf8(0x00a5));
1733 addAccents("\\textsection", getutf8(0x00a7));
1734 addAccents("\\mathsection", getutf8(0x00a7));
1735 addAccents("\\textcopyright", getutf8(0x00a9));
1736 addAccents("\\copyright", getutf8(0x00a9));
1737 addAccents("\\textlnot", getutf8(0x00ac));
1738 addAccents("\\neg", getutf8(0x00ac));
1739 addAccents("\\textregistered", getutf8(0x00ae));
1740 addAccents("\\circledR", getutf8(0x00ae));
1741 addAccents("\\textpm", getutf8(0x00b1));
1742 addAccents("\\pm", getutf8(0x00b1));
1743 addAccents("\\textparagraph", getutf8(0x00b6));
1744 addAccents("\\mathparagraph", getutf8(0x00b6));
1745 addAccents("\\textperiodcentered", getutf8(0x00b7));
1746 addAccents("\\texttimes", getutf8(0x00d7));
1747 addAccents("\\times", getutf8(0x00d7));
1748 addAccents("\\O", getutf8(0x00d8));
1749 addAccents("\\dh", getutf8(0x00f0));
1750 addAccents("\\eth", getutf8(0x00f0));
1751 addAccents("\\textdiv", getutf8(0x00f7));
1752 addAccents("\\div", getutf8(0x00f7));
1753 addAccents("\\o", getutf8(0x00f8));
1754 addAccents("\\textcrlambda", getutf8(0x019b));
1755 addAccents("\\j", getutf8(0x0237));
1756 addAccents("\\textrevepsilon", getutf8(0x025c));
1757 addAccents("\\textbaru", getutf8(0x0289));
1758 addAccents("\\textquoteleft", getutf8(0x02bb));
1759 addAccents("\\textGamma", getutf8(0x0393));
1760 addAccents("\\Gamma", getutf8(0x0393));
1761 addAccents("\\textDelta", getutf8(0x0394));
1762 addAccents("\\Delta", getutf8(0x0394));
1763 addAccents("\\textTheta", getutf8(0x0398));
1764 addAccents("\\Theta", getutf8(0x0398));
1765 addAccents("\\textLambda", getutf8(0x039b));
1766 addAccents("\\Lambda", getutf8(0x039b));
1767 addAccents("\\textXi", getutf8(0x039e));
1768 addAccents("\\Xi", getutf8(0x039e));
1769 addAccents("\\textPi", getutf8(0x03a0));
1770 addAccents("\\Pi", getutf8(0x03a0));
1771 addAccents("\\textSigma", getutf8(0x03a3));
1772 addAccents("\\Sigma", getutf8(0x03a3));
1773 addAccents("\\textUpsilon", getutf8(0x03a5));
1774 addAccents("\\Upsilon", getutf8(0x03a5));
1775 addAccents("\\textPhi", getutf8(0x03a6));
1776 addAccents("\\Phi", getutf8(0x03a6));
1777 addAccents("\\textPsi", getutf8(0x03a8));
1778 addAccents("\\Psi", getutf8(0x03a8));
1779 addAccents("\\textOmega", getutf8(0x03a9));
1780 addAccents("\\Omega", getutf8(0x03a9));
1781 addAccents("\\textalpha", getutf8(0x03b1));
1782 addAccents("\\alpha", getutf8(0x03b1));
1783 addAccents("\\textbeta", getutf8(0x03b2));
1784 addAccents("\\beta", getutf8(0x03b2));
1785 addAccents("\\textgamma", getutf8(0x03b3));
1786 addAccents("\\gamma", getutf8(0x03b3));
1787 addAccents("\\textdelta", getutf8(0x03b4));
1788 addAccents("\\delta", getutf8(0x03b4));
1789 addAccents("\\textepsilon", getutf8(0x03b5));
1790 addAccents("\\varepsilon", getutf8(0x03b5));
1791 addAccents("\\textzeta", getutf8(0x03b6));
1792 addAccents("\\zeta", getutf8(0x03b6));
1793 addAccents("\\texteta", getutf8(0x03b7));
1794 addAccents("\\eta", getutf8(0x03b7));
1795 addAccents("\\texttheta", getutf8(0x03b8));
1796 addAccents("\\theta", getutf8(0x03b8));
1797 addAccents("\\textiota", getutf8(0x03b9));
1798 addAccents("\\iota", getutf8(0x03b9));
1799 addAccents("\\textkappa", getutf8(0x03ba));
1800 addAccents("\\kappa", getutf8(0x03ba));
1801 addAccents("\\textlambda", getutf8(0x03bb));
1802 addAccents("\\lambda", getutf8(0x03bb));
1803 addAccents("\\textmu", getutf8(0x03bc));
1804 addAccents("\\mu", getutf8(0x03bc));
1805 addAccents("\\textnu", getutf8(0x03bd));
1806 addAccents("\\nu", getutf8(0x03bd));
1807 addAccents("\\textxi", getutf8(0x03be));
1808 addAccents("\\xi", getutf8(0x03be));
1809 addAccents("\\textpi", getutf8(0x03c0));
1810 addAccents("\\pi", getutf8(0x03c0));
1811 addAccents("\\textrho", getutf8(0x03c1));
1812 addAccents("\\rho", getutf8(0x03c1));
1813 addAccents("\\textfinalsigma", getutf8(0x03c2));
1814 addAccents("\\varsigma", getutf8(0x03c2));
1815 addAccents("\\textsigma", getutf8(0x03c3));
1816 addAccents("\\sigma", getutf8(0x03c3));
1817 addAccents("\\texttau", getutf8(0x03c4));
1818 addAccents("\\tau", getutf8(0x03c4));
1819 addAccents("\\textupsilon", getutf8(0x03c5));
1820 addAccents("\\upsilon", getutf8(0x03c5));
1821 addAccents("\\textphi", getutf8(0x03c6));
1822 addAccents("\\varphi", getutf8(0x03c6));
1823 addAccents("\\textchi", getutf8(0x03c7));
1824 addAccents("\\chi", getutf8(0x03c7));
1825 addAccents("\\textpsi", getutf8(0x03c8));
1826 addAccents("\\psi", getutf8(0x03c8));
1827 addAccents("\\textomega", getutf8(0x03c9));
1828 addAccents("\\omega", getutf8(0x03c9));
1829 addAccents("\\textdigamma", getutf8(0x03dd));
1830 addAccents("\\digamma", getutf8(0x03dd));
1831 addAccents("\\hebalef", getutf8(0x05d0));
1832 addAccents("\\aleph", getutf8(0x05d0));
1833 addAccents("\\hebbet", getutf8(0x05d1));
1834 addAccents("\\beth", getutf8(0x05d1));
1835 addAccents("\\hebgimel", getutf8(0x05d2));
1836 addAccents("\\gimel", getutf8(0x05d2));
1837 addAccents("\\hebdalet", getutf8(0x05d3));
1838 addAccents("\\daleth", getutf8(0x05d3));
1839 addAccents("\\hebhe", getutf8(0x05d4));
1840 addAccents("\\hebvav", getutf8(0x05d5));
1841 addAccents("\\hebzayin", getutf8(0x05d6));
1842 addAccents("\\hebhet", getutf8(0x05d7));
1843 addAccents("\\hebtet", getutf8(0x05d8));
1844 addAccents("\\hebyod", getutf8(0x05d9));
1845 addAccents("\\hebfinalkaf", getutf8(0x05da));
1846 addAccents("\\hebkaf", getutf8(0x05db));
1847 addAccents("\\heblamed", getutf8(0x05dc));
1848 addAccents("\\hebfinalmem", getutf8(0x05dd));
1849 addAccents("\\hebmem", getutf8(0x05de));
1850 addAccents("\\hebfinalnun", getutf8(0x05df));
1851 addAccents("\\hebnun", getutf8(0x05e0));
1852 addAccents("\\hebsamekh", getutf8(0x05e1));
1853 addAccents("\\hebayin", getutf8(0x05e2));
1854 addAccents("\\hebfinalpe", getutf8(0x05e3));
1855 addAccents("\\hebpe", getutf8(0x05e4));
1856 addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1857 addAccents("\\hebtsadi", getutf8(0x05e6));
1858 addAccents("\\hebqof", getutf8(0x05e7));
1859 addAccents("\\hebresh", getutf8(0x05e8));
1860 addAccents("\\hebshin", getutf8(0x05e9));
1861 addAccents("\\hebtav", getutf8(0x05ea));
1864 addAccents("\\thaiKoKai", getutf8(0x0e01));
1865 addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1866 addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1867 addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1868 addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1869 addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1870 addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1871 addAccents("\\thaiChoChan", getutf8(0x0e08));
1872 addAccents("\\thaiChoChing", getutf8(0x0e09));
1873 addAccents("\\thaiChoChang", getutf8(0x0e0a));
1874 addAccents("\\thaiSoSo", getutf8(0x0e0b));
1875 addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1876 addAccents("\\thaiYoYing", getutf8(0x0e0d));
1877 addAccents("\\thaiDoChada", getutf8(0x0e0e));
1878 addAccents("\\thaiToPatak", getutf8(0x0e0f));
1879 addAccents("\\thaiThoThan", getutf8(0x0e10));
1880 addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1881 addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1882 addAccents("\\thaiNoNen", getutf8(0x0e13));
1883 addAccents("\\thaiDoDek", getutf8(0x0e14));
1884 addAccents("\\thaiToTao", getutf8(0x0e15));
1885 addAccents("\\thaiThoThung", getutf8(0x0e16));
1886 addAccents("\\thaiThoThahan", getutf8(0x0e17));
1887 addAccents("\\thaiThoThong", getutf8(0x0e18));
1888 addAccents("\\thaiNoNu", getutf8(0x0e19));
1889 addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1890 addAccents("\\thaiPoPla", getutf8(0x0e1b));
1891 addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1892 addAccents("\\thaiFoFa", getutf8(0x0e1d));
1893 addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1894 addAccents("\\thaiFoFan", getutf8(0x0e1f));
1895 addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1896 addAccents("\\thaiMoMa", getutf8(0x0e21));
1897 addAccents("\\thaiYoYak", getutf8(0x0e22));
1898 addAccents("\\thaiRoRua", getutf8(0x0e23));
1899 addAccents("\\thaiRu", getutf8(0x0e24));
1900 addAccents("\\thaiLoLing", getutf8(0x0e25));
1901 addAccents("\\thaiLu", getutf8(0x0e26));
1902 addAccents("\\thaiWoWaen", getutf8(0x0e27));
1903 addAccents("\\thaiSoSala", getutf8(0x0e28));
1904 addAccents("\\thaiSoRusi", getutf8(0x0e29));
1905 addAccents("\\thaiSoSua", getutf8(0x0e2a));
1906 addAccents("\\thaiHoHip", getutf8(0x0e2b));
1907 addAccents("\\thaiLoChula", getutf8(0x0e2c));
1908 addAccents("\\thaiOAng", getutf8(0x0e2d));
1909 addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1910 addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1911 addAccents("\\thaiSaraA", getutf8(0x0e30));
1912 addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1913 addAccents("\\thaiSaraAa", getutf8(0x0e32));
1914 addAccents("\\thaiSaraAm", getutf8(0x0e33));
1915 addAccents("\\thaiSaraI", getutf8(0x0e34));
1916 addAccents("\\thaiSaraIi", getutf8(0x0e35));
1917 addAccents("\\thaiSaraUe", getutf8(0x0e36));
1918 addAccents("\\thaiSaraUee", getutf8(0x0e37));
1919 addAccents("\\thaiSaraU", getutf8(0x0e38));
1920 addAccents("\\thaiSaraUu", getutf8(0x0e39));
1921 addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1922 addAccents("\\thaiSaraE", getutf8(0x0e40));
1923 addAccents("\\thaiSaraAe", getutf8(0x0e41));
1924 addAccents("\\thaiSaraO", getutf8(0x0e42));
1925 addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1926 addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1927 addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1928 addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1929 addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1930 addAccents("\\thaiMaiEk", getutf8(0x0e48));
1931 addAccents("\\thaiMaiTho", getutf8(0x0e49));
1932 addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1933 addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1934 addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1935 addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1936 addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1937 addAccents("\\thaiFongman", getutf8(0x0e4f));
1938 addAccents("\\thaizero", getutf8(0x0e50));
1939 addAccents("\\thaione", getutf8(0x0e51));
1940 addAccents("\\thaitwo", getutf8(0x0e52));
1941 addAccents("\\thaithree", getutf8(0x0e53));
1942 addAccents("\\thaifour", getutf8(0x0e54));
1943 addAccents("\\thaifive", getutf8(0x0e55));
1944 addAccents("\\thaisix", getutf8(0x0e56));
1945 addAccents("\\thaiseven", getutf8(0x0e57));
1946 addAccents("\\thaieight", getutf8(0x0e58));
1947 addAccents("\\thainine", getutf8(0x0e59));
1948 addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1949 addAccents("\\thaiKhomut", getutf8(0x0e5b));
1950 addAccents("\\dag", getutf8(0x2020));
1951 addAccents("\\dagger", getutf8(0x2020));
1952 addAccents("\\textdagger", getutf8(0x2020));
1953 addAccents("\\ddag", getutf8(0x2021));
1954 addAccents("\\ddagger", getutf8(0x2021));
1955 addAccents("\\textdaggerdbl", getutf8(0x2021));
1956 addAccents("\\textbullet", getutf8(0x2022));
1957 addAccents("\\bullet", getutf8(0x2022));
1958 addAccents("\\dots", getutf8(0x2026));
1959 addAccents("\\ldots", getutf8(0x2026));
1960 addAccents("\\textellipsis", getutf8(0x2026));
1961 addAccents("\\textasciiacute", getutf8(0x2032));
1962 addAccents("\\prime", getutf8(0x2032));
1963 addAccents("\\textacutedbl", getutf8(0x2033));
1964 addAccents("\\dprime", getutf8(0x2033));
1965 addAccents("\\textasciigrave", getutf8(0x2035));
1966 addAccents("\\backprime", getutf8(0x2035));
1967 addAccents("\\textsubcircum{ }", getutf8(0x2038));
1968 addAccents("\\caretinsert", getutf8(0x2038));
1969 addAccents("\\textasteriskcentered", getutf8(0x204e));
1970 addAccents("\\ast", getutf8(0x204e));
1971 addAccents("\\textmho", getutf8(0x2127));
1972 addAccents("\\mho", getutf8(0x2127));
1973 addAccents("\\textleftarrow", getutf8(0x2190));
1974 addAccents("\\leftarrow", getutf8(0x2190));
1975 addAccents("\\textuparrow", getutf8(0x2191));
1976 addAccents("\\uparrow", getutf8(0x2191));
1977 addAccents("\\textrightarrow", getutf8(0x2192));
1978 addAccents("\\rightarrow", getutf8(0x2192));
1979 addAccents("\\textdownarrow", getutf8(0x2193));
1980 addAccents("\\downarrow", getutf8(0x2193));
1981 addAccents("\\textglobrise", getutf8(0x2197));
1982 addAccents("\\nearrow", getutf8(0x2197));
1983 addAccents("\\textglobfall", getutf8(0x2198));
1984 addAccents("\\searrow", getutf8(0x2198));
1985 addAccents("\\textsurd", getutf8(0x221a));
1986 addAccents("\\surd", getutf8(0x221a));
1987 addAccents("\\textbigcircle", getutf8(0x25ef));
1988 addAccents("\\bigcirc", getutf8(0x25ef));
1989 addAccents("\\FiveStar", getutf8(0x2605));
1990 addAccents("\\bigstar", getutf8(0x2605));
1991 addAccents("\\FiveStarOpen", getutf8(0x2606));
1992 addAccents("\\bigwhitestar", getutf8(0x2606));
1993 addAccents("\\Checkmark", getutf8(0x2713));
1994 addAccents("\\checkmark", getutf8(0x2713));
1995 addAccents("\\CrossMaltese", getutf8(0x2720));
1996 addAccents("\\maltese", getutf8(0x2720));
1997 addAccents("\\textlangle", getutf8(0x27e8));
1998 addAccents("\\langle", getutf8(0x27e8));
1999 addAccents("\\textrangle", getutf8(0x27e9));
2000 addAccents("\\rangle", getutf8(0x27e9));
2003 static void buildAccentsMap()
2005 accents["imath"] = "ı";
2007 accents["jmath"] = "ȷ";
2008 accents["cdot"] = "·";
2009 accents["textasciicircum"] = "^";
2010 accents["mathcircumflex"] = "^";
2011 accents["guillemotright"] = "»";
2012 accents["guillemotleft"] = "«";
2013 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
2014 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
2015 accents["negthinspace{}"]= getutf8(0xf0003); // to omit backslashed latex macros
2016 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
2017 accents["negmedspace{}"] = getutf8(0xf0005);
2018 accents["thickspace"] = getutf8(0xf0006);
2019 accents["negthickspace{}"]= getutf8(0xf0007);
2020 accents["lyx"] = getutf8(0xf0010); // Used logos
2021 accents["LyX"] = getutf8(0xf0010);
2022 accents["tex"] = getutf8(0xf0011);
2023 accents["TeX"] = getutf8(0xf0011);
2024 accents["latex"] = getutf8(0xf0012);
2025 accents["LaTeX"] = getutf8(0xf0012);
2026 accents["latexe"] = getutf8(0xf0013);
2027 accents["LaTeXe"] = getutf8(0xf0013);
2028 accents["lyxarrow"] = getutf8(0xf0020);
2029 accents["braceleft"] = getutf8(0xf0030);
2030 accents["braceright"] = getutf8(0xf0031);
2031 accents["lyxtilde"] = getutf8(0xf0032);
2032 accents["sim"] = getutf8(0xf0032);
2033 accents["lyxdollar"] = getutf8(0xf0033);
2034 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
2035 accents["backslash LyX"] = getutf8(0xf0010);
2036 accents["backslash tex"] = getutf8(0xf0011);
2037 accents["backslash TeX"] = getutf8(0xf0011);
2038 accents["backslash latex"] = getutf8(0xf0012);
2039 accents["backslash LaTeX"] = getutf8(0xf0012);
2040 accents["backslash latexe"] = getutf8(0xf0013);
2041 accents["backslash LaTeXe"] = getutf8(0xf0013);
2042 accents["backslash lyxarrow"] = getutf8(0xf0020);
2043 accents["ddot{\\imath}"] = "ï";
2044 buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
2045 "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ"); // umlaut
2046 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
2047 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
2048 accents["acute{\\imath}"] = "í";
2049 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2050 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2051 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
2052 buildaccent("mathring|r", "aAuUwy",
2054 accents["check{\\imath}"] = "ǐ";
2055 accents["check{\\jmath}"] = "ǰ";
2056 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2057 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
2058 accents["hat{\\imath}"] = "î";
2059 accents["hat{\\jmath}"] = "ĵ";
2060 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2061 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
2062 accents["bar{\\imath}"] = "ī";
2063 buildaccent("bar|=", "aAeEiIoOuUyY",
2064 "āĀēĒīĪōŌūŪȳȲ"); // macron
2065 accents["tilde{\\imath}"] = "ĩ";
2066 buildaccent("tilde", "aAeEiInNoOuUvVyY",
2067 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
2068 accents["breve{\\imath}"] = "ĭ";
2069 buildaccent("breve|u", "aAeEgGiIoOuU",
2070 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
2071 accents["grave{\\imath}"] = "ì";
2072 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2073 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
2074 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2075 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
2076 buildaccent("ogonek|k", "AaEeIiUuOo",
2077 "ĄąĘęĮįŲųǪǫ"); // ogonek
2078 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2079 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
2080 buildaccent("subring|textsubring", "Aa",
2082 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2083 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
2084 buildaccent("subtilde|textsubtilde", "EeIiUu",
2085 "ḚḛḬḭṴṵ"); // subtilde
2086 accents["dgrave{\\imath}"] = "ȉ";
2087 accents["textdoublegrave{\\i}"] = "ȉ";
2088 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2089 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2090 accents["rcap{\\imath}"] = "ȋ";
2091 accents["textroundcap{\\i}"] = "ȋ";
2092 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2093 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2094 buildaccent("slashed", "oO",
2096 fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2097 // LYXERR0("Number of accents " << accents.size());
2101 * Created accents in math or regexp environment
2102 * are macros, but we need the utf8 equivalent
2104 void Intervall::removeAccents()
2106 if (accents.empty())
2108 static regex const accre("\\\\("
2109 "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]*\\}"
2110 "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2112 "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2117 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2119 string key = sub.str(1);
2120 AccentsIterator it_ac = accents.find(key);
2121 if (it_ac != accents.end()) {
2122 string val = it_ac->second;
2123 size_t pos = sub.position(size_t(0));
2124 for (size_t i = 0; i < val.size(); i++) {
2125 par[pos+i] = val[i];
2127 // Remove possibly following space too
2128 if (par[pos+sub.str(0).size()] == ' ')
2129 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2131 addIntervall(pos+val.size(), pos + sub.str(0).size());
2132 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2133 // remove traces of any remaining chars
2138 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2143 void Intervall::handleOpenP(int i)
2146 if ((size_t) actualdeptindex >= depts.size()) {
2147 depts.resize(actualdeptindex + 30);
2148 closes.resize(actualdeptindex + 30);
2150 depts[actualdeptindex] = i+1;
2151 closes[actualdeptindex] = -1;
2152 // checkDepthIndex(actualdeptindex);
2155 void Intervall::handleCloseP(int i, bool closingAllowed)
2157 if (actualdeptindex <= 0) {
2158 if (! closingAllowed)
2159 LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
2160 // if we are at the very end
2161 addIntervall(i, i+1);
2164 closes[actualdeptindex] = i+1;
2169 void Intervall::resetOpenedP(int openPos)
2171 // Used as initializer for foreignlanguage entry
2172 actualdeptindex = 1;
2173 depts[1] = openPos+1;
2177 int Intervall::previousNotIgnored(int start) const
2179 int idx = 0; /* int intervalls */
2180 for (idx = ignoreidx; idx >= 0; --idx) {
2181 if (start > borders[idx].upper)
2183 if (start >= borders[idx].low)
2184 start = borders[idx].low-1;
2189 int Intervall::nextNotIgnored(int start) const
2191 int idx = 0; /* int intervalls */
2192 for (idx = 0; idx <= ignoreidx; idx++) {
2193 if (start < borders[idx].low)
2195 if (start < borders[idx].upper)
2196 start = borders[idx].upper;
2201 typedef unordered_map<string, KeyInfo> KeysMap;
2202 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2203 typedef vector< KeyInfo> Entries;
2204 static KeysMap keys = unordered_map<string, KeyInfo>();
2210 Intervall interval_;
2211 void buildKeys(bool);
2212 void buildEntries(bool);
2213 void makeKey(const string &, KeyInfo, bool isPatternString);
2214 void processRegion(int start, int region_end); /* remove {} parts */
2215 void removeHead(KeyInfo const &, int count=0);
2218 LatexInfo(string const & par, bool isPatternString)
2219 : entidx_(-1), interval_(isPatternString, par)
2221 buildKeys(isPatternString);
2222 entries_ = vector<KeyInfo>();
2223 buildEntries(isPatternString);
2227 if (entries_.empty()) {
2230 if (entries_[0].keytype == KeyInfo::isTitle) {
2231 interval_.hasTitle = true;
2232 if (! entries_[0].disabled) {
2233 interval_.titleValue = entries_[0].head;
2236 interval_.titleValue = "";
2238 removeHead(entries_[0]);
2239 if (entries_.size() > 1)
2248 if (int(entries_.size()) > entidx_) {
2255 bool setNextKey(int idx) {
2256 if ((idx == entidx_) && (entidx_ >= 0)) {
2263 int find(int start, KeyInfo::KeyType keytype) const {
2267 while (tmpIdx < int(entries_.size())) {
2268 if (entries_[tmpIdx].keytype == keytype)
2274 int process(ostringstream & os, KeyInfo const & actual);
2275 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2276 // string show(int lastpos) { return interval.show(lastpos);}
2277 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2278 KeyInfo &getKeyInfo(int keyinfo) {
2279 static KeyInfo invalidInfo = KeyInfo();
2280 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2283 return entries_[keyinfo];
2285 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2286 void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2290 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2294 for (int i = start; i < end; i += 1 + skip) {
2298 if (c == '\\') skip = 1;
2302 else if (c == down) {
2305 if ((repeat <= 0) || (par[i+1] != up))
2314 void Intervall::removeInvalidClosings(void)
2316 // this can happen, if there are deleted parts
2319 for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2322 if (c == '\\') skip = 1;
2325 else if (c == '}') {
2327 addIntervall(i, i+1);
2328 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2340 size_t mathpostfixsize;
2342 size_t mathprefixsize;
2346 vector<MathEntry> entries_;
2351 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2352 MathEntry m = MathEntry();
2354 m.mathStart = start;
2355 m.mathprefixsize = prefixsize;
2356 m.mathEnd = end + postfixsize;
2357 m.mathpostfixsize = postfixsize;
2358 m.mathSize = m.mathEnd - m.mathStart;
2359 entries_.push_back(m);
2361 bool empty() const { return entries_.empty(); }
2362 size_t getEndPos() const {
2363 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2366 return entries_[actualIdx_].mathEnd;
2368 size_t getStartPos() const {
2369 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2370 return 100000; /* definitely enough? */
2372 return entries_[actualIdx_].mathStart;
2374 size_t getPrefixSize() const {
2375 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2378 return entries_[actualIdx_].mathprefixsize;
2380 size_t getPostfixSize() const {
2381 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2384 return entries_[actualIdx_].mathpostfixsize;
2386 size_t getFirstPos() {
2388 return getStartPos();
2390 size_t getSize() const {
2391 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2394 return entries_[actualIdx_].mathSize;
2396 void incrEntry() { actualIdx_++; }
2399 void LatexInfo::buildEntries(bool isPatternString)
2401 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2402 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2403 static bool disableLanguageOverride = false;
2404 smatch sub, submath;
2405 bool evaluatingRegexp = false;
2407 bool evaluatingMath = false;
2408 bool evaluatingCode = false;
2410 bool evaluatingOptional = false;
2411 size_t optionalEnd = 0;
2414 bool math_end_waiting = false;
2415 size_t math_pos = 10000;
2416 size_t math_prefix_size = 1;
2418 static vector<string> usedText = vector<string>();
2419 static bool removeMathHull = false;
2421 interval_.removeAccents();
2422 interval_.removeInvalidClosings();
2424 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2426 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2427 // prefixed by odd count of '\\'
2430 if (math_end_waiting) {
2431 size_t pos = submath.position(size_t(2));
2432 if ((math_end == "$") &&
2433 (submath.str(2) == "$")) {
2434 mi.insert("$", math_pos, 1, pos, 1);
2435 math_end_waiting = false;
2437 else if ((math_end == "\\]") &&
2438 (submath.str(2) == "\\]")) {
2439 mi.insert("\\]", math_pos, 2, pos, 2);
2440 math_end_waiting = false;
2442 else if ((submath.str(3).compare("end") == 0) &&
2443 (submath.str(5).compare(math_end) == 0)) {
2444 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2445 math_end_waiting = false;
2451 if (submath.str(3).compare("begin") == 0) {
2452 math_end_waiting = true;
2453 math_end = submath.str(5);
2454 math_pos = submath.position(size_t(2));
2455 math_prefix_size = submath.str(2).length();
2457 else if (submath.str(2).compare("\\[") == 0) {
2458 math_end_waiting = true;
2460 math_pos = submath.position(size_t(2));
2462 else if (submath.str(2) == "$") {
2463 size_t pos = submath.position(size_t(2));
2464 math_end_waiting = true;
2470 // Ignore language if there is math somewhere in pattern-string
2471 if (isPatternString) {
2472 for (auto const & s: usedText) {
2473 // Remove entries created in previous search runs
2476 usedText = vector<string>();
2479 keys["foreignlanguage"].disabled = true;
2480 disableLanguageOverride = true;
2481 removeMathHull = false;
2484 removeMathHull = true; // used later if not isPatternString
2485 disableLanguageOverride = false;
2489 if (disableLanguageOverride) {
2490 keys["foreignlanguage"].disabled = true;
2493 math_pos = mi.getFirstPos();
2494 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2496 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2497 // prefixed by odd count of '\\'
2500 string key = sub.str(5);
2502 if (sub.str(2)[0] == '\\')
2503 key = sub.str(2)[1];
2508 KeysIterator it_key = keys.find(key);
2509 if (it_key != keys.end()) {
2510 if (it_key->second.keytype == KeyInfo::headRemove) {
2511 KeyInfo found1 = it_key->second;
2512 found1.disabled = true;
2513 found1.head = "\\" + key + "{";
2514 found1._tokenstart = sub.position(size_t(2));
2515 found1._tokensize = found1.head.length();
2516 found1._dataStart = found1._tokenstart + found1.head.length();
2517 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2518 found1._dataEnd = endpos;
2523 if (evaluatingRegexp) {
2524 if (sub.str(3).compare("endregexp") == 0) {
2525 evaluatingRegexp = false;
2526 // found._tokenstart already set
2527 found._dataEnd = sub.position(size_t(2)) + 13;
2528 found._dataStart = found._dataEnd;
2529 found._tokensize = found._dataEnd - found._tokenstart;
2530 found.parenthesiscount = 0;
2531 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2538 if (evaluatingMath) {
2539 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2541 evaluatingMath = false;
2543 math_pos = mi.getStartPos();
2545 if (it_key == keys.end()) {
2546 found = KeyInfo(KeyInfo::isStandard, 0, true);
2547 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2548 found = KeyInfo(KeyInfo::isText, 0, false);
2549 if (isPatternString) {
2550 found.keytype = KeyInfo::isChar;
2551 found.disabled = false;
2555 usedText.push_back(key);
2559 if (key.compare("regexp") == 0) {
2560 evaluatingRegexp = true;
2561 found._tokenstart = sub.position(size_t(2));
2562 found._tokensize = 0;
2566 // Handle the other params of key
2567 if (found.keytype == KeyInfo::isIgnored)
2569 else if (found.keytype == KeyInfo::isMath) {
2570 if (size_t(sub.position(size_t(2))) == math_pos) {
2572 found._tokenstart = sub.position(size_t(2));
2573 found._tokensize = mi.getSize();
2574 found._dataEnd = found._tokenstart + found._tokensize;
2575 found._dataStart = found._dataEnd;
2576 found.parenthesiscount = 0;
2577 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2578 if (removeMathHull) {
2579 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2580 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2583 // Treate all math constructs as simple math
2584 interval_.par[found._tokenstart] = '$';
2585 interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2586 interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2587 interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2589 evaluatingMath = true;
2592 // begin|end of unknown env, discard
2593 // First handle tables
2594 // longtable|tabular
2595 bool discardComment;
2597 found.keytype = KeyInfo::doRemove;
2598 if ((sub.str(7).compare("longtable") == 0) ||
2599 (sub.str(7).compare("tabular") == 0)) {
2600 discardComment = true; /* '%' */
2603 discardComment = false;
2604 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2606 string token = sub.str(7);
2607 if (regex_match(token, sub2, removeArgs)) {
2608 found.keytype = KeyInfo::removeWithArg;
2611 // discard spaces before pos(2)
2612 int pos = sub.position(size_t(2));
2614 for (count = 0; pos - count > 0; count++) {
2615 char c = interval_.par[pos-count-1];
2616 if (discardComment) {
2617 if ((c != ' ') && (c != '%'))
2623 found._tokenstart = pos - count;
2624 if (sub.str(3).compare(0, 5, "begin") == 0) {
2625 size_t pos1 = pos + sub.str(2).length();
2626 if (sub.str(7).compare("cjk") == 0) {
2627 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2628 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2630 found.keytype = KeyInfo::isMain;
2631 found._dataStart = pos1;
2632 found._dataEnd = interval_.par.length();
2633 found.disabled = keys["foreignlanguage"].disabled;
2634 found.used = keys["foreignlanguage"].used;
2635 found._tokensize = pos1 - found._tokenstart;
2636 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2639 // Swallow possible optional params
2640 while (interval_.par[pos1] == '[') {
2641 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2643 // Swallow also the eventual parameter
2644 if (interval_.par[pos1] == '{') {
2645 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2648 found._dataEnd = pos1;
2650 found._dataStart = found._dataEnd;
2651 found._tokensize = count + found._dataEnd - pos;
2652 found.parenthesiscount = 0;
2653 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2654 found.disabled = true;
2658 // Handle "\end{...}"
2659 found._dataStart = pos + sub.str(2).length();
2660 found._dataEnd = found._dataStart;
2661 found._tokensize = count + found._dataEnd - pos;
2662 found.parenthesiscount = 0;
2663 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2664 found.disabled = true;
2668 else if (found.keytype != KeyInfo::isRegex) {
2669 found._tokenstart = sub.position(size_t(2));
2670 if (found.parenthesiscount == 0) {
2671 // Probably to be discarded
2672 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2673 char following = interval_.par[following_pos];
2674 if (following == ' ')
2675 found.head = "\\" + sub.str(5) + " ";
2676 else if (following == '=') {
2677 // like \uldepth=1000pt
2678 found.head = sub.str(2);
2681 found.head = "\\" + key;
2682 found._tokensize = found.head.length();
2683 found._dataEnd = found._tokenstart + found._tokensize;
2684 found._dataStart = found._dataEnd;
2687 int params = found._tokenstart + key.length() + 1;
2688 if (evaluatingOptional) {
2689 if (size_t(found._tokenstart) > optionalEnd) {
2690 evaluatingOptional = false;
2693 found.disabled = true;
2696 int optend = params;
2697 while (interval_.par[optend] == '[') {
2698 // discard optional parameters
2699 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2701 if (optend > params) {
2702 key += interval_.par.substr(params, optend-params);
2703 evaluatingOptional = true;
2704 optionalEnd = optend;
2705 if (found.keytype == KeyInfo::isSectioning) {
2706 // Remove optional values (but still keep in header)
2707 interval_.addIntervall(params, optend);
2710 string token = sub.str(7);
2712 if (interval_.par[optend] != '{') {
2714 found.parenthesiscount = 0;
2715 found.head = "\\" + key;
2718 closings = found.parenthesiscount;
2719 if (found.parenthesiscount == 1) {
2720 found.head = "\\" + key + "{";
2722 else if (found.parenthesiscount > 1) {
2724 found.head = sub.str(2) + "{";
2725 closings = found.parenthesiscount - 1;
2728 found.head = "\\" + key + "{";
2731 found._tokensize = found.head.length();
2732 found._dataStart = found._tokenstart + found.head.length();
2733 if (found.keytype == KeyInfo::doRemove) {
2735 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2736 if (endpar >= interval_.par.length())
2737 found._dataStart = interval_.par.length();
2739 found._dataStart = endpar;
2740 found._tokensize = found._dataStart - found._tokenstart;
2743 found._dataStart = found._tokenstart + found._tokensize;
2747 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2748 found._dataStart += 15;
2752 endpos = found._dataStart - 1;
2754 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2755 if (found.keytype == KeyInfo::isList) {
2756 // Check if it really is list env
2757 static regex const listre("^([a-z]+)$");
2759 if (!regex_match(token, sub2, listre)) {
2760 // Change the key of this entry. It is not in a list/item environment
2761 found.keytype = KeyInfo::endArguments;
2764 if (found.keytype == KeyInfo::noMain) {
2765 evaluatingCode = true;
2767 codeStart = found._dataStart;
2769 else if (evaluatingCode) {
2770 if (size_t(found._dataStart) > codeEnd)
2771 evaluatingCode = false;
2772 else if (found.keytype == KeyInfo::isMain) {
2773 // Disable this key, treate it as standard
2774 found.keytype = KeyInfo::isStandard;
2775 found.disabled = true;
2776 if ((codeEnd +1 >= interval_.par.length()) &&
2777 (found._tokenstart == codeStart)) {
2778 // trickery, because the code inset starts
2779 // with \selectlanguage ...
2781 if (entries_.size() > 1) {
2782 entries_[entries_.size()-1]._dataEnd = codeEnd;
2787 if ((endpos == interval_.par.length()) &&
2788 (found.keytype == KeyInfo::doRemove)) {
2789 // Missing closing => error in latex-input?
2790 // therefore do not delete remaining data
2791 found._dataStart -= 1;
2792 found._dataEnd = found._dataStart;
2795 found._dataEnd = endpos;
2797 if (isPatternString) {
2798 keys[key].used = true;
2801 entries_.push_back(found);
2805 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2807 stringstream s(keysstring);
2809 const char delim = '|';
2810 while (getline(s, key, delim)) {
2811 KeyInfo keyII(keyI);
2812 if (isPatternString) {
2815 else if ( !keys[key].used)
2816 keyII.disabled = true;
2821 void LatexInfo::buildKeys(bool isPatternString)
2824 static bool keysBuilt = false;
2825 if (keysBuilt && !isPatternString) return;
2827 // Keys to ignore in any case
2828 makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2829 makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2830 // Known standard keys with 1 parameter.
2831 // Split is done, if not at start of region
2832 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2833 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2834 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2835 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2836 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2837 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2839 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2840 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2841 makeKey("section*|subsection*|subsubsection*|paragraph*",
2842 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2843 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2844 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2846 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2848 // Split is done, if not at start of region
2849 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2850 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2852 // Split is done always.
2853 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2857 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2858 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2859 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2860 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2862 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2863 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2864 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2865 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2867 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2868 // Custom space/skip, remove the content (== length value)
2869 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2870 // Found in fr/UserGuide.lyx
2871 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2873 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2874 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2875 // Known macros to remove (including their parameter)
2877 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2878 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2879 // handle like standard keys with 1 parameter.
2880 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2882 if (ignoreFormats.getDeleted()) {
2883 // Ignore deleted text
2884 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2887 // but preserve added text
2888 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2890 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2892 // Macros to remove, but let the parameter survive
2894 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2896 // Remove language spec from content of these insets
2897 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2899 // Same effect as previous, parameter will survive (because there is no one anyway)
2901 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2902 // Remove table decorations
2903 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2904 // Discard shape-header.
2905 // For footnote or shortcut too, because of lang settings
2906 // and wrong handling if used 'KeyInfo::noMain'
2907 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2908 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2909 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2910 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2911 makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2912 makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2913 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2914 // like ('tiny{}' or '\tiny ' ... )
2915 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2917 // Survives, like known character
2918 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2919 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2920 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2922 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2923 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2924 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2926 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2927 // Remove RTL/LTR marker
2928 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2929 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2930 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2931 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2932 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2933 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2934 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2935 if (isPatternString) {
2936 // Allow the first searched string to rebuild the keys too
2940 // no need to rebuild again
2946 * Keep the list of actual opened parentheses actual
2947 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2949 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2952 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2956 if (c == '\\') skip = 1;
2957 else if (c == '{') {
2960 else if (c == '}') {
2961 handleCloseP(i, closingAllowed);
2967 string Intervall::show(int lastpos)
2969 int idx = 0; /* int intervalls */
2972 if ((unsigned) lastpos > par.size())
2973 lastpos = par.size();
2974 for (idx = 0; idx <= ignoreidx; idx++) {
2975 while (i < lastpos) {
2977 if (i <= borders[idx].low) {
2978 if (borders[idx].low > lastpos)
2979 printsize = lastpos - i;
2981 printsize = borders[idx].low - i;
2982 s += par.substr(i, printsize);
2984 if (i >= borders[idx].low)
2985 i = borders[idx].upper;
2988 i = borders[idx].upper;
2994 s += par.substr(i, lastpos-i);
3000 void Intervall::output(ostringstream &os, int lastpos)
3002 // get number of chars to output
3003 int idx = 0; /* int intervalls */
3006 string startTitle = titleValue;
3007 for (idx = 0; idx <= ignoreidx; idx++) {
3009 if (i <= borders[idx].low) {
3011 if (borders[idx].low > lastpos)
3012 printsize = lastpos - i;
3014 printsize = borders[idx].low - i;
3015 if (printsize > 0) {
3016 os << startTitle << par.substr(i, printsize);
3018 printed += printsize;
3021 handleParentheses(i, false);
3022 if (i >= borders[idx].low)
3023 i = borders[idx].upper;
3026 i = borders[idx].upper;
3033 os << startTitle << par.substr(i, lastpos-i);
3034 printed += lastpos-i;
3036 handleParentheses(lastpos, false);
3038 if (keys["foreignlanguage"].disabled)
3039 startindex = actualdeptindex-langcount;
3041 startindex = actualdeptindex;
3042 for (int i = startindex; i > 0; --i) {
3045 if (hasTitle && (printed > 0))
3047 if (! isPatternString_)
3049 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3052 void LatexInfo::processRegion(int start, int region_end)
3054 while (start < region_end) { /* Let {[} and {]} survive */
3055 int cnt = interval_.isOpeningPar(start);
3057 // Closing is allowed past the region
3058 int closing = interval_.findclosing(start+1, interval_.par.length());
3059 interval_.addIntervall(start, start+1);
3060 interval_.addIntervall(closing, closing+1);
3064 start = interval_.nextNotIgnored(start+1);
3068 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3070 if (actual.parenthesiscount == 0) {
3071 // "{\tiny{} ...}" ==> "{{} ...}"
3072 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3075 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3076 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3077 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3081 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3084 switch (actual.keytype)
3086 case KeyInfo::isTitle: {
3088 nextKeyIdx = getNextKey();
3091 case KeyInfo::cleanToStart: {
3092 actual._dataEnd = actual._dataStart;
3093 nextKeyIdx = getNextKey();
3094 // Search for end of arguments
3095 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3097 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3098 entries_[i].disabled = true;
3100 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3102 while (interval_.par[actual._dataEnd] == ' ')
3104 interval_.addIntervall(0, actual._dataEnd+1);
3105 interval_.actualdeptindex = 0;
3106 interval_.depts[0] = actual._dataEnd+1;
3107 interval_.closes[0] = -1;
3110 case KeyInfo::isText:
3111 interval_.par[actual._tokenstart] = '#';
3112 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3113 nextKeyIdx = getNextKey();
3115 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
3116 if (actual.disabled)
3117 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3119 interval_.addIntervall(actual._dataStart, actual._dataEnd);
3122 case KeyInfo::isChar: {
3123 nextKeyIdx = getNextKey();
3126 case KeyInfo::isSize: {
3127 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3128 if (actual.parenthesiscount == 0)
3129 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3131 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3133 nextKeyIdx = getNextKey();
3135 // Here _dataStart points to '{', so correct it
3136 actual._dataStart += 1;
3137 actual._tokensize += 1;
3138 actual.parenthesiscount = 1;
3139 if (interval_.par[actual._dataStart] == '}') {
3140 // Determine the end if used like '{\tiny{}...}'
3141 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3142 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3145 // Determine the end if used like '\tiny{...}'
3146 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3148 // Split on this key if not at start
3149 int start = interval_.nextNotIgnored(previousStart);
3150 if (start < actual._tokenstart) {
3151 interval_.output(os, actual._tokenstart);
3152 interval_.addIntervall(start, actual._tokenstart);
3154 // discard entry if at end of actual
3155 nextKeyIdx = process(os, actual);
3159 case KeyInfo::endArguments: {
3160 // Remove trailing '{}' too
3161 actual._dataStart += 1;
3162 actual._dataEnd += 1;
3163 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3164 nextKeyIdx = getNextKey();
3167 case KeyInfo::noMain:
3169 case KeyInfo::isStandard: {
3170 if (actual.disabled) {
3172 processRegion(actual._dataStart, actual._dataStart+1);
3173 nextKeyIdx = getNextKey();
3175 // Split on this key if not at datastart of calling entry
3176 int start = interval_.nextNotIgnored(previousStart);
3177 if (start < actual._tokenstart) {
3178 interval_.output(os, actual._tokenstart);
3179 interval_.addIntervall(start, actual._tokenstart);
3181 // discard entry if at end of actual
3182 nextKeyIdx = process(os, actual);
3186 case KeyInfo::removeWithArg: {
3187 nextKeyIdx = getNextKey();
3188 // Search for end of arguments
3189 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3191 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3192 entries_[i].disabled = true;
3194 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3196 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3199 case KeyInfo::doRemove: {
3200 // Remove the key with all parameters and following spaces
3203 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3204 start = actual._dataEnd;
3206 start = actual._dataEnd+1;
3207 for (pos = start; pos < interval_.par.length(); pos++) {
3208 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3211 // Remove also enclosing parentheses [] and {}
3214 while (actual._tokenstart > numpars) {
3215 if (pos+numpars >= interval_.par.size())
3217 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3219 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3225 if (interval_.par[pos+numpars] == ' ')
3229 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3230 nextKeyIdx = getNextKey();
3233 case KeyInfo::isList: {
3234 // Discard space before _tokenstart
3236 for (count = 0; count < actual._tokenstart; count++) {
3237 if (interval_.par[actual._tokenstart-count-1] != ' ')
3240 nextKeyIdx = getNextKey();
3241 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3243 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3245 // How else can we catch this one?
3246 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3247 entries_[i].disabled = true;
3249 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3251 else if (nextKeyIdx > 0) {
3252 // Ignore any lang entries inside data region
3253 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3254 if (entries_[i].keytype == KeyInfo::isMain)
3255 entries_[i].disabled = true;
3258 if (actual.disabled) {
3259 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3262 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3264 if (interval_.par[actual._dataEnd+1] == '[') {
3265 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3266 if ((interval_.par[actual._dataEnd+2] == '{') &&
3267 (interval_.par[posdown-1] == '}')) {
3268 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3269 interval_.addIntervall(posdown-1, posdown+1);
3272 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3273 interval_.addIntervall(posdown, posdown+1);
3275 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3276 if (blk > posdown) {
3277 // Discard at most 1 space after empty item
3279 for (count = 0; count < 1; count++) {
3280 if (interval_.par[blk+count] != ' ')
3284 interval_.addIntervall(blk, blk+count);
3289 case KeyInfo::isSectioning: {
3290 // Discard spaces before _tokenstart
3292 int val = actual._tokenstart;
3293 for (count = 0; count < actual._tokenstart;) {
3294 val = interval_.previousNotIgnored(val-1);
3295 if (val < 0 || interval_.par[val] != ' ')
3298 count = actual._tokenstart - val;
3301 if (actual.disabled) {
3302 removeHead(actual, count);
3303 nextKeyIdx = getNextKey();
3305 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3306 nextKeyIdx = process(os, actual);
3310 case KeyInfo::isMath: {
3311 // Same as regex, use the content unchanged
3312 nextKeyIdx = getNextKey();
3315 case KeyInfo::isRegex: {
3316 // DO NOT SPLIT ON REGEX
3318 nextKeyIdx = getNextKey();
3321 case KeyInfo::isIgnored: {
3322 // Treat like a character for now
3323 nextKeyIdx = getNextKey();
3326 case KeyInfo::isMain: {
3327 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3328 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3329 if (actual._tokenstart > 0) {
3330 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3331 if ((prev >= 0) && interval_.par[prev] == '%')
3332 interval_.addIntervall(prev, prev+1);
3334 if (actual.disabled) {
3336 interval_.langcount++;
3337 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3338 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3339 // Discard also the space before math-equation
3340 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3342 nextKeyIdx = getNextKey();
3343 // interval.resetOpenedP(actual._dataStart-1);
3346 if (actual._tokenstart < 26) {
3347 // for the first (and maybe dummy) language
3348 interval_.setForDefaultLang(actual);
3350 interval_.resetOpenedP(actual._dataStart-1);
3354 case KeyInfo::invalid:
3355 case KeyInfo::headRemove:
3356 // These two cases cannot happen, already handled
3359 // LYXERR(Debug::INFO, "Unhandled keytype");
3360 nextKeyIdx = getNextKey();
3367 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3369 int end = interval_.nextNotIgnored(actual._dataEnd);
3370 int oldStart = actual._dataStart;
3371 int nextKeyIdx = getNextKey();
3373 if ((nextKeyIdx < 0) ||
3374 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3375 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3376 if (oldStart <= end) {
3377 processRegion(oldStart, end);
3382 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3384 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3385 (void) dispatch(os, actual._dataStart, nextKey);
3386 end = nextKey._tokenstart;
3389 processRegion(oldStart, nextKey._tokenstart);
3390 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3392 oldStart = nextKey._dataEnd+1;
3394 // now nextKey is either invalid or is outside of actual._dataEnd
3395 // output the remaining and discard myself
3396 if (oldStart <= end) {
3397 processRegion(oldStart, end);
3399 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3401 // This is the normal case.
3402 // But if using the firstlanguage, the closing may be missing
3404 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3406 if (actual._dataEnd < end)
3407 output_end = interval_.nextNotIgnored(actual._dataEnd);
3408 else if (interval_.par.size() > (size_t) end)
3409 output_end = interval_.nextNotIgnored(end);
3411 output_end = interval_.par.size();
3412 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3413 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3415 // Remove possible empty data
3416 int dstart = interval_.nextNotIgnored(actual._dataStart);
3417 while (interval_.isOpeningPar(dstart) == 1) {
3418 interval_.addIntervall(dstart, dstart+1);
3419 int dend = interval_.findclosing(dstart+1, output_end);
3420 interval_.addIntervall(dend, dend+1);
3421 dstart = interval_.nextNotIgnored(dstart+1);
3423 if (dstart < output_end)
3424 interval_.output(os, output_end);
3426 interval_.addIntervall(0, end);
3428 interval_.addIntervall(actual._tokenstart, end);
3432 string splitOnKnownMacros(string par, bool isPatternString)
3435 LatexInfo li(par, isPatternString);
3436 // LYXERR(Debug::INFO, "Berfore split: " << par);
3437 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3439 DummyKey._tokensize = 0;
3440 DummyKey._dataStart = 0;
3441 DummyKey._dataEnd = par.length();
3442 DummyKey.disabled = true;
3443 int firstkeyIdx = li.getFirstKey();
3445 if (firstkeyIdx >= 0) {
3446 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3447 DummyKey._tokenstart = firstKey._tokenstart;
3449 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3450 // Use dummy firstKey
3451 firstKey = DummyKey;
3452 (void) li.setNextKey(firstkeyIdx);
3455 if (par.substr(firstKey._dataStart, 2) == "% ")
3456 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3458 nextkeyIdx = li.process(os, firstKey);
3459 while (nextkeyIdx >= 0) {
3460 // Check for a possible gap between the last
3461 // entry and this one
3462 int datastart = li.nextNotIgnored(firstKey._dataStart);
3463 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3464 if ((nextKey._tokenstart > datastart)) {
3466 firstKey._dataStart = datastart;
3467 firstKey._dataEnd = par.length();
3468 (void) li.setNextKey(nextkeyIdx);
3469 // Fake the last opened parenthesis
3470 li.setForDefaultLang(firstKey);
3471 nextkeyIdx = li.process(os, firstKey);
3474 if (nextKey.keytype != KeyInfo::isMain) {
3475 firstKey._dataStart = datastart;
3476 firstKey._dataEnd = nextKey._dataEnd+1;
3477 (void) li.setNextKey(nextkeyIdx);
3478 li.setForDefaultLang(firstKey);
3479 nextkeyIdx = li.process(os, firstKey);
3482 nextkeyIdx = li.process(os, nextKey);
3486 // Handle the remaining
3487 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3488 firstKey._dataEnd = par.length();
3490 if ((firstKey._dataStart < firstKey._dataEnd) &&
3491 (par[firstKey._dataStart] != '}')) {
3492 li.setForDefaultLang(firstKey);
3493 (void) li.process(os, firstKey);
3496 // return string definitelly impossible to match, but should be known
3499 s = par; /* no known macros found */
3500 // LYXERR(Debug::INFO, "After split: " << s);
3505 * Try to unify the language specs in the latexified text.
3506 * Resulting modified string is set to "", if
3507 * the searched tex does not contain all the features in the search pattern
3509 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3511 static Features regex_f;
3512 static int missed = 0;
3513 static bool regex_with_format = false;
3515 int parlen = par.length();
3517 while ((parlen > 0) && (par[parlen-1] == '\n')) {
3521 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3522 // Happens to be there in case of description or labeling environment
3528 // Split the latex input into pieces which
3529 // can be digested by our search engine
3530 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3531 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3532 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3533 string doclang = pbuf->params().language->polyglossia();
3534 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3536 bool toIgnoreLang = true;
3537 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3539 if (sub.str(2) != doclang) {
3540 toIgnoreLang = false;
3544 setIgnoreFormat("language", toIgnoreLang, false);
3547 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3548 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3551 result = par.substr(0, parlen);
3552 if (isPatternString) {
3555 regex_f = identifyFeatures(result);
3556 string features = "";
3557 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3558 string a = it->first;
3559 regex_with_format = true;
3560 features += " " + a;
3561 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3563 LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3566 } else if (regex_with_format) {
3567 Features info = identifyFeatures(result);
3568 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3569 string a = it->first;
3570 bool b = it->second;
3571 if (b && ! info[a]) {
3573 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3580 // LYXERR(Debug::INFO, "No regex formats");
3586 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3587 static void identifyClosing(string & t, bool ignoreformat)
3590 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3591 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3593 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3595 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3597 if (! ignoreformat) {
3598 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3606 static int num_replaced = 0;
3607 static bool previous_single_replace = true;
3609 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3612 if (regexp_str.empty() || regexp2_str.empty()) {
3613 regexIsValid = false;
3614 regexError = "Invalid empty regex";
3617 // Handle \w properly
3618 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3619 if (! opt.casesensitive) {
3620 popts |= QRegularExpression::CaseInsensitiveOption;
3622 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3623 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3625 if (regexp.isValid() && regexp2.isValid()) {
3626 regexIsValid = true;
3627 // Check '{', '}' pairs inside the regex
3630 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3631 char c = par_as_string[i];
3638 else if (c == '}') {
3645 if (balanced != 0) {
3646 regexIsValid = false;
3647 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3651 regexIsValid = false;
3652 if (!regexp.isValid())
3653 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3655 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3658 (void)par_as_string;
3659 if (opt.casesensitive) {
3660 regexp = regex(regexp_str);
3661 regexp2 = regex(regexp2_str);
3664 regexp = regex(regexp_str, std::regex_constants::icase);
3665 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3670 static void modifyRegexForMatchWord(string &t)
3673 regex wordre("(\\\\)*((\\.|\\\\b))");
3676 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3678 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3681 else if (sub.str(2) == "\\\\b")
3683 if (lastpos < (size_t) sub.position(2))
3684 s += t.substr(lastpos, sub.position(2) - lastpos);
3686 lastpos = sub.position(2) + sub.length(2);
3689 s = "\\b" + t + "\\b";
3693 else if (lastpos < t.length())
3694 s += t.substr(lastpos, t.length() - lastpos);
3695 t = "\\b" + s + "\\b";
3698 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3699 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3701 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3702 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3704 CreateRegexp(opt, "", "", "");
3707 use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3708 if (opt.replace_all && previous_single_replace) {
3709 previous_single_replace = false;
3712 else if (!opt.replace_all) {
3713 num_replaced = 0; // count number of replaced strings
3714 previous_single_replace = true;
3716 // When using regexp, braces are hacked already by escape_for_regex()
3717 par_as_string = convertLF2Space(ds, opt.ignoreformat);
3719 size_t lead_size = 0;
3720 // correct the language settings
3721 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3722 if (par_as_string.empty()) {
3723 CreateRegexp(opt, "", "", "");
3726 opt.matchAtStart = false;
3728 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3729 if (opt.ignoreformat) {
3733 lead_size = identifyLeading(par_as_string);
3735 lead_as_string = par_as_string.substr(0, lead_size);
3736 string lead_as_regex_string = string2regex(lead_as_string);
3737 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3738 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3739 /* Handle whole words too in this case
3741 if (opt.matchword) {
3742 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3743 opt.matchword = false;
3745 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3746 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3747 CreateRegexp(opt, regexp_str, regexp2_str);
3749 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3750 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3754 if (!opt.ignoreformat) {
3755 lead_size = identifyLeading(par_as_string);
3756 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3757 lead_as_string = par_as_string.substr(0, lead_size);
3758 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3761 // Here we are using regexp
3762 LASSERT(use_regexp, /**/);
3764 string lead_as_regexp;
3765 if (lead_size > 0) {
3766 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3767 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3768 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3769 par_as_string = par_as_string_nolead;
3770 LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3771 LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3773 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3774 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3775 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3776 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3778 size_t lng = par_as_string.size();
3779 if (!opt.ignoreformat) {
3780 // Remove extra '\}' at end if not part of \{\.\}
3782 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3784 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3793 if (lng < par_as_string.size())
3794 par_as_string.resize(lng);
3796 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3797 if ((lng > 0) && (par_as_string[0] == '^')) {
3798 par_as_string = par_as_string.substr(1);
3800 opt.matchAtStart = true;
3802 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3803 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3804 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3806 // If entered regexp must match at begin of searched string buffer
3807 // Kornel: Added parentheses to use $1 for size of the leading string
3811 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3812 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3813 // so the convert has no effect in that case
3814 for (int i = 7; i > 0; --i) {
3815 string orig = "\\\\" + std::to_string(i);
3816 string dest = "\\" + std::to_string(i+2);
3817 while (regex_replace(par_as_string, par_as_string, orig, dest));
3819 if (opt.matchword) {
3820 modifyRegexForMatchWord(par_as_string);
3821 // opt.matchword = false;
3823 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3824 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3826 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3827 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3828 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3832 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3836 mres.searched_size = len;
3838 docstring docstr = stringifyFromForSearch(opt, cur, len);
3840 str = convertLF2Space(docstr, opt.ignoreformat);
3841 if (!opt.ignoreformat) {
3842 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3843 // remove closing '}' and '\n' to allow for use of '$' in regex
3844 size_t lng = str.size();
3845 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3847 if (lng != str.size()) {
3848 str = str.substr(0, lng);
3850 // Replace occurences of '~' to ' '
3851 static std::regex specialChars { R"(~)" };
3852 str = std::regex_replace(str, specialChars, R"( )" );
3855 mres.match_len = -1;
3858 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3860 LASSERT(use_regexp, /**/);
3862 // use_regexp always true
3863 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3865 QString qstr = QString::fromStdString(str);
3866 QRegularExpression const *p_regexp;
3867 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3868 if (at_begin == MatchStringAdv::MatchFromStart) {
3871 p_regexp = ®exp2;
3873 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3874 if (!match.hasMatch())
3877 regex const *p_regexp;
3878 regex_constants::match_flag_type flags;
3879 if (at_begin == MatchStringAdv::MatchFromStart) {
3880 flags = regex_constants::match_continuous;
3883 flags = regex_constants::match_default;
3884 p_regexp = ®exp2;
3886 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3887 if (re_it == sregex_iterator())
3889 match_results<string::const_iterator> const & m = *re_it;
3891 // Whole found string, including the leading
3892 // std: m[0].second - m[0].first
3893 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3895 // Size of the leading string
3896 // std: m[1].second - m[1].first
3897 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3898 int leadingsize = 0;
3900 if (match.lastCapturedIndex() > 0) {
3901 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3906 leadingsize = m[1].second - m[1].first;
3910 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3911 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3912 // because of different number of closing at end of string
3913 // we have to 'unify' the length of the post-match.
3914 // Done by ignoring closing parenthesis and linefeeds at string end
3915 int matchend = match.capturedEnd(0);
3916 size_t strsize = qstr.size();
3917 if (!opt.ignoreformat) {
3918 while (mres.match_len > 1) {
3919 QChar c = qstr.at(matchend - 1);
3920 if ((c == '\n') || (c == '}') || (c == '{')) {
3927 while (strsize > (size_t) match.capturedEnd(0)) {
3928 QChar c = qstr.at(strsize-1);
3929 if ((c == '\n') || (c == '}')) {
3936 // LYXERR0(qstr.toStdString());
3937 mres.match2end = strsize - matchend;
3938 mres.pos = match.capturedStart(2);
3940 mres.match_prefix = m[2].second - m[2].first;
3941 mres.match_len = m[0].second - m[2].second;
3942 // ignore closing parenthesis and linefeeds at string end
3943 size_t strend = m[0].second - m[0].first;
3944 int matchend = strend;
3945 size_t strsize = str.size();
3946 if (!opt.ignoreformat) {
3947 while (mres.match_len > 1) {
3948 char c = str.at(matchend - 1);
3949 if ((c == '\n') || (c == '}') || (c == '{')) {
3956 while (strsize > strend) {
3957 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3965 mres.match2end = strsize - matchend;
3966 mres.pos = m[2].first - m[0].first;;
3968 if (mres.match2end < 0)
3970 mres.leadsize = leadingsize;
3972 if (mres.match_len > 0) {
3973 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3974 mres.result.push_back(a0);
3975 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3976 mres.result.push_back(match.captured(i).toStdString());
3980 if (mres.match_len > 0) {
3981 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3982 mres.result.push_back(a0);
3983 for (size_t i = 3; i < m.size(); i++) {
3984 mres.result.push_back(m[i]);
3993 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3995 MatchResult mres = findAux(cur, len, at_begin);
3996 LYXERR(Debug::FINDVERBOSE,
3997 "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3998 << ", matchAtStart=" << opt.matchAtStart
3999 << ", inTexted=" << cur.inTexted());
4000 if (mres.match_len > 0) {
4001 if (opt.matchAtStart) {
4002 if (cur.pos() > 0 || mres.match_prefix > 0)
4010 static bool simple_replace(string &t, string from, string to)
4012 regex repl("(\\\\)*(" + from + ")");
4016 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
4018 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4020 if (lastpos < (size_t) sub.position(2))
4021 s += t.substr(lastpos, sub.position(2) - lastpos);
4023 lastpos = sub.position(2) + sub.length(2);
4027 else if (lastpos < t.length())
4028 s += t.substr(lastpos, t.length() - lastpos);
4034 string MatchStringAdv::convertLF2Space(docstring const &s, bool ignore_format) const
4036 // Using original docstring to handle '\n'
4038 if (s.size() == 0) return "";
4042 size_t end = s.size() - 1;
4043 if (!ignore_format) {
4044 while (s[start] == '\n' && start <= end)
4046 while (end >= start && s[end] == '\n')
4048 if (start >= end + 1)
4052 bool dospace = true;
4054 pos = s.find('\n', start);
4056 t << lyx::to_utf8(s.substr(start, end + 1 - start));
4059 if (!ignore_format) {
4060 if ((pos > start + 1) &&
4064 if ((pos > start + 2) &&
4065 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4066 s[pos-3] == '~' || isSpace(s[pos-3]))) {
4067 // discard "\\\\\n", do not replace with space
4071 else if (pos > start) {
4072 if (s[pos-1] == '%') {
4074 while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4076 if ((pos > start+skip) &&
4077 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4078 s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4079 // discard '%%%%%\n'
4083 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4085 skip = 0; // remove the '\n' only
4093 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4097 } while (start <= end);
4101 docstring stringifyFromCursor(DocIterator const & cur, int len)
4103 LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4104 if (cur.inTexted()) {
4105 Paragraph const & par = cur.paragraph();
4106 // TODO what about searching beyond/across paragraph breaks ?
4107 // TODO Try adding a AS_STR_INSERTS as last arg
4108 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4109 int(par.size()) : cur.pos() + len;
4110 // OutputParams runparams(&cur.buffer()->params().encoding());
4111 OutputParams runparams(encodings.fromLyXName("utf8"));
4112 runparams.nice = true;
4113 setFindParams(runparams);
4114 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4115 if (ignoreFormats.getDeleted()) {
4116 option |= AS_STR_SKIPDELETE;
4117 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4120 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4122 if (ignoreFormats.getNonContent()) {
4123 runparams.find_add_feature(OutputParams::SearchNonOutput);
4125 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4126 << cur << ", from pos: " << cur.pos() << ", end: " << end);
4127 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4129 &runparams), false));
4130 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4132 } else if (cur.inMathed()) {
4133 CursorSlice cs = cur.top();
4134 MathData md = cs.cell();
4135 MathData::const_iterator it_end =
4136 (( len == -1 || cs.pos() + len > int(md.size()))
4138 : md.begin() + cs.pos() + len );
4139 MathData md2(cur.buffer());
4140 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4142 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4143 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4146 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4150 /** Computes the LaTeX export of buf starting from cur and ending len positions
4151 * after cur, if len is positive, or at the paragraph or innermost inset end
4154 docstring latexifyFromCursor(DocIterator const & cur, int len)
4157 LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4158 LYXERR(Debug::FINDVERBOSE, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4159 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4161 Buffer const & buf = *cur.buffer();
4163 odocstringstream ods;
4165 //OutputParams runparams(&buf.params().encoding());
4166 OutputParams runparams(encodings.fromLyXName("utf8"));
4167 runparams.nice = false;
4168 setFindParams(runparams);
4169 if (ignoreFormats.getDeleted()) {
4170 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4173 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4175 if (ignoreFormats.getNonContent()) {
4176 runparams.find_add_feature(OutputParams::SearchNonOutput);
4179 if (cur.inTexted()) {
4180 // @TODO what about searching beyond/across paragraph breaks ?
4181 pos_type endpos = cur.paragraph().size();
4182 if (len != -1 && endpos > cur.pos() + len)
4183 endpos = cur.pos() + len;
4184 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4185 string(), cur.pos(), endpos, true);
4186 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4188 } else if (cur.inMathed()) {
4189 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4190 for (int s = cur.depth() - 1; s >= 0; --s) {
4191 CursorSlice const & cs = cur[s];
4192 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4193 TeXMathStream ws(os);
4194 cs.asInsetMath()->asHullInset()->header_write(ws);
4199 CursorSlice const & cs = cur.top();
4200 MathData md = cs.cell();
4201 MathData::const_iterator it_end =
4202 ((len == -1 || cs.pos() + len > int(md.size()))
4204 : md.begin() + cs.pos() + len);
4205 MathData md2(cur.buffer());
4206 for (MathData::const_iterator it = md.begin() + cs.pos();
4210 ods << asString(md2);
4211 // Retrieve the math environment type, and add '$' or '$]'
4212 // or others (\end{equation}) accordingly
4213 for (int s = cur.depth() - 1; s >= 0; --s) {
4214 CursorSlice const & cs2 = cur[s];
4215 InsetMath * inset = cs2.asInsetMath();
4216 if (inset && inset->asHullInset()) {
4217 TeXMathStream ws(os);
4218 inset->asHullInset()->footer_write(ws);
4222 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4224 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4229 #if defined(ResultsDebug)
4231 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4233 LYXERR0( "from:\t\t\t" << from);
4235 if (mres.pos_len > 0) {
4237 status = "FINALSEARCH";
4240 if (mres.match_len > 0) {
4241 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4242 status = "Good Match";
4244 status = "Matched in";
4247 status = "MissedSearch";
4250 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4251 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4252 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4253 if ((mres.pos > 0) || (mres.match_prefix > 0))
4254 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4255 for (size_t i = 0; i < mres.result.size(); i++)
4256 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4258 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4260 #define displayMres(s, txt, cur)
4263 /** Finalize an advanced find operation, advancing the cursor to the innermost
4264 ** position that matches, plus computing the length of the matching text to
4266 ** Return the cur.pos() difference between start and end of found match
4268 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4270 // Search the foremost position that matches (avoids find of entire math
4271 // inset when match at start of it)
4272 DocIterator old_cur(cur.buffer());
4274 static MatchResult fail = MatchResult();
4275 MatchResult max_match;
4276 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4277 // Happens with e.g. hyperlinks
4278 // either one sees "http://www.bla.bla" or nothing
4279 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4280 // and although we search for only 3 chars, we find the whole hyperlink inset
4281 MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4282 if (!match.opt.forward && match.opt.ignoreformat) {
4283 if (expected.pos > 0)
4286 LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4287 if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4288 // Search for deepest match
4290 max_match = expected;
4292 size_t d = cur.depth();
4296 if (cur.depth() < d)
4298 if (cur.depth() == d)
4301 while (cur && cur.depth() > lastd) {
4302 lastd = cur.depth();
4303 mres = match(cur, -1, at_begin);
4304 displayMres(mres, "Checking innermost", cur);
4305 if (mres.match_len > 0)
4310 if (mres.match_len < expected.match_len)
4318 // (expected.match_len <= 0)
4319 mres = match(cur, -1, MatchStringAdv::MatchFromStart); /* match valid only if not searching whole words */
4320 displayMres(mres, "Start with negative match", cur);
4323 // Only now we are really at_begin
4324 if ((max_match.match_len <= 0) ||
4325 (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4327 LYXERR(Debug::FINDVERBOSE, "Ok");
4329 // Compute the match length
4331 if (cur.pos() + len > cur.lastpos())
4334 LASSERT(match.use_regexp, /**/);
4337 int maxl = cur.lastpos() - cur.pos();
4338 // Greedy behaviour while matching regexps
4339 while (maxl > minl) {
4341 mres2 = match(cur, len, at_begin);
4342 displayMres(mres2, "Finalize loop", cur);
4343 int actual_match_len = mres2.match_len;
4344 if (actual_match_len >= max_match.match_len) {
4345 // actual_match_len > max_match _can_ happen,
4346 // if the search area splits
4347 // some following word so that the regex
4348 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4350 // This means, the len value is too big
4351 actual_match_len = max_match.match_len;
4353 max_match.match_len = actual_match_len;
4355 if (maxl - minl < 4)
4356 len = (maxl + minl)/2;
4358 len = minl + (maxl - minl + 3)/4;
4361 // (actual_match_len < max_match.match_len)
4363 len = (maxl + minl)/2;
4368 // Search for real start of matched characters
4370 MatchResult actual_match;
4373 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4374 if (cur.depth() < old_cur.depth()) {
4376 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4379 if (cur.pos() != old_cur.pos()) {
4380 // OK, forwarded 1 pos in actual inset
4381 actual_match = match(cur, len-1, at_begin);
4382 if (actual_match.match_len == max_match.match_len) {
4383 // Ha, got it! The shorter selection has the same match length
4386 max_match = actual_match;
4389 // OK, the shorter selection matches less chars, revert to previous value
4395 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4396 actual_match = match(cur, len, at_begin);
4397 if (actual_match.match_len == max_match.match_len) {
4399 max_match = actual_match;
4406 max_match.pos_len = len;
4407 displayMres(max_match, "SEARCH RESULT", cur)
4414 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4419 DocIterator orig_cur; // to be used if repeat not successful
4420 MatchResult orig_mres;
4424 } while (cur.depth() > orig_cur.depth());
4426 while (!theApp()->longOperationCancelled() && cur) {
4427 //(void) findAdvForwardInnermost(cur);
4428 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4429 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4430 string msg = "Starting";
4433 displayMres(mres, msg + " findForwardAdv", cur)
4434 int match_len = mres.match_len;
4435 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4436 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4439 if (match_len <= 0) {
4444 // This should exit nested insets, if any, or otherwise undefine the currsor.
4445 cur.pos() = cur.lastpos();
4447 LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4450 else { // match_len > 0
4451 // Try to find the begin of searched string
4453 int firstInvalid = cur.lastpos() - cur.pos();
4455 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4456 int incrcur = (firstInvalid + 1 )*3/4;
4457 if (incrcur < incrmatch)
4458 increment = incrcur;
4460 increment = incrmatch;
4464 LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4465 while (increment > 0) {
4466 DocIterator old_cur = cur;
4467 if (cur.pos() + increment >= cur.lastpos()) {
4471 cur.pos() = cur.pos() + increment;
4472 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4473 displayMres(mres2, "findForwardAdv loop", cur)
4474 switch (interpretMatch(mres, mres2)) {
4475 case MatchResult::newIsTooFar:
4476 // behind the expected match
4477 firstInvalid = increment;
4481 case MatchResult::newIsBetter:
4482 // not reached yet, but cur.pos()+increment is better
4484 firstInvalid -= increment;
4485 if (increment > firstInvalid*3/4)
4486 increment = firstInvalid*3/4;
4487 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4488 if (increment >= mres2.match_prefix)
4489 increment = (mres2.match_prefix+1)*3/4;
4494 // Handle not like MatchResult::newIsTooFar
4495 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4497 increment = increment*3/4;
4502 if (mres.match_len > 0) {
4503 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4504 // The match seems to indicate some deeper level
4512 else if (repeat > 0) {
4513 // should never be reached.
4517 // LYXERR0("Leaving first loop");
4518 LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4519 MatchResult found_match = findAdvFinalize(cur, match, mres);
4520 if (found_match.match_len > 0) {
4521 match.FillResults(found_match);
4522 return found_match.pos_len;
4525 // try next possible match
4536 /// Find the most backward consecutive match within same paragraph while searching backwards.
4537 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4539 DocIterator cur_begin = cur;
4540 cur_begin.pos() = 0;
4541 DocIterator tmp_cur = cur;
4542 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4543 Inset & inset = cur.inset();
4544 for (; cur != cur_begin; cur.backwardPos()) {
4545 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4546 DocIterator new_cur = cur;
4547 new_cur.backwardPos();
4548 if (new_cur == cur || &new_cur.inset() != &inset
4549 || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4551 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4552 if (new_mr.match_len == mr.match_len)
4556 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4562 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4566 // Backup of original position
4567 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4568 if (cur == cur_begin)
4571 DocIterator cur_orig(cur);
4572 bool pit_changed = false;
4575 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4577 if (found_match.match_len > 0) {
4579 cur.pos() = cur.lastpos();
4581 cur.pos() = cur_orig.pos();
4582 LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4583 DocIterator cur_prev_iter;
4585 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4586 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4587 << (found_match.match_len > 0) << ", cur: " << cur);
4588 if (found_match.match_len > 0) {
4589 MatchResult found_mr = findMostBackwards(cur, match, found_match);
4590 if (found_mr.pos_len > 0) {
4591 match.FillResults(found_mr);
4592 return found_mr.pos_len;
4596 // Stop if begin of document reached
4597 if (cur == cur_begin)
4599 cur_prev_iter = cur;
4603 if (cur == cur_begin)
4610 } while (!theApp()->longOperationCancelled());
4618 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4619 DocIterator const & cur, int len)
4621 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4623 if (!opt.ignoreformat)
4624 return latexifyFromCursor(cur, len);
4626 return stringifyFromCursor(cur, len);
4630 FindAndReplaceOptions::FindAndReplaceOptions(
4631 docstring const & _find_buf_name, bool _casesensitive,
4632 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4633 docstring const & _repl_buf_name, bool _keep_case,
4634 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4635 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4636 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4637 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4645 /** Check if 'len' letters following cursor are all non-lowercase */
4646 static bool allNonLowercase(Cursor const & cur, int len)
4648 pos_type beg_pos = cur.selectionBegin().pos();
4649 pos_type end_pos = cur.selectionBegin().pos() + len;
4650 if (len > cur.lastpos() + 1 - beg_pos) {
4651 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4652 len = cur.lastpos() + 1 - beg_pos;
4653 end_pos = beg_pos + len;
4655 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4656 if (isLowerCase(cur.paragraph().getChar(pos)))
4662 /** Check if first letter is upper case and second one is lower case */
4663 static bool firstUppercase(Cursor const & cur)
4666 pos_type pos = cur.selectionBegin().pos();
4667 if (pos >= cur.lastpos() - 1) {
4668 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4671 ch1 = cur.paragraph().getChar(pos);
4672 ch2 = cur.paragraph().getChar(pos + 1);
4673 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4674 LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4675 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4676 << ch2 << "(" << char(ch2) << ")"
4677 << ", result=" << result << ", cur=" << cur);
4682 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4684 ** \fixme What to do with possible further paragraphs in replace buffer ?
4686 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4688 ParagraphList::iterator pit = buffer.paragraphs().begin();
4689 LASSERT(!pit->empty(), /**/);
4690 pos_type right = pos_type(1);
4691 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4692 right = pit->size();
4693 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4697 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4699 // Should replace the string "$" + std::to_string(matchnum) with replacement
4700 // if the char '$' is not prefixed with odd number of char '\\'
4701 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4705 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4707 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4709 int num = stoi(sub.str(3), nullptr, 10);
4710 if (num >= maxmatchnum)
4712 if (lastpos < (size_t) sub.position(2))
4713 s += t.substr(lastpos, sub.position(2) - lastpos);
4714 s += replacements[num];
4715 lastpos = sub.position(2) + sub.length(2);
4719 else if (lastpos < t.length())
4720 s += t.substr(lastpos, t.length() - lastpos);
4726 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4728 Cursor & cur = bv->cursor();
4729 if (opt.repl_buf_name.empty()
4730 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4731 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4734 DocIterator sel_beg = cur.selectionBegin();
4735 DocIterator sel_end = cur.selectionEnd();
4736 if (&sel_beg.inset() != &sel_end.inset()
4737 || sel_beg.pit() != sel_end.pit()
4738 || sel_beg.idx() != sel_end.idx())
4740 int sel_len = sel_end.pos() - sel_beg.pos();
4741 LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4742 << ", sel_len: " << sel_len << endl);
4745 LASSERT(sel_len > 0, return 0);
4747 if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4750 // Build a copy of the replace buffer, adapted to the KeepCase option
4751 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4753 repl_buffer_orig.write(oss);
4754 string lyx = oss.str();
4755 if (matchAdv.valid_matches > 0)
4756 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4757 Buffer repl_buffer(string(), false);
4758 repl_buffer.setInternal(true);
4759 repl_buffer.setUnnamed(true);
4760 LASSERT(repl_buffer.readString(lyx), return 0);
4761 if (opt.keep_case && sel_len >= 2) {
4762 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4763 if (cur.inTexted()) {
4764 if (firstUppercase(cur))
4765 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4766 else if (allNonLowercase(cur, sel_len))
4767 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4770 cap::cutSelection(cur, false);
4771 if (cur.inTexted()) {
4772 repl_buffer.changeLanguage(
4773 repl_buffer.language(),
4774 cur.getFont().language());
4775 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4776 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4777 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4778 repl_buffer.params().documentClassPtr(),
4779 repl_buffer.params().authors(),
4780 bv->buffer().errorList("Paste"));
4781 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4782 sel_len = repl_buffer.paragraphs().begin()->size();
4783 } else if (cur.inMathed()) {
4784 odocstringstream ods;
4786 // OutputParams runparams(&repl_buffer.params().encoding());
4787 OutputParams runparams(encodings.fromLyXName("utf8"));
4788 runparams.nice = false;
4789 setFindParams(runparams);
4790 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4791 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4792 docstring repl_latex = ods.str();
4793 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4795 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4796 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4797 repl_latex = from_utf8(s);
4798 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4799 MathData ar(cur.buffer());
4800 asArray(repl_latex, ar, Parse::NORMAL);
4802 sel_len = ar.size();
4803 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4805 if (cur.pos() >= sel_len)
4806 cur.pos() -= sel_len;
4809 LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4810 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4811 bv->processUpdateFlags(Update::Force);
4815 static bool isWordChar(char_type c)
4817 return isLetterChar(c) || isNumberChar(c);
4820 /// Perform a FindAdv operation.
4821 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4826 // e.g., when invoking word-findadv from mini-buffer wither with
4827 // wrong options syntax or before ever opening advanced F&R pane
4828 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4832 MatchStringAdv matchAdv(bv->buffer(), opt);
4834 if (!matchAdv.regexIsValid) {
4835 bv->message(lyx::from_utf8(matchAdv.regexError));
4839 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4841 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4842 num_replaced += findAdvReplace(bv, opt, matchAdv);
4845 if (opt.matchword && cur.pos() > 0) { // Skip word-characters if we are in the mid of a word
4846 if (cur.inTexted()) {
4847 Paragraph const & par = cur.paragraph();
4848 int len_limit, new_pos;
4849 if (cur.lastpos() < par.size())
4850 len_limit = cur.lastpos();
4852 len_limit = par.size();
4853 for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4854 if (!isWordChar(par.getChar(new_pos)))
4857 if (new_pos > cur.pos())
4858 cur.pos() = new_pos;
4860 else if (cur.inMathed()) {
4861 // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4862 // I am not sure, we should consider the selection
4863 bool sel = bv->cursor().selection();
4864 if (!sel && cur.pos() < cur.lastpos()) {
4865 CursorSlice const & cs = cur.top();
4866 MathData md = cs.cell();
4868 MathData::const_iterator it_end = md.end();
4869 MathData md2(cur.buffer());
4870 // Start the check with one character before actual cursor position
4871 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4874 docstring inp = asString(md2);
4875 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4876 if (!isWordChar(inp[len]))
4879 // len == 0 means previous char was a word separator
4880 // len == 1 search starts with a word separator
4881 // len == 2 ... we have to skip len -1 chars
4883 cur.pos() = cur.pos() + len - 1;
4886 opt.matchword = false;
4888 pos_len = findForwardAdv(cur, matchAdv);
4891 pos_len = findBackwardsAdv(cur, matchAdv);
4892 } catch (exception & ex) {
4893 bv->message(from_utf8(ex.what()));
4898 if (num_replaced > 0) {
4899 switch (num_replaced)
4902 bv->message(_("One match has been replaced."));
4905 bv->message(_("Two matches have been replaced."));
4908 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4914 bv->message(_("Match not found."));
4919 if (num_replaced > 0)
4920 bv->message(_("Match has been replaced."));
4922 bv->message(_("Match found."));
4924 if (cur.pos() + pos_len > cur.lastpos()) {
4925 // Prevent crash in bv->putSelectionAt()
4926 // Should never happen, maybe LASSERT() here?
4927 pos_len = cur.lastpos() - cur.pos();
4929 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4930 bv->putSelectionAt(cur, pos_len, !opt.forward);
4936 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4938 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4939 << opt.casesensitive << ' '
4940 << opt.matchword << ' '
4941 << opt.forward << ' '
4942 << opt.expandmacros << ' '
4943 << opt.ignoreformat << ' '
4944 << opt.replace_all << ' '
4945 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4946 << opt.keep_case << ' '
4947 << int(opt.scope) << ' '
4950 LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4956 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4958 // LYXERR(Debug::FINDVERBOSE, "parsing");
4962 while (line != "EOSS") {
4966 if (is.eof()) // Tolerate malformed request
4970 // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4971 opt.find_buf_name = from_utf8(s);
4972 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4973 is.get(); // Waste space before replace string
4976 while (line != "EOSS") {
4980 if (is.eof()) // Tolerate malformed request
4984 // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
4985 opt.repl_buf_name = from_utf8(s);
4986 is >> opt.keep_case;
4989 opt.scope = FindAndReplaceOptions::SearchScope(i);
4991 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4994 LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4995 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4996 << opt.scope << ' ' << opt.restr);