3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
11 * \author Kornel Benko
13 * Full author contact details are available in file CREDITS.
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
27 #include "CutAndPaste.h"
28 #include "FuncRequest.h"
30 #include "output_latex.h"
31 #include "OutputParams.h"
32 #include "Paragraph.h"
37 #include "frontends/Application.h"
38 #include "frontends/alert.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
54 #include <unordered_map>
57 //#define ResultsDebug
58 #define USE_QT_FOR_SEARCH
59 #if defined(USE_QT_FOR_SEARCH)
60 #include <QRegularExpression>
67 using namespace lyx::support;
71 typedef unordered_map<string, string> AccentsMap;
72 typedef unordered_map<string,string>::const_iterator AccentsIterator;
73 static AccentsMap accents = unordered_map<string, string>();
75 // Helper class for deciding what should be ignored
79 IgnoreFormats() = default;
81 bool getFamily() const { return ignoreFamily_; }
83 bool getSeries() const { return ignoreSeries_; }
85 bool getShape() const { return ignoreShape_; }
87 bool getSize() const { return ignoreSize_; }
89 bool getUnderline() const { return ignoreUnderline_; }
91 bool getMarkUp() const { return ignoreMarkUp_; }
93 bool getStrikeOut() const { return ignoreStrikeOut_; }
95 bool getSectioning() const { return ignoreSectioning_; }
97 bool getFrontMatter() const { return ignoreFrontMatter_; }
99 bool getColor() const { return ignoreColor_; }
101 bool getLanguage() const { return ignoreLanguage_; }
103 bool getDeleted() const { return ignoreDeleted_; }
105 void setIgnoreDeleted(bool value);
107 bool getNonContent() const { return searchNonContent_; }
109 void setIgnoreFormat(string const & type, bool value, bool fromUser = true);
113 bool ignoreFamily_ = false;
115 bool ignoreSeries_ = false;
117 bool ignoreShape_ = false;
119 bool ignoreSize_ = true;
121 bool ignoreUnderline_ = false;
123 bool ignoreMarkUp_ = false;
125 bool ignoreStrikeOut_ = false;
127 bool ignoreSectioning_ = false;
129 bool ignoreFrontMatter_ = false;
131 bool ignoreColor_ = false;
133 bool ignoreLanguage_ = false;
134 bool userSelectedIgnoreLanguage_ = false;
136 bool ignoreDeleted_ = true;
138 bool searchNonContent_ = true;
141 void IgnoreFormats::setIgnoreFormat(string const & type, bool value, bool fromUser)
143 if (type == "color") {
144 ignoreColor_ = value;
146 else if (type == "language") {
148 userSelectedIgnoreLanguage_ = value;
149 ignoreLanguage_ = value;
152 ignoreLanguage_ = (value || userSelectedIgnoreLanguage_);
154 else if (type == "sectioning") {
155 ignoreSectioning_ = value;
156 ignoreFrontMatter_ = value;
158 else if (type == "font") {
159 ignoreSeries_ = value;
160 ignoreShape_ = value;
161 ignoreFamily_ = value;
163 else if (type == "series") {
164 ignoreSeries_ = value;
166 else if (type == "shape") {
167 ignoreShape_ = value;
169 else if (type == "size") {
172 else if (type == "family") {
173 ignoreFamily_ = value;
175 else if (type == "markup") {
176 ignoreMarkUp_ = value;
178 else if (type == "underline") {
179 ignoreUnderline_ = value;
181 else if (type == "strike") {
182 ignoreStrikeOut_ = value;
184 else if (type == "deleted") {
185 ignoreDeleted_ = value;
187 else if (type == "non-output-content") {
188 searchNonContent_ = !value;
192 // The global variable that can be changed from outside
193 IgnoreFormats ignoreFormats;
196 void setIgnoreFormat(string const & type, bool value, bool fromUser)
198 ignoreFormats.setIgnoreFormat(type, value, fromUser);
204 bool parse_bool(docstring & howto, bool const defvalue = false)
209 howto = split(howto, var, ' ');
217 MatchString(docstring const & s, bool cs, bool mw)
218 : str(s), case_sens(cs), whole_words(mw)
221 // returns true if the specified string is at the specified position
222 // del specifies whether deleted strings in ct mode will be considered
223 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
225 return par.find(str, case_sens, whole_words, pos, del);
233 // match whole words only
238 int findForward(DocIterator & cur, DocIterator const endcur,
239 MatchString const & match,
240 bool find_del = true, bool onlysel = false)
242 for (; cur; cur.forwardChar()) {
243 if (onlysel && endcur.pit() == cur.pit()
244 && endcur.idx() == cur.idx() && endcur.pos() < cur.pos())
246 if (cur.inTexted()) {
247 int len = match(cur.paragraph(), cur.pos(), find_del);
256 int findBackwards(DocIterator & cur, DocIterator const endcur,
257 MatchString const & match,
258 bool find_del = true, bool onlysel = false)
262 if (onlysel && endcur.pit() == cur.pit()
263 && endcur.idx() == cur.idx() && endcur.pos() > cur.pos())
265 if (cur.inTexted()) {
266 int len = match(cur.paragraph(), cur.pos(), find_del);
275 bool searchAllowed(docstring const & str)
278 frontend::Alert::error(_("Search error"), _("Search string is empty"));
287 bool findOne(BufferView * bv, docstring const & searchstr,
288 bool case_sens, bool whole, bool forward,
289 bool find_del, bool check_wrap, bool const auto_wrap,
290 bool instant, bool onlysel)
292 // Clean up previous selections with empty searchstr on instant
293 if (searchstr.empty() && instant) {
294 if (bv->cursor().selection()) {
295 bv->setCursor(bv->cursor().selectionBegin());
296 bv->clearSelection();
301 if (!searchAllowed(searchstr))
304 DocIterator const endcur = forward ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin();
306 if (onlysel && bv->cursor().selection()) {
307 docstring const matchstring = bv->cursor().selectionAsString(false);
308 docstring const lcmatchsting = support::lowercase(matchstring);
309 if (matchstring == searchstr || (!case_sens && lcmatchsting == lowercase(searchstr))) {
310 docstring q = _("The search string matches the selection, and search is limited to selection.\n"
311 "Continue search outside?");
312 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
313 q, 0, 1, _("&Yes"), _("&No"));
314 if (search_answer == 0) {
315 bv->clearSelection();
316 if (findOne(bv, searchstr, case_sens, whole, forward,
317 find_del, check_wrap, auto_wrap, false, false))
324 DocIterator cur = forward
325 ? ((instant || onlysel) ? bv->cursor().selectionBegin() : bv->cursor().selectionEnd())
326 : ((instant || onlysel) ? bv->cursor().selectionEnd() : bv->cursor().selectionBegin());
328 MatchString const match(searchstr, case_sens, whole);
330 int match_len = forward
331 ? findForward(cur, endcur, match, find_del, onlysel)
332 : findBackwards(cur, endcur, match, find_del, onlysel);
335 bv->putSelectionAt(cur, match_len, !forward);
336 else if (onlysel && bv->cursor().selection()) {
337 docstring q = _("The search string was not found within the selection.\n"
338 "Continue search outside?");
339 int search_answer = frontend::Alert::prompt(_("Search outside selection?"),
340 q, 0, 1, _("&Yes"), _("&No"));
341 if (search_answer == 0) {
342 bv->clearSelection();
343 if (findOne(bv, searchstr, case_sens, whole, forward,
344 find_del, check_wrap, auto_wrap, false, false))
349 else if (check_wrap) {
350 DocIterator cur_orig(bv->cursor());
351 bool wrap = auto_wrap;
355 q = _("End of file reached while searching forward.\n"
356 "Continue searching from the beginning?");
358 q = _("Beginning of file reached while searching backward.\n"
359 "Continue searching from the end?");
360 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
361 q, 0, 1, _("&Yes"), _("&No"));
362 wrap = wrap_answer == 0;
366 bv->cursor().clear();
367 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
369 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
370 bv->cursor().backwardPos();
373 docstring const msg = forward
374 ? _("Search reached end of document, continuing from beginning.")
375 : _("Search reached beginning of document, continuing from end.");
378 bv->clearSelection();
379 if (findOne(bv, searchstr, case_sens, whole, forward,
380 find_del, false, false, false, false))
383 bv->cursor().setCursor(cur_orig);
387 return match_len > 0;
393 int replaceAll(BufferView * bv,
394 docstring const & searchstr, docstring const & replacestr,
395 bool case_sens, bool whole, bool onlysel)
397 Buffer & buf = bv->buffer();
399 if (!searchAllowed(searchstr) || buf.isReadonly())
402 DocIterator startcur = bv->cursor().selectionBegin();
403 DocIterator endcur = bv->cursor().selectionEnd();
404 bool const had_selection = bv->cursor().selection();
406 MatchString const match(searchstr, case_sens, whole);
409 int const rsize = replacestr.size();
410 int const ssize = searchstr.size();
413 cur.setCursor(doc_iterator_begin(&buf));
414 int match_len = findForward(cur, endcur, match, false, onlysel);
415 while (match_len > 0) {
416 // Backup current cursor position and font.
417 pos_type const pos = cur.pos();
418 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
420 int ct_deleted_text = ssize -
421 cur.paragraph().eraseChars(pos, pos + match_len,
422 buf.params().track_changes);
423 cur.paragraph().insert(pos, replacestr, font,
424 Change(buf.params().track_changes
426 : Change::UNCHANGED));
427 for (int i = 0; i < rsize + ct_deleted_text
428 && cur.pos() < cur.lastpos(); ++i)
430 if (onlysel && cur.pit() == endcur.pit() && cur.idx() == endcur.idx()) {
431 // Adjust end of selection for replace-all in selection
433 int const offset = rsize - ssize;
434 for (int i = 0; i < offset + ct_deleted_text
435 && endcur.pos() < endcur.lastpos(); ++i)
438 int const offset = ssize - rsize;
439 for (int i = 0; i < offset && endcur.pos() > 0; ++i)
440 endcur.backwardPos();
441 for (int i = 0; i < ct_deleted_text
442 && endcur.pos() < endcur.lastpos(); ++i)
447 match_len = findForward(cur, endcur, match, false, onlysel);
450 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
452 startcur.fixIfBroken();
453 bv->setCursor(startcur);
455 // Reset selection, accounting for changes in selection
457 endcur.fixIfBroken();
458 bv->cursor().resetAnchor();
459 bv->setCursorSelectionTo(endcur);
466 // the idea here is that we are going to replace the string that
467 // is selected IF it is the search string.
468 // if there is a selection, but it is not the search string, then
469 // we basically ignore it. (FIXME We ought to replace only within
471 // if there is no selection, then:
472 // (i) if some search string has been provided, then we find it.
473 // (think of how the dialog works when you hit "replace" the
475 // (ii) if no search string has been provided, then we treat the
476 // word the cursor is in as the search string. (why? i have no
477 // idea.) but this only works in text?
479 // returns the number of replacements made (one, if any) and
480 // whether anything at all was done.
481 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
482 docstring const & replacestr, bool case_sens,
483 bool whole, bool forward, bool findnext, bool wrap,
486 Cursor & cur = bv->cursor();
487 if (!cur.selection() || onlysel) {
488 // no selection, non-empty search string: find it
489 if (!searchstr.empty()) {
490 bool const found = findOne(bv, searchstr, case_sens, whole,
491 forward, true, findnext, wrap, false, onlysel);
492 return make_pair(found, 0);
494 // empty search string
497 return make_pair(false, 0);
498 // select current word and treat it as the search string.
499 // This causes a minor bug as undo will restore this selection,
500 // which the user did not create (#8986).
501 cur.innerText()->selectWord(cur, WHOLE_WORD);
502 searchstr = cur.selectionAsString(false, true);
505 // if we still don't have a search string, report the error
507 if (!searchAllowed(searchstr))
508 return make_pair(false, 0);
510 bool have_selection = cur.selection();
511 docstring const selected = cur.selectionAsString(false, true);
514 ? searchstr == selected
515 : compare_no_case(searchstr, selected) == 0;
517 // no selection or current selection is not search word:
518 // just find the search word
519 if (!have_selection || !match) {
520 bool const found = findOne(bv, searchstr, case_sens, whole, forward,
521 true, findnext, wrap, false, onlysel);
522 return make_pair(found, 0);
525 // we're now actually ready to replace. if the buffer is
526 // read-only, we can't, though.
527 if (bv->buffer().isReadonly())
528 return make_pair(false, 0);
530 cap::replaceSelectionWithString(cur, replacestr);
532 cur.pos() += replacestr.length();
533 LASSERT(cur.pos() <= cur.lastpos(),
534 cur.pos() = cur.lastpos());
537 findOne(bv, searchstr, case_sens, whole,
538 forward, false, findnext, wrap, false, onlysel);
540 return make_pair(true, 1);
546 docstring const find2string(docstring const & search,
547 bool casesensitive, bool matchword,
548 bool forward, bool wrap, bool instant,
553 << int(casesensitive) << ' '
554 << int(matchword) << ' '
555 << int(forward) << ' '
557 << int(instant) << ' '
563 docstring const replace2string(docstring const & replace,
564 docstring const & search,
565 bool casesensitive, bool matchword,
566 bool all, bool forward, bool findnext,
567 bool wrap, bool onlysel)
570 ss << replace << '\n'
572 << int(casesensitive) << ' '
573 << int(matchword) << ' '
575 << int(forward) << ' '
576 << int(findnext) << ' '
583 docstring const string2find(docstring const & argument,
591 // data is of the form
593 // <casesensitive> <matchword> <forward> <wrap> <onlysel>"
595 docstring howto = split(argument, search, '\n');
597 casesensitive = parse_bool(howto);
598 matchword = parse_bool(howto);
599 forward = parse_bool(howto, true);
600 wrap = parse_bool(howto);
601 instant = parse_bool(howto);
602 onlysel = parse_bool(howto);
608 bool lyxfind(BufferView * bv, FuncRequest const & ev)
610 if (!bv || ev.action() != LFUN_WORD_FIND)
613 //lyxerr << "find called, cmd: " << ev << endl;
621 docstring search = string2find(ev.argument(), casesensitive,
622 matchword, forward, wrap, instant, onlysel);
624 return findOne(bv, search, casesensitive, matchword, forward,
625 false, true, wrap, instant, onlysel);
629 bool lyxreplace(BufferView * bv, FuncRequest const & ev)
631 if (!bv || ev.action() != LFUN_WORD_REPLACE)
634 // data is of the form
637 // <casesensitive> <matchword> <all> <forward> <findnext> <wrap> <onlysel>"
640 docstring howto = split(ev.argument(), rplc, '\n');
641 howto = split(howto, search, '\n');
643 bool casesensitive = parse_bool(howto);
644 bool matchword = parse_bool(howto);
645 bool all = parse_bool(howto);
646 bool forward = parse_bool(howto, true);
647 bool findnext = parse_bool(howto, true);
648 bool wrap = parse_bool(howto);
649 bool onlysel = parse_bool(howto);
651 if (!bv->cursor().selection())
652 // only selection only makes sense with selection
657 int replace_count = 0;
659 replace_count = replaceAll(bv, search, rplc, casesensitive,
661 update = replace_count > 0;
664 replaceOne(bv, search, rplc, casesensitive, matchword,
665 forward, findnext, wrap, onlysel);
667 replace_count = rv.second;
670 Buffer const & buf = bv->buffer();
672 // emit message signal.
674 buf.message(_("String not found in selection."));
676 buf.message(_("String not found."));
678 if (replace_count == 0) {
679 buf.message(_("String found."));
680 } else if (replace_count == 1) {
681 buf.message(_("String has been replaced."));
683 docstring const str = onlysel
684 ? bformat(_("%1$d strings have been replaced in the selection."), replace_count)
685 : bformat(_("%1$d strings have been replaced."), replace_count);
693 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
695 for (; cur; cur.forwardPos())
696 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
700 DocIterator cur_orig(bv->cursor());
701 docstring q = _("End of file reached while searching forward.\n"
702 "Continue searching from the beginning?");
703 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
704 q, 0, 1, _("&Yes"), _("&No"));
705 if (wrap_answer == 0) {
706 bv->cursor().clear();
707 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
708 bv->clearSelection();
709 cur.setCursor(bv->cursor().selectionBegin());
710 if (findNextChange(bv, cur, false))
713 bv->cursor().setCursor(cur_orig);
720 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
722 for (cur.backwardPos(); cur; cur.backwardPos()) {
723 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
728 DocIterator cur_orig(bv->cursor());
729 docstring q = _("Beginning of file reached while searching backward.\n"
730 "Continue searching from the end?");
731 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
732 q, 0, 1, _("&Yes"), _("&No"));
733 if (wrap_answer == 0) {
734 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
735 bv->cursor().backwardPos();
736 bv->clearSelection();
737 cur.setCursor(bv->cursor().selectionBegin());
738 if (findPreviousChange(bv, cur, false))
741 bv->cursor().setCursor(cur_orig);
748 bool selectChange(Cursor & cur, bool forward)
750 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
752 Change ch = cur.paragraph().lookupChange(cur.pos());
754 CursorSlice tip1 = cur.top();
755 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
756 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
757 if (!ch2.isSimilarTo(ch))
760 CursorSlice tip2 = cur.top();
761 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
763 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
764 if (!ch2.isSimilarTo(ch)) {
765 // take a step forward to correctly set the selection
773 cur.bv().mouseSetCursor(cur, false);
775 cur.bv().mouseSetCursor(cur, true);
783 bool findChange(BufferView * bv, bool forward)
786 cur.setCursor(forward ? bv->cursor().selectionEnd()
787 : bv->cursor().selectionBegin());
788 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
789 return selectChange(cur, forward);
794 bool findNextChange(BufferView * bv)
796 return findChange(bv, true);
800 bool findPreviousChange(BufferView * bv)
802 return findChange(bv, false);
809 typedef vector<pair<string, string> > Escapes;
811 static string getRegexSpaceCount(int count)
815 return "\\s{" + std::to_string(count) + "}";
822 string string2regex(string in)
824 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\$\\])" };
825 string tempx = std::regex_replace(in, specialChars, R"(\$&)" );
826 // Special handling for ' '
829 for (unsigned i = 0; i < tempx.size(); i++) {
830 if (tempx[i] == ' ' || tempx[i] == '~' ) {
834 else if (tempx[i] == '\302' && tempx[i+1] == '\240') {
839 else if (tempx[i] == '\342') {
840 if (tempx[i+1] == '\200') {
841 if ((tempx[i+2] == '\257')
842 || (tempx[i+2] == '\203')
843 || (tempx[i+2] == '\202')) {
844 // Non-breaking Thin (1/6 em)
845 // Quad(1 em), (Double quad counts as 2 blanks)
850 else if (tempx[i+2] == '\213') {
851 // Ignoring parts of Medium and Thick
855 else if ((tempx[i+2] == '\204') || (tempx[i+2] == '\205')) {
862 else if (tempx[i+1] == '\201') {
863 if (tempx[i+2] == '\240') {
864 // Ignoring parts of half quad
869 else if ((tempx[i+1] == '\220') && (tempx[i+2] == '\243')) {
877 temp += getRegexSpaceCount(blanks);
884 temp += getRegexSpaceCount(blanks);
891 while (fl_pos < temp.size()) {
892 fl_pos = temp.find("\\\\foreignlanguage", lastpos + offset);
893 if (fl_pos == string::npos)
896 temp2 += temp.substr(lastpos, fl_pos - lastpos);
902 if (lastpos < temp.size()) {
903 temp2 += temp.substr(lastpos, temp.size() - lastpos);
908 static void buildAccentsMap();
910 string correctRegex(string t, bool withformat)
912 /* Convert \backslash => \
913 * and \{, \}, \[, \] => {, }, [, ]
916 static std::regex wordre("(\\\\)*(\\\\(( |[A-Za-z]+|[\\{\\}%])( |\\{\\})?|[\\[\\]\\{\\}]))");
917 static std::regex protectedSpace { R"(~)" };
920 bool backslashed = false;
924 //LYXERR0("correctRegex input '" << t << "'");
926 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
929 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
933 if (sub.str(4) == "backslash") {
934 replace = string("\\");
936 // transforms '\backslash \{' into '\{'
937 string next = t.substr(sub.position(2) + sub.str(2).length(), 2);
938 if ((next == "\\{") || (next == "\\}") || (next == "\\ ")) {
942 else if (withformat && next[0] == '$') {
943 replace = accents["lyxdollar"];
944 skip = 1; // Skip following '$'
948 else if (sub.str(4) == "mathcircumflex")
950 else if (backslashed) {
953 if (sub.str(3) == "{")
954 replace = accents["braceleft"];
955 else if (sub.str(3) == "}")
956 replace = accents["braceright"];
957 else if (sub.str(3) == " ")
960 // else part should not exist
965 if (sub.str(3) == "{")
967 else if (sub.str(3) == "}")
969 else if (sub.str(3) == " ")
972 // else part should not exist
977 else if (sub.str(4) == "{") // transforms '\{' into '{'
979 else if (sub.str(4) == "}")
981 else if (sub.str(4) == "%")
983 else if (sub.str(4) == " ")
986 AccentsIterator it_ac = accents.find(sub.str(4));
987 if (it_ac == accents.end()) {
988 replace = sub.str(2);
991 replace = it_ac->second;
995 if (lastpos < (size_t) sub.position(2))
996 s += std::regex_replace(t.substr(lastpos, sub.position(2) - lastpos), protectedSpace, R"( )");
998 lastpos = sub.position(2) + sub.length(2) + skip;
1002 s = std::regex_replace(t, protectedSpace, R"( )");
1003 else if (lastpos < t.length())
1004 s += std::regex_replace(t.substr(lastpos, t.length() - lastpos), protectedSpace, R"( )");
1005 // Handle quotes in regex
1006 // substitute all '„', '“', '»', '«' with '"'
1007 // and all '‚', '‘', '›', '‹' with "\'"
1008 static std::regex plainquotes { R"(„|“|»|«)" };
1009 static std::regex innerquotes { R"(‚|‘|›|‹)" };
1010 t = std::regex_replace(s, plainquotes, R"(")");
1011 s = std::regex_replace(t, innerquotes, R"(')");
1012 //LYXERR0("correctRegex output '" << s << "'");
1016 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
1017 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
1018 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
1019 string escape_for_regex(string s, bool withformat)
1023 while (lastpos < s.size()) {
1024 size_t regex_pos = s.find("\\regexp{", lastpos);
1025 if (regex_pos == string::npos) {
1026 regex_pos = s.size();
1028 if (regex_pos > lastpos) {
1029 result += string2regex(s.substr(lastpos, regex_pos-lastpos));
1030 lastpos = regex_pos;
1031 if (lastpos == s.size())
1034 size_t end_pos = s.find("\\endregexp", regex_pos + 8);
1035 result += correctRegex(s.substr(regex_pos + 8, end_pos -(regex_pos + 8)), withformat);
1036 lastpos = end_pos + 13;
1042 /// Wrapper for lyx::regex_replace with simpler interface
1043 bool regex_replace(string const & s, string & t, string const & searchstr,
1044 string const & replacestr)
1046 regex e(searchstr, regex_constants::ECMAScript);
1048 ostream_iterator<char, char> it(oss);
1049 regex_replace(it, s.begin(), s.end(), e, replacestr);
1050 // tolerate t and s be references to the same variable
1051 bool rv = (s != oss.str());
1070 vector <string> result = vector <string>();
1071 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0),pos_len(-1),searched_size(0) {}
1074 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
1076 if (newres.match2end < oldres.match2end)
1077 return MatchResult::newIsTooFar;
1078 if (newres.match_len < oldres.match_len)
1079 return MatchResult::newIsTooFar;
1081 if (newres.match_len == oldres.match_len) {
1082 if (newres.match2end == oldres.match2end)
1083 return MatchResult::newIsBetter;
1085 return MatchResult::newIsInvalid;
1088 /** The class performing a match between a position in the document and the FindAdvOptions.
1091 class MatchStringAdv {
1093 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt);
1095 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
1096 ** constructor as opt.search, under the opt.* options settings.
1099 ** If set to MatchStringAdv::MatchFromStart,
1100 ** then match is searched only against beginning of text starting at cur.
1101 ** Otherwise the match is searched anywhere in text starting at cur.
1104 ** The length of the matching text, or zero if no match was found.
1110 string matchTypeAsString(matchType const x) const { return (x == MatchFromStart ? "MatchFromStart" : "MatchAnyPlace"); }
1111 MatchResult operator()(DocIterator const & cur, int len, matchType at_begin) const;
1119 lyx::Buffer * p_buf;
1120 /// first buffer on which search was started
1121 lyx::Buffer * const p_first_buf;
1123 FindAndReplaceOptions const & opt;
1126 /// Auxiliary find method (does not account for opt.matchword)
1127 MatchResult findAux(DocIterator const & cur, int len, matchType at_begin) const;
1128 void CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string = "");
1130 /** Normalize a stringified or latexified LyX paragraph.
1134 ** <li>if search is not casesensitive, then lowercase the string;
1135 ** <li>remove any newline at begin or end of the string;
1136 ** <li>replace any newline in the middle of the string with a simple space;
1137 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
1140 ** @todo Normalization should also expand macros, if the corresponding
1141 ** search option was checked.
1143 string convertLF2Space(docstring const & s, bool ignore_fomat) const;
1144 // normalized string to search
1145 string par_as_string;
1146 // regular expression to use for searching
1147 // regexp2 is same as regexp, but prefixed with a ".*?"
1149 QRegularExpression regexp;
1150 QRegularExpression regexp2;
1155 // leading format material as string
1156 string lead_as_string;
1157 // par_as_string after removal of lead_as_string
1158 string par_as_string_nolead;
1159 // unmatched open braces in the search string/regexp
1160 int open_braces = 0;
1161 // number of (.*?) subexpressions added at end of search regexp for closing
1162 // environments, math mode, styles, etc...
1163 int close_wildcards = 0;
1165 // Are we searching with regular expressions ?
1166 bool use_regexp = false;
1167 static int valid_matches;
1168 static vector <string> matches;
1169 void FillResults(MatchResult &found_mr);
1172 int MatchStringAdv::valid_matches = 0;
1173 vector <string> MatchStringAdv::matches = vector <string>(10);
1175 void MatchStringAdv::FillResults(MatchResult &found_mr)
1177 if (found_mr.match_len > 0) {
1178 valid_matches = found_mr.result.size();
1179 for (size_t i = 0; i < found_mr.result.size(); i++)
1180 matches[i] = found_mr.result[i];
1185 static void setFindParams(OutputParams &runparams)
1187 runparams.flavor = Flavor::XeTeX;
1188 //runparams.use_polyglossia = true;
1189 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1190 // No side effect of file copying and image conversion
1191 runparams.dryrun = true;
1194 static docstring buffer_to_latex(Buffer & buffer)
1196 //OutputParams runparams(&buffer.params().encoding());
1197 OutputParams runparams(encodings.fromLyXName("utf8"));
1198 odocstringstream ods;
1200 runparams.nice = true;
1201 setFindParams(runparams);
1202 if (ignoreFormats.getDeleted())
1203 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1205 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1206 if (ignoreFormats.getNonContent()) {
1207 runparams.find_add_feature(OutputParams::SearchNonOutput);
1209 pit_type const endpit = buffer.paragraphs().size();
1210 for (pit_type pit = 0; pit != endpit; ++pit) {
1211 TeXOnePar(buffer, buffer.text(), pit, os, runparams, string(), -1, -1, true);
1212 LYXERR(Debug::FINDVERBOSE, "searchString up to here: " << ods.str());
1217 static string latexNamesToUtf8(docstring strIn, bool withformat)
1219 string addtmp = to_utf8(strIn);
1220 static regex const rmAcc("(\\\\)*("
1221 "\\\\([A-Za-z]+\\{.\\})" // e.g. "ddot{A}" == sub.str(3)
1222 "|\\\\([A-Za-z]+)( |\\{\\})?" // e.g. "LyX", "LyX{}", "LyX " == sub.str(4)
1229 if (accents.empty())
1231 for (sregex_iterator it_add(addtmp.begin(), addtmp.end(), rmAcc), end; it_add != end; ++it_add) {
1233 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
1238 if (sub.length(3) > 0)
1242 AccentsIterator it_ac = accents.find(key);
1243 if (it_ac == accents.end()) {
1244 replace = sub.str(2);
1247 replace = it_ac->second;
1250 if (lastpos < (size_t) sub.position(2))
1251 add += addtmp.substr(lastpos, sub.position(2) - lastpos);
1253 lastpos = sub.position(2) + sub.length(2);
1257 else if (addtmp.length() > lastpos)
1258 add += addtmp.substr(lastpos, addtmp.length() - lastpos);
1260 static std::regex repltilde { R"(~)" };
1261 add = std::regex_replace(add, repltilde, accents["lyxtilde"]);
1263 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1268 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1271 if (!opt.ignoreformat) {
1272 str = buffer_to_latex(buffer);
1274 // OutputParams runparams(&buffer.params().encoding());
1275 OutputParams runparams(encodings.fromLyXName("utf8"));
1276 runparams.nice = true;
1277 setFindParams(runparams);
1278 int option = AS_STR_INSETS |AS_STR_PLAINTEXT;
1279 if (ignoreFormats.getDeleted()) {
1280 option |= AS_STR_SKIPDELETE;
1281 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
1284 runparams.find_set_feature(OutputParams::SearchWithDeleted);
1286 if (ignoreFormats.getNonContent()) {
1287 runparams.find_add_feature(OutputParams::SearchNonOutput);
1290 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1291 Paragraph const & par = buffer.paragraphs().at(pit);
1292 string add = latexNamesToUtf8(par.asString(pos_type(0), par.size(),
1294 &runparams), !opt.ignoreformat);
1295 LYXERR(Debug::FINDVERBOSE, "Adding to search string: '"
1299 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1300 while (regex_replace(t, t, "\\\\(text|lyxmathsym|ensuremath)\\{([^\\}]*)\\}", "$2"));
1307 /// Return separation pos between the leading material and the rest
1308 static size_t identifyLeading(string const & s)
1311 // @TODO Support \item[text]
1312 // Kornel: Added textsl, textsf, textit, texttt and noun
1313 // + allow to search for colored text too
1314 while (regex_replace(t, t, "^\\\\(("
1315 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1316 "lyxaddress|lyxrightaddress|"
1317 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1318 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1319 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1320 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1321 || regex_replace(t, t, "^\\$", "")
1322 || regex_replace(t, t, "^\\\\\\[", "")
1323 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1324 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1326 LYXERR(Debug::FINDVERBOSE, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1327 return s.size() - t.size();
1331 * Given a latexified string, retrieve some handled features
1332 * The features of the regex will later be compared with the features
1333 * of the searched text. If the regex features are not a
1334 * subset of the analized, then, in not format ignoring search
1335 * we can early stop the search in the relevant inset.
1337 typedef map<string, bool> Features;
1339 static Features identifyFeatures(string const & s)
1341 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1342 static regex const valid("^("
1344 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1345 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1346 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1347 "(u|uu)line|(s|x)out|uwave|"
1348 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1349 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1354 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1357 if (sub.str(1).compare("regexp") == 0) {
1361 string token = sub.str(1);
1363 if (regex_match(token, sub2, valid)) {
1371 if (sub.str(1).compare("endregexp") == 0) {
1381 * defines values features of a key "\\[a-z]+{"
1386 /* Char type with content discarded
1387 * like \hspace{1cm} */
1389 /* Char, like \backslash */
1391 /* replace starting backslash with '#' */
1393 /* \part, \section*, ... */
1395 /* title, author etc */
1397 /* \foreignlanguage{ngerman}, ... */
1400 * to discard language in content */
1403 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1405 /* fonts, colors, markups, ... */
1407 /* footnotesize, ... large, ...
1408 * Ignore all of them */
1411 /* inputencoding, ...
1412 * Discard also content, because they do not help in search */
1415 * like remove, but also all arguments */
1417 /* item, listitem */
1419 /* tex, latex, ... like isChar */
1421 /* like \lettrine[lines=5]{}{} */
1423 // like isStandard, but always remove head
1425 /* End of arguments marker for lettrine,
1426 * so that they can be ignored */
1429 KeyInfo() = default;
1430 KeyInfo(KeyType type, int parcount, bool disable)
1432 parenthesiscount(parcount),
1433 disabled(disable) {}
1434 KeyType keytype = invalid;
1436 int _tokensize = -1;
1437 int _tokenstart = -1;
1438 int _dataStart = -1;
1440 int parenthesiscount = 1;
1441 bool disabled = false;
1442 bool used = false; /* by pattern */
1447 Border(int l=0, int u=0) : low(l), upper(u) {}
1452 #define MAXOPENED 30
1454 bool isPatternString_;
1456 explicit Intervall(bool isPattern, string const & p)
1457 : isPatternString_(isPattern), par(p), ignoreidx(-1),
1458 actualdeptindex(0), hasTitle(false), langcount(0)
1466 static vector<Border> borders;
1467 static vector<int> depts;
1468 static vector<int> closes;
1469 int actualdeptindex;
1470 int previousNotIgnored(int) const;
1471 int nextNotIgnored(int) const;
1472 void handleOpenP(int i);
1473 void handleCloseP(int i, bool closingAllowed);
1474 void resetOpenedP(int openPos);
1475 void addIntervall(int upper);
1476 void addIntervall(int low, int upper); /* if explicit */
1477 void removeAccents();
1478 void setForDefaultLang(KeyInfo const & defLang) const;
1479 int findclosing(int start, int end, char up, char down, int repeat);
1480 void removeInvalidClosings(void);
1481 void handleParentheses(int lastpos, bool closingAllowed);
1483 // Number of disabled language specs up
1484 // to current position in actual interval
1486 int isOpeningPar(int pos) const;
1488 void output(ostringstream &os, int lastpos);
1489 // string show(int lastpos);
1492 vector<Border> Intervall::borders = vector<Border>(30);
1493 vector<int> Intervall::depts = vector<int>(30);
1494 vector<int> Intervall::closes = vector<int>(30);
1496 int Intervall::isOpeningPar(int pos) const
1498 if ((pos < 0) || (size_t(pos) >= par.size()))
1500 if (par[pos] != '{')
1502 if (size_t(pos) + 2 >= par.size())
1504 if (par[pos+2] != '}')
1506 if (par[pos+1] == '[' || par[pos+1] == ']')
1511 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1513 // Enable the use of first token again
1514 if (ignoreidx >= 0) {
1515 int value = defLang._tokenstart + defLang._tokensize;
1520 if (borders[borderidx].low < value)
1521 borders[borderidx].low = value;
1522 if (borders[borderidx].upper < value)
1523 borders[borderidx].upper = value;
1529 // Not needed, because dpts and closes are now dynamically expanded
1530 static void checkDepthIndex(int val)
1532 static int maxdepthidx = MAXOPENED-2;
1533 static int lastmaxdepth = 0;
1534 if (val > lastmaxdepth) {
1535 LYXERR(Debug::INFO, "Depth reached " << val);
1538 if (val > maxdepthidx) {
1540 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1546 // Not needed, because borders are now dynamically expanded
1547 static void checkIgnoreIdx(int val)
1549 static int lastmaxignore = -1;
1550 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1551 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1552 lastmaxignore = val;
1558 * Expand the region of ignored parts of the input latex string
1559 * The region is only relevant in output()
1561 void Intervall::addIntervall(int low, int upper)
1564 if (low == upper) return;
1565 for (idx = ignoreidx+1; idx > 0; --idx) {
1566 if (low > borders[idx-1].upper) {
1570 Border br(low, upper);
1571 if (idx > ignoreidx) {
1572 if (borders.size() <= size_t(idx)) {
1573 borders.push_back(br);
1579 // checkIgnoreIdx(ignoreidx);
1583 // Expand only if one of the new bound is inside the interwall
1584 // We know here that br.low > borders[idx-1].upper
1585 if (br.upper < borders[idx].low) {
1586 // We have to insert at this pos
1587 if (size_t(ignoreidx+1) >= borders.size()) {
1588 borders.push_back(borders[ignoreidx]);
1591 borders[ignoreidx+1] = borders[ignoreidx];
1593 for (int i = ignoreidx; i > idx; --i) {
1594 borders[i] = borders[i-1];
1598 // checkIgnoreIdx(ignoreidx);
1601 // Here we know, that we are overlapping
1602 if (br.low > borders[idx].low)
1603 br.low = borders[idx].low;
1604 // check what has to be concatenated
1606 for (int i = idx; i <= ignoreidx; i++) {
1607 if (br.upper >= borders[i].low) {
1609 if (br.upper < borders[i].upper)
1610 br.upper = borders[i].upper;
1616 // count should be >= 1 here
1619 for (int i = idx + count; i <= ignoreidx; i++) {
1620 borders[i-count+1] = borders[i];
1622 ignoreidx -= count - 1;
1628 static void buildaccent(string n, string param, string values)
1632 const char delim = '|';
1633 while (getline(s, name, delim)) {
1635 for (char c : param) {
1636 string key = name + "{" + c + "}";
1637 // get the corresponding utf8-value
1638 if ((values[start] & 0xc0) != 0xc0) {
1639 // should not happen, utf8 encoding starts at least with 11xxxxxx
1640 // but value for '\dot{i}' is 'i', which is ascii
1641 if ((values[start] & 0x80) == 0) {
1643 accents[key] = values.substr(start, 1);
1644 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1649 for (int j = 1; ;j++) {
1650 if (start + j >= values.size()) {
1651 accents[key] = values.substr(start, j);
1652 start = values.size() - 1;
1655 else if ((values[start+j] & 0xc0) != 0x80) {
1656 // This is the first byte of following utf8 char
1657 accents[key] = values.substr(start, j);
1659 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1668 static string getutf8(unsigned uchar)
1671 string ret = string();
1673 if (uchar <= 0x7f) {
1674 c[maxc-1] = uchar & 0x7f;
1677 unsigned char rest = 0x40;
1678 unsigned char first = 0x80;
1680 for (int i = start; i >=0; --i) {
1682 c[i] = first + uchar;
1685 c[i] = 0x80 | (uchar & 0x3f);
1692 for (int i = 0; i < maxc; i++) {
1693 if (c[i] == 0) continue;
1699 static void addAccents(string latex_in, string unicode_out)
1701 latex_in = latex_in.substr(1);
1702 AccentsIterator it_ac = accents.find(latex_in);
1703 if (it_ac == accents.end()) {
1704 accents[latex_in] = unicode_out;
1707 LYXERR0("Key " << latex_in << " already set");
1711 void static fillMissingUnicodesymbols()
1713 addAccents("\\pounds", getutf8(0x00a3));
1714 addAccents("\\textsterling", getutf8(0x00a3));
1715 addAccents("\\textyen", getutf8(0x00a5));
1716 addAccents("\\yen", getutf8(0x00a5));
1717 addAccents("\\textsection", getutf8(0x00a7));
1718 addAccents("\\mathsection", getutf8(0x00a7));
1719 addAccents("\\textcopyright", getutf8(0x00a9));
1720 addAccents("\\copyright", getutf8(0x00a9));
1721 addAccents("\\textlnot", getutf8(0x00ac));
1722 addAccents("\\neg", getutf8(0x00ac));
1723 addAccents("\\textregistered", getutf8(0x00ae));
1724 addAccents("\\circledR", getutf8(0x00ae));
1725 addAccents("\\textpm", getutf8(0x00b1));
1726 addAccents("\\pm", getutf8(0x00b1));
1727 addAccents("\\textparagraph", getutf8(0x00b6));
1728 addAccents("\\mathparagraph", getutf8(0x00b6));
1729 addAccents("\\textperiodcentered", getutf8(0x00b7));
1730 addAccents("\\texttimes", getutf8(0x00d7));
1731 addAccents("\\times", getutf8(0x00d7));
1732 addAccents("\\O", getutf8(0x00d8));
1733 addAccents("\\dh", getutf8(0x00f0));
1734 addAccents("\\eth", getutf8(0x00f0));
1735 addAccents("\\textdiv", getutf8(0x00f7));
1736 addAccents("\\div", getutf8(0x00f7));
1737 addAccents("\\o", getutf8(0x00f8));
1738 addAccents("\\textcrlambda", getutf8(0x019b));
1739 addAccents("\\j", getutf8(0x0237));
1740 addAccents("\\textrevepsilon", getutf8(0x025c));
1741 addAccents("\\textbaru", getutf8(0x0289));
1742 addAccents("\\textquoteleft", getutf8(0x02bb));
1743 addAccents("\\textGamma", getutf8(0x0393));
1744 addAccents("\\Gamma", getutf8(0x0393));
1745 addAccents("\\textDelta", getutf8(0x0394));
1746 addAccents("\\Delta", getutf8(0x0394));
1747 addAccents("\\textTheta", getutf8(0x0398));
1748 addAccents("\\Theta", getutf8(0x0398));
1749 addAccents("\\textLambda", getutf8(0x039b));
1750 addAccents("\\Lambda", getutf8(0x039b));
1751 addAccents("\\textXi", getutf8(0x039e));
1752 addAccents("\\Xi", getutf8(0x039e));
1753 addAccents("\\textPi", getutf8(0x03a0));
1754 addAccents("\\Pi", getutf8(0x03a0));
1755 addAccents("\\textSigma", getutf8(0x03a3));
1756 addAccents("\\Sigma", getutf8(0x03a3));
1757 addAccents("\\textUpsilon", getutf8(0x03a5));
1758 addAccents("\\Upsilon", getutf8(0x03a5));
1759 addAccents("\\textPhi", getutf8(0x03a6));
1760 addAccents("\\Phi", getutf8(0x03a6));
1761 addAccents("\\textPsi", getutf8(0x03a8));
1762 addAccents("\\Psi", getutf8(0x03a8));
1763 addAccents("\\textOmega", getutf8(0x03a9));
1764 addAccents("\\Omega", getutf8(0x03a9));
1765 addAccents("\\textalpha", getutf8(0x03b1));
1766 addAccents("\\alpha", getutf8(0x03b1));
1767 addAccents("\\textbeta", getutf8(0x03b2));
1768 addAccents("\\beta", getutf8(0x03b2));
1769 addAccents("\\textgamma", getutf8(0x03b3));
1770 addAccents("\\gamma", getutf8(0x03b3));
1771 addAccents("\\textdelta", getutf8(0x03b4));
1772 addAccents("\\delta", getutf8(0x03b4));
1773 addAccents("\\textepsilon", getutf8(0x03b5));
1774 addAccents("\\varepsilon", getutf8(0x03b5));
1775 addAccents("\\textzeta", getutf8(0x03b6));
1776 addAccents("\\zeta", getutf8(0x03b6));
1777 addAccents("\\texteta", getutf8(0x03b7));
1778 addAccents("\\eta", getutf8(0x03b7));
1779 addAccents("\\texttheta", getutf8(0x03b8));
1780 addAccents("\\theta", getutf8(0x03b8));
1781 addAccents("\\textiota", getutf8(0x03b9));
1782 addAccents("\\iota", getutf8(0x03b9));
1783 addAccents("\\textkappa", getutf8(0x03ba));
1784 addAccents("\\kappa", getutf8(0x03ba));
1785 addAccents("\\textlambda", getutf8(0x03bb));
1786 addAccents("\\lambda", getutf8(0x03bb));
1787 addAccents("\\textmu", getutf8(0x03bc));
1788 addAccents("\\mu", getutf8(0x03bc));
1789 addAccents("\\textnu", getutf8(0x03bd));
1790 addAccents("\\nu", getutf8(0x03bd));
1791 addAccents("\\textxi", getutf8(0x03be));
1792 addAccents("\\xi", getutf8(0x03be));
1793 addAccents("\\textpi", getutf8(0x03c0));
1794 addAccents("\\pi", getutf8(0x03c0));
1795 addAccents("\\textrho", getutf8(0x03c1));
1796 addAccents("\\rho", getutf8(0x03c1));
1797 addAccents("\\textfinalsigma", getutf8(0x03c2));
1798 addAccents("\\varsigma", getutf8(0x03c2));
1799 addAccents("\\textsigma", getutf8(0x03c3));
1800 addAccents("\\sigma", getutf8(0x03c3));
1801 addAccents("\\texttau", getutf8(0x03c4));
1802 addAccents("\\tau", getutf8(0x03c4));
1803 addAccents("\\textupsilon", getutf8(0x03c5));
1804 addAccents("\\upsilon", getutf8(0x03c5));
1805 addAccents("\\textphi", getutf8(0x03c6));
1806 addAccents("\\varphi", getutf8(0x03c6));
1807 addAccents("\\textchi", getutf8(0x03c7));
1808 addAccents("\\chi", getutf8(0x03c7));
1809 addAccents("\\textpsi", getutf8(0x03c8));
1810 addAccents("\\psi", getutf8(0x03c8));
1811 addAccents("\\textomega", getutf8(0x03c9));
1812 addAccents("\\omega", getutf8(0x03c9));
1813 addAccents("\\textdigamma", getutf8(0x03dd));
1814 addAccents("\\digamma", getutf8(0x03dd));
1815 addAccents("\\hebalef", getutf8(0x05d0));
1816 addAccents("\\aleph", getutf8(0x05d0));
1817 addAccents("\\hebbet", getutf8(0x05d1));
1818 addAccents("\\beth", getutf8(0x05d1));
1819 addAccents("\\hebgimel", getutf8(0x05d2));
1820 addAccents("\\gimel", getutf8(0x05d2));
1821 addAccents("\\hebdalet", getutf8(0x05d3));
1822 addAccents("\\daleth", getutf8(0x05d3));
1823 addAccents("\\hebhe", getutf8(0x05d4));
1824 addAccents("\\hebvav", getutf8(0x05d5));
1825 addAccents("\\hebzayin", getutf8(0x05d6));
1826 addAccents("\\hebhet", getutf8(0x05d7));
1827 addAccents("\\hebtet", getutf8(0x05d8));
1828 addAccents("\\hebyod", getutf8(0x05d9));
1829 addAccents("\\hebfinalkaf", getutf8(0x05da));
1830 addAccents("\\hebkaf", getutf8(0x05db));
1831 addAccents("\\heblamed", getutf8(0x05dc));
1832 addAccents("\\hebfinalmem", getutf8(0x05dd));
1833 addAccents("\\hebmem", getutf8(0x05de));
1834 addAccents("\\hebfinalnun", getutf8(0x05df));
1835 addAccents("\\hebnun", getutf8(0x05e0));
1836 addAccents("\\hebsamekh", getutf8(0x05e1));
1837 addAccents("\\hebayin", getutf8(0x05e2));
1838 addAccents("\\hebfinalpe", getutf8(0x05e3));
1839 addAccents("\\hebpe", getutf8(0x05e4));
1840 addAccents("\\hebfinaltsadi", getutf8(0x05e5));
1841 addAccents("\\hebtsadi", getutf8(0x05e6));
1842 addAccents("\\hebqof", getutf8(0x05e7));
1843 addAccents("\\hebresh", getutf8(0x05e8));
1844 addAccents("\\hebshin", getutf8(0x05e9));
1845 addAccents("\\hebtav", getutf8(0x05ea));
1848 addAccents("\\thaiKoKai", getutf8(0x0e01));
1849 addAccents("\\thaiKhoKhai", getutf8(0x0e02));
1850 addAccents("\\thaiKhoKhuat", getutf8(0x0e03));
1851 addAccents("\\thaiKhoKhwai", getutf8(0x0e04));
1852 addAccents("\\thaiKhoKhon", getutf8(0x0e05));
1853 addAccents("\\thaiKhoRakhang", getutf8(0x0e06));
1854 addAccents("\\thaiNgoNgu", getutf8(0x0e07));
1855 addAccents("\\thaiChoChan", getutf8(0x0e08));
1856 addAccents("\\thaiChoChing", getutf8(0x0e09));
1857 addAccents("\\thaiChoChang", getutf8(0x0e0a));
1858 addAccents("\\thaiSoSo", getutf8(0x0e0b));
1859 addAccents("\\thaiChoChoe", getutf8(0x0e0c));
1860 addAccents("\\thaiYoYing", getutf8(0x0e0d));
1861 addAccents("\\thaiDoChada", getutf8(0x0e0e));
1862 addAccents("\\thaiToPatak", getutf8(0x0e0f));
1863 addAccents("\\thaiThoThan", getutf8(0x0e10));
1864 addAccents("\\thaiThoNangmontho", getutf8(0x0e11));
1865 addAccents("\\thaiThoPhuthao", getutf8(0x0e12));
1866 addAccents("\\thaiNoNen", getutf8(0x0e13));
1867 addAccents("\\thaiDoDek", getutf8(0x0e14));
1868 addAccents("\\thaiToTao", getutf8(0x0e15));
1869 addAccents("\\thaiThoThung", getutf8(0x0e16));
1870 addAccents("\\thaiThoThahan", getutf8(0x0e17));
1871 addAccents("\\thaiThoThong", getutf8(0x0e18));
1872 addAccents("\\thaiNoNu", getutf8(0x0e19));
1873 addAccents("\\thaiBoBaimai", getutf8(0x0e1a));
1874 addAccents("\\thaiPoPla", getutf8(0x0e1b));
1875 addAccents("\\thaiPhoPhung", getutf8(0x0e1c));
1876 addAccents("\\thaiFoFa", getutf8(0x0e1d));
1877 addAccents("\\thaiPhoPhan", getutf8(0x0e1e));
1878 addAccents("\\thaiFoFan", getutf8(0x0e1f));
1879 addAccents("\\thaiPhoSamphao", getutf8(0x0e20));
1880 addAccents("\\thaiMoMa", getutf8(0x0e21));
1881 addAccents("\\thaiYoYak", getutf8(0x0e22));
1882 addAccents("\\thaiRoRua", getutf8(0x0e23));
1883 addAccents("\\thaiRu", getutf8(0x0e24));
1884 addAccents("\\thaiLoLing", getutf8(0x0e25));
1885 addAccents("\\thaiLu", getutf8(0x0e26));
1886 addAccents("\\thaiWoWaen", getutf8(0x0e27));
1887 addAccents("\\thaiSoSala", getutf8(0x0e28));
1888 addAccents("\\thaiSoRusi", getutf8(0x0e29));
1889 addAccents("\\thaiSoSua", getutf8(0x0e2a));
1890 addAccents("\\thaiHoHip", getutf8(0x0e2b));
1891 addAccents("\\thaiLoChula", getutf8(0x0e2c));
1892 addAccents("\\thaiOAng", getutf8(0x0e2d));
1893 addAccents("\\thaiHoNokhuk", getutf8(0x0e2e));
1894 addAccents("\\thaiPaiyannoi", getutf8(0x0e2f));
1895 addAccents("\\thaiSaraA", getutf8(0x0e30));
1896 addAccents("\\thaiMaiHanakat", getutf8(0x0e31));
1897 addAccents("\\thaiSaraAa", getutf8(0x0e32));
1898 addAccents("\\thaiSaraAm", getutf8(0x0e33));
1899 addAccents("\\thaiSaraI", getutf8(0x0e34));
1900 addAccents("\\thaiSaraIi", getutf8(0x0e35));
1901 addAccents("\\thaiSaraUe", getutf8(0x0e36));
1902 addAccents("\\thaiSaraUee", getutf8(0x0e37));
1903 addAccents("\\thaiSaraU", getutf8(0x0e38));
1904 addAccents("\\thaiSaraUu", getutf8(0x0e39));
1905 addAccents("\\thaiPhinthu", getutf8(0x0e3a));
1906 addAccents("\\thaiSaraE", getutf8(0x0e40));
1907 addAccents("\\thaiSaraAe", getutf8(0x0e41));
1908 addAccents("\\thaiSaraO", getutf8(0x0e42));
1909 addAccents("\\thaiSaraAiMaimuan", getutf8(0x0e43));
1910 addAccents("\\thaiSaraAiMaimalai", getutf8(0x0e44));
1911 addAccents("\\thaiLakkhangyao", getutf8(0x0e45));
1912 addAccents("\\thaiMaiyamok", getutf8(0x0e46));
1913 addAccents("\\thaiMaitaikhu", getutf8(0x0e47));
1914 addAccents("\\thaiMaiEk", getutf8(0x0e48));
1915 addAccents("\\thaiMaiTho", getutf8(0x0e49));
1916 addAccents("\\thaiMaiTri", getutf8(0x0e4a));
1917 addAccents("\\thaiMaiChattawa", getutf8(0x0e4b));
1918 addAccents("\\thaiThanthakhat", getutf8(0x0e4c));
1919 addAccents("\\thaiNikhahit", getutf8(0x0e4d));
1920 addAccents("\\thaiYamakkan", getutf8(0x0e4e));
1921 addAccents("\\thaiFongman", getutf8(0x0e4f));
1922 addAccents("\\thaizero", getutf8(0x0e50));
1923 addAccents("\\thaione", getutf8(0x0e51));
1924 addAccents("\\thaitwo", getutf8(0x0e52));
1925 addAccents("\\thaithree", getutf8(0x0e53));
1926 addAccents("\\thaifour", getutf8(0x0e54));
1927 addAccents("\\thaifive", getutf8(0x0e55));
1928 addAccents("\\thaisix", getutf8(0x0e56));
1929 addAccents("\\thaiseven", getutf8(0x0e57));
1930 addAccents("\\thaieight", getutf8(0x0e58));
1931 addAccents("\\thainine", getutf8(0x0e59));
1932 addAccents("\\thaiAngkhankhu", getutf8(0x0e5a));
1933 addAccents("\\thaiKhomut", getutf8(0x0e5b));
1934 addAccents("\\dag", getutf8(0x2020));
1935 addAccents("\\dagger", getutf8(0x2020));
1936 addAccents("\\textdagger", getutf8(0x2020));
1937 addAccents("\\ddag", getutf8(0x2021));
1938 addAccents("\\ddagger", getutf8(0x2021));
1939 addAccents("\\textdaggerdbl", getutf8(0x2021));
1940 addAccents("\\textbullet", getutf8(0x2022));
1941 addAccents("\\bullet", getutf8(0x2022));
1942 addAccents("\\dots", getutf8(0x2026));
1943 addAccents("\\ldots", getutf8(0x2026));
1944 addAccents("\\textellipsis", getutf8(0x2026));
1945 addAccents("\\textasciiacute", getutf8(0x2032));
1946 addAccents("\\prime", getutf8(0x2032));
1947 addAccents("\\textacutedbl", getutf8(0x2033));
1948 addAccents("\\dprime", getutf8(0x2033));
1949 addAccents("\\textasciigrave", getutf8(0x2035));
1950 addAccents("\\backprime", getutf8(0x2035));
1951 addAccents("\\textsubcircum{ }", getutf8(0x2038));
1952 addAccents("\\caretinsert", getutf8(0x2038));
1953 addAccents("\\textasteriskcentered", getutf8(0x204e));
1954 addAccents("\\ast", getutf8(0x204e));
1955 addAccents("\\textmho", getutf8(0x2127));
1956 addAccents("\\mho", getutf8(0x2127));
1957 addAccents("\\textleftarrow", getutf8(0x2190));
1958 addAccents("\\leftarrow", getutf8(0x2190));
1959 addAccents("\\textuparrow", getutf8(0x2191));
1960 addAccents("\\uparrow", getutf8(0x2191));
1961 addAccents("\\textrightarrow", getutf8(0x2192));
1962 addAccents("\\rightarrow", getutf8(0x2192));
1963 addAccents("\\textdownarrow", getutf8(0x2193));
1964 addAccents("\\downarrow", getutf8(0x2193));
1965 addAccents("\\textglobrise", getutf8(0x2197));
1966 addAccents("\\nearrow", getutf8(0x2197));
1967 addAccents("\\textglobfall", getutf8(0x2198));
1968 addAccents("\\searrow", getutf8(0x2198));
1969 addAccents("\\textsurd", getutf8(0x221a));
1970 addAccents("\\surd", getutf8(0x221a));
1971 addAccents("\\textbigcircle", getutf8(0x25ef));
1972 addAccents("\\bigcirc", getutf8(0x25ef));
1973 addAccents("\\FiveStar", getutf8(0x2605));
1974 addAccents("\\bigstar", getutf8(0x2605));
1975 addAccents("\\FiveStarOpen", getutf8(0x2606));
1976 addAccents("\\bigwhitestar", getutf8(0x2606));
1977 addAccents("\\Checkmark", getutf8(0x2713));
1978 addAccents("\\checkmark", getutf8(0x2713));
1979 addAccents("\\CrossMaltese", getutf8(0x2720));
1980 addAccents("\\maltese", getutf8(0x2720));
1981 addAccents("\\textlangle", getutf8(0x27e8));
1982 addAccents("\\langle", getutf8(0x27e8));
1983 addAccents("\\textrangle", getutf8(0x27e9));
1984 addAccents("\\rangle", getutf8(0x27e9));
1987 static void buildAccentsMap()
1989 accents["imath"] = "ı";
1991 accents["jmath"] = "ȷ";
1992 accents["cdot"] = "·";
1993 accents["textasciicircum"] = "^";
1994 accents["mathcircumflex"] = "^";
1995 accents["guillemotright"] = "»";
1996 accents["guillemotleft"] = "«";
1997 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1998 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1999 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
2000 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
2001 accents["negmedspace"] = getutf8(0xf0005);
2002 accents["thickspace"] = getutf8(0xf0006);
2003 accents["negthickspace"] = getutf8(0xf0007);
2004 accents["lyx"] = getutf8(0xf0010); // Used logos
2005 accents["LyX"] = getutf8(0xf0010);
2006 accents["tex"] = getutf8(0xf0011);
2007 accents["TeX"] = getutf8(0xf0011);
2008 accents["latex"] = getutf8(0xf0012);
2009 accents["LaTeX"] = getutf8(0xf0012);
2010 accents["latexe"] = getutf8(0xf0013);
2011 accents["LaTeXe"] = getutf8(0xf0013);
2012 accents["lyxarrow"] = getutf8(0xf0020);
2013 accents["braceleft"] = getutf8(0xf0030);
2014 accents["braceright"] = getutf8(0xf0031);
2015 accents["lyxtilde"] = getutf8(0xf0032);
2016 accents["sim"] = getutf8(0xf0032);
2017 accents["lyxdollar"] = getutf8(0xf0033);
2018 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
2019 accents["backslash LyX"] = getutf8(0xf0010);
2020 accents["backslash tex"] = getutf8(0xf0011);
2021 accents["backslash TeX"] = getutf8(0xf0011);
2022 accents["backslash latex"] = getutf8(0xf0012);
2023 accents["backslash LaTeX"] = getutf8(0xf0012);
2024 accents["backslash latexe"] = getutf8(0xf0013);
2025 accents["backslash LaTeXe"] = getutf8(0xf0013);
2026 accents["backslash lyxarrow"] = getutf8(0xf0020);
2027 accents["ddot{\\imath}"] = "ï";
2028 buildaccent("ddot", "aAeEhHiIoOtuUwWxXyY",
2029 "äÄëËḧḦïÏöÖẗüÜẅẄẍẌÿŸ"); // umlaut
2030 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
2031 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
2032 accents["acute{\\imath}"] = "í";
2033 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
2034 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
2035 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
2036 buildaccent("mathring|r", "aAuUwy",
2038 accents["check{\\imath}"] = "ǐ";
2039 accents["check{\\jmath}"] = "ǰ";
2040 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
2041 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
2042 accents["hat{\\imath}"] = "î";
2043 accents["hat{\\jmath}"] = "ĵ";
2044 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
2045 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
2046 accents["bar{\\imath}"] = "ī";
2047 buildaccent("bar|=", "aAeEiIoOuUyY",
2048 "āĀēĒīĪōŌūŪȳȲ"); // macron
2049 accents["tilde{\\imath}"] = "ĩ";
2050 buildaccent("tilde", "aAeEiInNoOuUvVyY",
2051 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
2052 accents["breve{\\imath}"] = "ĭ";
2053 buildaccent("breve|u", "aAeEgGiIoOuU",
2054 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
2055 accents["grave{\\imath}"] = "ì";
2056 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
2057 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
2058 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
2059 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
2060 buildaccent("ogonek|k", "AaEeIiUuOo",
2061 "ĄąĘęĮįŲųǪǫ"); // ogonek
2062 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
2063 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
2064 buildaccent("subring|textsubring", "Aa",
2066 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
2067 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
2068 buildaccent("subtilde|textsubtilde", "EeIiUu",
2069 "ḚḛḬḭṴṵ"); // subtilde
2070 accents["dgrave{\\imath}"] = "ȉ";
2071 accents["textdoublegrave{\\i}"] = "ȉ";
2072 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
2073 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
2074 accents["rcap{\\imath}"] = "ȋ";
2075 accents["textroundcap{\\i}"] = "ȋ";
2076 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
2077 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
2078 buildaccent("slashed", "oO",
2080 fillMissingUnicodesymbols(); // Add some still not handled entries contained in 'unicodesynbols'
2081 // LYXERR0("Number of accents " << accents.size());
2085 * Created accents in math or regexp environment
2086 * are macros, but we need the utf8 equivalent
2088 void Intervall::removeAccents()
2090 if (accents.empty())
2092 static regex const accre("\\\\("
2093 "([\\S]|[A-Za-z]+)\\{[^\\\\\\{\\}]+\\}"
2094 "|([\\S]|[A-Za-z]+)\\{\\\\[ij](math)?\\}"
2096 "(backslash ([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))"
2101 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
2103 string key = sub.str(1);
2104 AccentsIterator it_ac = accents.find(key);
2105 if (it_ac != accents.end()) {
2106 string val = it_ac->second;
2107 size_t pos = sub.position(size_t(0));
2108 for (size_t i = 0; i < val.size(); i++) {
2109 par[pos+i] = val[i];
2111 // Remove possibly following space too
2112 if (par[pos+sub.str(0).size()] == ' ')
2113 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
2115 addIntervall(pos+val.size(), pos + sub.str(0).size());
2116 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
2117 // remove traces of any remaining chars
2122 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
2127 void Intervall::handleOpenP(int i)
2130 if ((size_t) actualdeptindex >= depts.size()) {
2131 depts.resize(actualdeptindex + 30);
2132 closes.resize(actualdeptindex + 30);
2134 depts[actualdeptindex] = i+1;
2135 closes[actualdeptindex] = -1;
2136 // checkDepthIndex(actualdeptindex);
2139 void Intervall::handleCloseP(int i, bool closingAllowed)
2141 if (actualdeptindex <= 0) {
2142 if (! closingAllowed)
2143 LYXERR(Debug::FINDVERBOSE, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
2144 // if we are at the very end
2145 addIntervall(i, i+1);
2148 closes[actualdeptindex] = i+1;
2153 void Intervall::resetOpenedP(int openPos)
2155 // Used as initializer for foreignlanguage entry
2156 actualdeptindex = 1;
2157 depts[1] = openPos+1;
2161 int Intervall::previousNotIgnored(int start) const
2163 int idx = 0; /* int intervalls */
2164 for (idx = ignoreidx; idx >= 0; --idx) {
2165 if (start > borders[idx].upper)
2167 if (start >= borders[idx].low)
2168 start = borders[idx].low-1;
2173 int Intervall::nextNotIgnored(int start) const
2175 int idx = 0; /* int intervalls */
2176 for (idx = 0; idx <= ignoreidx; idx++) {
2177 if (start < borders[idx].low)
2179 if (start < borders[idx].upper)
2180 start = borders[idx].upper;
2185 typedef unordered_map<string, KeyInfo> KeysMap;
2186 typedef unordered_map<string, KeyInfo>::const_iterator KeysIterator;
2187 typedef vector< KeyInfo> Entries;
2188 static KeysMap keys = unordered_map<string, KeyInfo>();
2194 Intervall interval_;
2195 void buildKeys(bool);
2196 void buildEntries(bool);
2197 void makeKey(const string &, KeyInfo, bool isPatternString);
2198 void processRegion(int start, int region_end); /* remove {} parts */
2199 void removeHead(KeyInfo const &, int count=0);
2202 LatexInfo(string const & par, bool isPatternString)
2203 : entidx_(-1), interval_(isPatternString, par)
2205 buildKeys(isPatternString);
2206 entries_ = vector<KeyInfo>();
2207 buildEntries(isPatternString);
2211 if (entries_.empty()) {
2214 if (entries_[0].keytype == KeyInfo::isTitle) {
2215 interval_.hasTitle = true;
2216 if (! entries_[0].disabled) {
2217 interval_.titleValue = entries_[0].head;
2220 interval_.titleValue = "";
2222 removeHead(entries_[0]);
2223 if (entries_.size() > 1)
2232 if (int(entries_.size()) > entidx_) {
2239 bool setNextKey(int idx) {
2240 if ((idx == entidx_) && (entidx_ >= 0)) {
2247 int find(int start, KeyInfo::KeyType keytype) const {
2251 while (tmpIdx < int(entries_.size())) {
2252 if (entries_[tmpIdx].keytype == keytype)
2258 int process(ostringstream & os, KeyInfo const & actual);
2259 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
2260 // string show(int lastpos) { return interval.show(lastpos);}
2261 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);}
2262 KeyInfo &getKeyInfo(int keyinfo) {
2263 static KeyInfo invalidInfo = KeyInfo();
2264 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
2267 return entries_[keyinfo];
2269 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);}
2270 void addIntervall(int low, int up) { interval_.addIntervall(low, up); }
2274 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
2278 for (int i = start; i < end; i += 1 + skip) {
2282 if (c == '\\') skip = 1;
2286 else if (c == down) {
2289 if ((repeat <= 0) || (par[i+1] != up))
2298 void Intervall::removeInvalidClosings(void)
2300 // this can happen, if there are deleted parts
2303 for (unsigned i = 0; i < par.size(); i += 1 + skip) {
2306 if (c == '\\') skip = 1;
2309 else if (c == '}') {
2311 addIntervall(i, i+1);
2312 LYXERR(Debug::FINDVERBOSE, "removed invalid closing '}' at " << i);
2324 size_t mathpostfixsize;
2326 size_t mathprefixsize;
2330 vector<MathEntry> entries_;
2335 void insert(string const & wait, size_t start, size_t prefixsize, size_t end, size_t postfixsize) {
2336 MathEntry m = MathEntry();
2338 m.mathStart = start;
2339 m.mathprefixsize = prefixsize;
2340 m.mathEnd = end + postfixsize;
2341 m.mathpostfixsize = postfixsize;
2342 m.mathSize = m.mathEnd - m.mathStart;
2343 entries_.push_back(m);
2345 bool empty() const { return entries_.empty(); }
2346 size_t getEndPos() const {
2347 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2350 return entries_[actualIdx_].mathEnd;
2352 size_t getStartPos() const {
2353 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2354 return 100000; /* definitely enough? */
2356 return entries_[actualIdx_].mathStart;
2358 size_t getPrefixSize() const {
2359 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2362 return entries_[actualIdx_].mathprefixsize;
2364 size_t getPostfixSize() const {
2365 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2368 return entries_[actualIdx_].mathpostfixsize;
2370 size_t getFirstPos() {
2372 return getStartPos();
2374 size_t getSize() const {
2375 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
2378 return entries_[actualIdx_].mathSize;
2380 void incrEntry() { actualIdx_++; }
2383 void LatexInfo::buildEntries(bool isPatternString)
2385 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|x?x?alignat)\\*?\\})(\\{[0-9]+\\})?)");
2386 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
2387 static bool disableLanguageOverride = false;
2388 smatch sub, submath;
2389 bool evaluatingRegexp = false;
2391 bool evaluatingMath = false;
2392 bool evaluatingCode = false;
2394 bool evaluatingOptional = false;
2395 size_t optionalEnd = 0;
2398 bool math_end_waiting = false;
2399 size_t math_pos = 10000;
2400 size_t math_prefix_size = 1;
2402 static vector<string> usedText = vector<string>();
2403 static bool removeMathHull = false;
2405 interval_.removeAccents();
2406 interval_.removeInvalidClosings();
2408 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
2410 if ((submath.position(2) - submath.position(0)) %2 == 1) {
2411 // prefixed by odd count of '\\'
2414 if (math_end_waiting) {
2415 size_t pos = submath.position(size_t(2));
2416 if ((math_end == "$") &&
2417 (submath.str(2) == "$")) {
2418 mi.insert("$", math_pos, 1, pos, 1);
2419 math_end_waiting = false;
2421 else if ((math_end == "\\]") &&
2422 (submath.str(2) == "\\]")) {
2423 mi.insert("\\]", math_pos, 2, pos, 2);
2424 math_end_waiting = false;
2426 else if ((submath.str(3).compare("end") == 0) &&
2427 (submath.str(5).compare(math_end) == 0)) {
2428 mi.insert(math_end, math_pos, math_prefix_size, pos, submath.str(2).length());
2429 math_end_waiting = false;
2435 if (submath.str(3).compare("begin") == 0) {
2436 math_end_waiting = true;
2437 math_end = submath.str(5);
2438 math_pos = submath.position(size_t(2));
2439 math_prefix_size = submath.str(2).length();
2441 else if (submath.str(2).compare("\\[") == 0) {
2442 math_end_waiting = true;
2444 math_pos = submath.position(size_t(2));
2446 else if (submath.str(2) == "$") {
2447 size_t pos = submath.position(size_t(2));
2448 math_end_waiting = true;
2454 // Ignore language if there is math somewhere in pattern-string
2455 if (isPatternString) {
2456 for (auto const & s: usedText) {
2457 // Remove entries created in previous search runs
2460 usedText = vector<string>();
2463 keys["foreignlanguage"].disabled = true;
2464 disableLanguageOverride = true;
2465 removeMathHull = false;
2468 removeMathHull = true; // used later if not isPatternString
2469 disableLanguageOverride = false;
2473 if (disableLanguageOverride) {
2474 keys["foreignlanguage"].disabled = true;
2477 math_pos = mi.getFirstPos();
2478 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
2480 if ((sub.position(2) - sub.position(0)) %2 == 1) {
2481 // prefixed by odd count of '\\'
2484 string key = sub.str(5);
2486 if (sub.str(2)[0] == '\\')
2487 key = sub.str(2)[1];
2492 KeysIterator it_key = keys.find(key);
2493 if (it_key != keys.end()) {
2494 if (it_key->second.keytype == KeyInfo::headRemove) {
2495 KeyInfo found1 = it_key->second;
2496 found1.disabled = true;
2497 found1.head = "\\" + key + "{";
2498 found1._tokenstart = sub.position(size_t(2));
2499 found1._tokensize = found1.head.length();
2500 found1._dataStart = found1._tokenstart + found1.head.length();
2501 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
2502 found1._dataEnd = endpos;
2507 if (evaluatingRegexp) {
2508 if (sub.str(3).compare("endregexp") == 0) {
2509 evaluatingRegexp = false;
2510 // found._tokenstart already set
2511 found._dataEnd = sub.position(size_t(2)) + 13;
2512 found._dataStart = found._dataEnd;
2513 found._tokensize = found._dataEnd - found._tokenstart;
2514 found.parenthesiscount = 0;
2515 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2522 if (evaluatingMath) {
2523 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
2525 evaluatingMath = false;
2527 math_pos = mi.getStartPos();
2529 if (it_key == keys.end()) {
2530 found = KeyInfo(KeyInfo::isStandard, 0, true);
2531 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
2532 found = KeyInfo(KeyInfo::isText, 0, false);
2533 if (isPatternString) {
2534 found.keytype = KeyInfo::isChar;
2535 found.disabled = false;
2539 usedText.push_back(key);
2543 if (key.compare("regexp") == 0) {
2544 evaluatingRegexp = true;
2545 found._tokenstart = sub.position(size_t(2));
2546 found._tokensize = 0;
2550 // Handle the other params of key
2551 if (found.keytype == KeyInfo::isIgnored)
2553 else if (found.keytype == KeyInfo::isMath) {
2554 if (size_t(sub.position(size_t(2))) == math_pos) {
2556 found._tokenstart = sub.position(size_t(2));
2557 found._tokensize = mi.getSize();
2558 found._dataEnd = found._tokenstart + found._tokensize;
2559 found._dataStart = found._dataEnd;
2560 found.parenthesiscount = 0;
2561 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2562 if (removeMathHull) {
2563 interval_.addIntervall(found._tokenstart, found._tokenstart + mi.getPrefixSize());
2564 interval_.addIntervall(found._dataEnd - mi.getPostfixSize(), found._dataEnd);
2567 // Treate all math constructs as simple math
2568 interval_.par[found._tokenstart] = '$';
2569 interval_.par[found._dataEnd - mi.getPostfixSize()] = '$';
2570 interval_.addIntervall(found._tokenstart + 1, found._tokenstart + mi.getPrefixSize());
2571 interval_.addIntervall(found._dataEnd - mi.getPostfixSize() + 1, found._dataEnd);
2573 evaluatingMath = true;
2576 // begin|end of unknown env, discard
2577 // First handle tables
2578 // longtable|tabular
2579 bool discardComment;
2581 found.keytype = KeyInfo::doRemove;
2582 if ((sub.str(7).compare("longtable") == 0) ||
2583 (sub.str(7).compare("tabular") == 0)) {
2584 discardComment = true; /* '%' */
2587 discardComment = false;
2588 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
2590 string token = sub.str(7);
2591 if (regex_match(token, sub2, removeArgs)) {
2592 found.keytype = KeyInfo::removeWithArg;
2595 // discard spaces before pos(2)
2596 int pos = sub.position(size_t(2));
2598 for (count = 0; pos - count > 0; count++) {
2599 char c = interval_.par[pos-count-1];
2600 if (discardComment) {
2601 if ((c != ' ') && (c != '%'))
2607 found._tokenstart = pos - count;
2608 if (sub.str(3).compare(0, 5, "begin") == 0) {
2609 size_t pos1 = pos + sub.str(2).length();
2610 if (sub.str(7).compare("cjk") == 0) {
2611 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2612 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
2614 found.keytype = KeyInfo::isMain;
2615 found._dataStart = pos1;
2616 found._dataEnd = interval_.par.length();
2617 found.disabled = keys["foreignlanguage"].disabled;
2618 found.used = keys["foreignlanguage"].used;
2619 found._tokensize = pos1 - found._tokenstart;
2620 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2623 // Swallow possible optional params
2624 while (interval_.par[pos1] == '[') {
2625 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
2627 // Swallow also the eventual parameter
2628 if (interval_.par[pos1] == '{') {
2629 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
2632 found._dataEnd = pos1;
2634 found._dataStart = found._dataEnd;
2635 found._tokensize = count + found._dataEnd - pos;
2636 found.parenthesiscount = 0;
2637 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2638 found.disabled = true;
2642 // Handle "\end{...}"
2643 found._dataStart = pos + sub.str(2).length();
2644 found._dataEnd = found._dataStart;
2645 found._tokensize = count + found._dataEnd - pos;
2646 found.parenthesiscount = 0;
2647 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2648 found.disabled = true;
2652 else if (found.keytype != KeyInfo::isRegex) {
2653 found._tokenstart = sub.position(size_t(2));
2654 if (found.parenthesiscount == 0) {
2655 // Probably to be discarded
2656 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2657 char following = interval_.par[following_pos];
2658 if (following == ' ')
2659 found.head = "\\" + sub.str(5) + " ";
2660 else if (following == '=') {
2661 // like \uldepth=1000pt
2662 found.head = sub.str(2);
2665 found.head = "\\" + key;
2666 found._tokensize = found.head.length();
2667 found._dataEnd = found._tokenstart + found._tokensize;
2668 found._dataStart = found._dataEnd;
2671 int params = found._tokenstart + key.length() + 1;
2672 if (evaluatingOptional) {
2673 if (size_t(found._tokenstart) > optionalEnd) {
2674 evaluatingOptional = false;
2677 found.disabled = true;
2680 int optend = params;
2681 while (interval_.par[optend] == '[') {
2682 // discard optional parameters
2683 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2685 if (optend > params) {
2686 key += interval_.par.substr(params, optend-params);
2687 evaluatingOptional = true;
2688 optionalEnd = optend;
2689 if (found.keytype == KeyInfo::isSectioning) {
2690 // Remove optional values (but still keep in header)
2691 interval_.addIntervall(params, optend);
2694 string token = sub.str(7);
2696 if (interval_.par[optend] != '{') {
2698 found.parenthesiscount = 0;
2699 found.head = "\\" + key;
2702 closings = found.parenthesiscount;
2703 if (found.parenthesiscount == 1) {
2704 found.head = "\\" + key + "{";
2706 else if (found.parenthesiscount > 1) {
2708 found.head = sub.str(2) + "{";
2709 closings = found.parenthesiscount - 1;
2712 found.head = "\\" + key + "{";
2715 found._tokensize = found.head.length();
2716 found._dataStart = found._tokenstart + found.head.length();
2717 if (found.keytype == KeyInfo::doRemove) {
2719 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2720 if (endpar >= interval_.par.length())
2721 found._dataStart = interval_.par.length();
2723 found._dataStart = endpar;
2724 found._tokensize = found._dataStart - found._tokenstart;
2727 found._dataStart = found._tokenstart + found._tokensize;
2731 if (interval_.par.substr(found._dataStart, 15).compare("\\endarguments{}") == 0) {
2732 found._dataStart += 15;
2736 endpos = found._dataStart - 1;
2738 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2739 if (found.keytype == KeyInfo::isList) {
2740 // Check if it really is list env
2741 static regex const listre("^([a-z]+)$");
2743 if (!regex_match(token, sub2, listre)) {
2744 // Change the key of this entry. It is not in a list/item environment
2745 found.keytype = KeyInfo::endArguments;
2748 if (found.keytype == KeyInfo::noMain) {
2749 evaluatingCode = true;
2751 codeStart = found._dataStart;
2753 else if (evaluatingCode) {
2754 if (size_t(found._dataStart) > codeEnd)
2755 evaluatingCode = false;
2756 else if (found.keytype == KeyInfo::isMain) {
2757 // Disable this key, treate it as standard
2758 found.keytype = KeyInfo::isStandard;
2759 found.disabled = true;
2760 if ((codeEnd +1 >= interval_.par.length()) &&
2761 (found._tokenstart == codeStart)) {
2762 // trickery, because the code inset starts
2763 // with \selectlanguage ...
2765 if (entries_.size() > 1) {
2766 entries_[entries_.size()-1]._dataEnd = codeEnd;
2771 if ((endpos == interval_.par.length()) &&
2772 (found.keytype == KeyInfo::doRemove)) {
2773 // Missing closing => error in latex-input?
2774 // therefore do not delete remaining data
2775 found._dataStart -= 1;
2776 found._dataEnd = found._dataStart;
2779 found._dataEnd = endpos;
2781 if (isPatternString) {
2782 keys[key].used = true;
2785 entries_.push_back(found);
2789 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2791 stringstream s(keysstring);
2793 const char delim = '|';
2794 while (getline(s, key, delim)) {
2795 KeyInfo keyII(keyI);
2796 if (isPatternString) {
2799 else if ( !keys[key].used)
2800 keyII.disabled = true;
2805 void LatexInfo::buildKeys(bool isPatternString)
2808 static bool keysBuilt = false;
2809 if (keysBuilt && !isPatternString) return;
2811 // Keys to ignore in any case
2812 makeKey("text|lyxmathsym|ensuremath", KeyInfo(KeyInfo::headRemove, 1, true), true);
2813 makeKey("nonumber|notag", KeyInfo(KeyInfo::headRemove, 0, true), true);
2814 // Known standard keys with 1 parameter.
2815 // Split is done, if not at start of region
2816 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2817 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2818 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2819 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2820 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2821 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2823 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2824 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2825 makeKey("section*|subsection*|subsubsection*|paragraph*",
2826 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2827 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2828 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2830 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2832 // Split is done, if not at start of region
2833 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2834 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2836 // Split is done always.
2837 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2841 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2842 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2843 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2844 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2846 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2847 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2848 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2849 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2851 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2852 // Custom space/skip, remove the content (== length value)
2853 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2854 // Found in fr/UserGuide.lyx
2855 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2857 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2858 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2859 // Known macros to remove (including their parameter)
2861 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2862 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2863 // handle like standard keys with 1 parameter.
2864 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2866 if (ignoreFormats.getDeleted()) {
2867 // Ignore deleted text
2868 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2871 // but preserve added text
2872 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2874 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2876 // Macros to remove, but let the parameter survive
2878 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2880 // Remove language spec from content of these insets
2881 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2883 // Same effect as previous, parameter will survive (because there is no one anyway)
2885 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2886 // Remove table decorations
2887 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2888 // Discard shape-header.
2889 // For footnote or shortcut too, because of lang settings
2890 // and wrong handling if used 'KeyInfo::noMain'
2891 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2892 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2893 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2894 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2895 makeKey("hphantom|vphantom|note|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2896 makeKey("textgreek|textcyrillic", KeyInfo(KeyInfo::isStandard, 1, true), false);
2897 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2898 // like ('tiny{}' or '\tiny ' ... )
2899 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, ignoreFormats.getSize()), isPatternString);
2901 // Survives, like known character
2902 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2903 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2904 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2906 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2907 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2908 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2910 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2911 // Remove RTL/LTR marker
2912 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2913 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2914 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2915 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2916 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2917 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2918 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2919 if (isPatternString) {
2920 // Allow the first searched string to rebuild the keys too
2924 // no need to rebuild again
2930 * Keep the list of actual opened parentheses actual
2931 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2933 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2936 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2940 if (c == '\\') skip = 1;
2941 else if (c == '{') {
2944 else if (c == '}') {
2945 handleCloseP(i, closingAllowed);
2951 string Intervall::show(int lastpos)
2953 int idx = 0; /* int intervalls */
2956 if ((unsigned) lastpos > par.size())
2957 lastpos = par.size();
2958 for (idx = 0; idx <= ignoreidx; idx++) {
2959 while (i < lastpos) {
2961 if (i <= borders[idx].low) {
2962 if (borders[idx].low > lastpos)
2963 printsize = lastpos - i;
2965 printsize = borders[idx].low - i;
2966 s += par.substr(i, printsize);
2968 if (i >= borders[idx].low)
2969 i = borders[idx].upper;
2972 i = borders[idx].upper;
2978 s += par.substr(i, lastpos-i);
2984 void Intervall::output(ostringstream &os, int lastpos)
2986 // get number of chars to output
2987 int idx = 0; /* int intervalls */
2990 string startTitle = titleValue;
2991 for (idx = 0; idx <= ignoreidx; idx++) {
2993 if (i <= borders[idx].low) {
2995 if (borders[idx].low > lastpos)
2996 printsize = lastpos - i;
2998 printsize = borders[idx].low - i;
2999 if (printsize > 0) {
3000 os << startTitle << par.substr(i, printsize);
3002 printed += printsize;
3005 handleParentheses(i, false);
3006 if (i >= borders[idx].low)
3007 i = borders[idx].upper;
3010 i = borders[idx].upper;
3017 os << startTitle << par.substr(i, lastpos-i);
3018 printed += lastpos-i;
3020 handleParentheses(lastpos, false);
3022 if (keys["foreignlanguage"].disabled)
3023 startindex = actualdeptindex-langcount;
3025 startindex = actualdeptindex;
3026 for (int i = startindex; i > 0; --i) {
3029 if (hasTitle && (printed > 0))
3031 if (! isPatternString_)
3033 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
3036 void LatexInfo::processRegion(int start, int region_end)
3038 while (start < region_end) { /* Let {[} and {]} survive */
3039 int cnt = interval_.isOpeningPar(start);
3041 // Closing is allowed past the region
3042 int closing = interval_.findclosing(start+1, interval_.par.length());
3043 interval_.addIntervall(start, start+1);
3044 interval_.addIntervall(closing, closing+1);
3048 start = interval_.nextNotIgnored(start+1);
3052 void LatexInfo::removeHead(KeyInfo const & actual, int count)
3054 if (actual.parenthesiscount == 0) {
3055 // "{\tiny{} ...}" ==> "{{} ...}"
3056 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
3059 // Remove header hull, that is "\url{abcd}" ==> "abcd"
3060 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
3061 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
3065 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
3068 switch (actual.keytype)
3070 case KeyInfo::isTitle: {
3072 nextKeyIdx = getNextKey();
3075 case KeyInfo::cleanToStart: {
3076 actual._dataEnd = actual._dataStart;
3077 nextKeyIdx = getNextKey();
3078 // Search for end of arguments
3079 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3081 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3082 entries_[i].disabled = true;
3084 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3086 while (interval_.par[actual._dataEnd] == ' ')
3088 interval_.addIntervall(0, actual._dataEnd+1);
3089 interval_.actualdeptindex = 0;
3090 interval_.depts[0] = actual._dataEnd+1;
3091 interval_.closes[0] = -1;
3094 case KeyInfo::isText:
3095 interval_.par[actual._tokenstart] = '#';
3096 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
3097 nextKeyIdx = getNextKey();
3099 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
3100 if (actual.disabled)
3101 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3103 interval_.addIntervall(actual._dataStart, actual._dataEnd);
3106 case KeyInfo::isChar: {
3107 nextKeyIdx = getNextKey();
3110 case KeyInfo::isSize: {
3111 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
3112 if (actual.parenthesiscount == 0)
3113 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
3115 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3117 nextKeyIdx = getNextKey();
3119 // Here _dataStart points to '{', so correct it
3120 actual._dataStart += 1;
3121 actual._tokensize += 1;
3122 actual.parenthesiscount = 1;
3123 if (interval_.par[actual._dataStart] == '}') {
3124 // Determine the end if used like '{\tiny{}...}'
3125 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
3126 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3129 // Determine the end if used like '\tiny{...}'
3130 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
3132 // Split on this key if not at start
3133 int start = interval_.nextNotIgnored(previousStart);
3134 if (start < actual._tokenstart) {
3135 interval_.output(os, actual._tokenstart);
3136 interval_.addIntervall(start, actual._tokenstart);
3138 // discard entry if at end of actual
3139 nextKeyIdx = process(os, actual);
3143 case KeyInfo::endArguments: {
3144 // Remove trailing '{}' too
3145 actual._dataStart += 1;
3146 actual._dataEnd += 1;
3147 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3148 nextKeyIdx = getNextKey();
3151 case KeyInfo::noMain:
3153 case KeyInfo::isStandard: {
3154 if (actual.disabled) {
3156 processRegion(actual._dataStart, actual._dataStart+1);
3157 nextKeyIdx = getNextKey();
3159 // Split on this key if not at datastart of calling entry
3160 int start = interval_.nextNotIgnored(previousStart);
3161 if (start < actual._tokenstart) {
3162 interval_.output(os, actual._tokenstart);
3163 interval_.addIntervall(start, actual._tokenstart);
3165 // discard entry if at end of actual
3166 nextKeyIdx = process(os, actual);
3170 case KeyInfo::removeWithArg: {
3171 nextKeyIdx = getNextKey();
3172 // Search for end of arguments
3173 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3175 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3176 entries_[i].disabled = true;
3178 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3180 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
3183 case KeyInfo::doRemove: {
3184 // Remove the key with all parameters and following spaces
3187 if (interval_.par[actual._dataEnd-1] == ' ' || interval_.par[actual._dataEnd-1] == '}')
3188 start = actual._dataEnd;
3190 start = actual._dataEnd+1;
3191 for (pos = start; pos < interval_.par.length(); pos++) {
3192 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
3195 // Remove also enclosing parentheses [] and {}
3198 while (actual._tokenstart > numpars) {
3199 if (pos+numpars >= interval_.par.size())
3201 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
3203 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
3209 if (interval_.par[pos+numpars] == ' ')
3213 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
3214 nextKeyIdx = getNextKey();
3217 case KeyInfo::isList: {
3218 // Discard space before _tokenstart
3220 for (count = 0; count < actual._tokenstart; count++) {
3221 if (interval_.par[actual._tokenstart-count-1] != ' ')
3224 nextKeyIdx = getNextKey();
3225 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
3227 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
3229 // How else can we catch this one?
3230 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
3231 entries_[i].disabled = true;
3233 actual._dataEnd = entries_[tmpIdx]._dataEnd;
3235 else if (nextKeyIdx > 0) {
3236 // Ignore any lang entries inside data region
3237 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
3238 if (entries_[i].keytype == KeyInfo::isMain)
3239 entries_[i].disabled = true;
3242 if (actual.disabled) {
3243 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
3246 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3248 if (interval_.par[actual._dataEnd+1] == '[') {
3249 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
3250 if ((interval_.par[actual._dataEnd+2] == '{') &&
3251 (interval_.par[posdown-1] == '}')) {
3252 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
3253 interval_.addIntervall(posdown-1, posdown+1);
3256 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
3257 interval_.addIntervall(posdown, posdown+1);
3259 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
3260 if (blk > posdown) {
3261 // Discard at most 1 space after empty item
3263 for (count = 0; count < 1; count++) {
3264 if (interval_.par[blk+count] != ' ')
3268 interval_.addIntervall(blk, blk+count);
3273 case KeyInfo::isSectioning: {
3274 // Discard spaces before _tokenstart
3276 int val = actual._tokenstart;
3277 for (count = 0; count < actual._tokenstart;) {
3278 val = interval_.previousNotIgnored(val-1);
3279 if (val < 0 || interval_.par[val] != ' ')
3282 count = actual._tokenstart - val;
3285 if (actual.disabled) {
3286 removeHead(actual, count);
3287 nextKeyIdx = getNextKey();
3289 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
3290 nextKeyIdx = process(os, actual);
3294 case KeyInfo::isMath: {
3295 // Same as regex, use the content unchanged
3296 nextKeyIdx = getNextKey();
3299 case KeyInfo::isRegex: {
3300 // DO NOT SPLIT ON REGEX
3302 nextKeyIdx = getNextKey();
3305 case KeyInfo::isIgnored: {
3306 // Treat like a character for now
3307 nextKeyIdx = getNextKey();
3310 case KeyInfo::isMain: {
3311 if (interval_.par.substr(actual._dataStart, 2) == "% ")
3312 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
3313 if (actual._tokenstart > 0) {
3314 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
3315 if ((prev >= 0) && interval_.par[prev] == '%')
3316 interval_.addIntervall(prev, prev+1);
3318 if (actual.disabled) {
3320 interval_.langcount++;
3321 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
3322 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
3323 // Discard also the space before math-equation
3324 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
3326 nextKeyIdx = getNextKey();
3327 // interval.resetOpenedP(actual._dataStart-1);
3330 if (actual._tokenstart < 26) {
3331 // for the first (and maybe dummy) language
3332 interval_.setForDefaultLang(actual);
3334 interval_.resetOpenedP(actual._dataStart-1);
3338 case KeyInfo::invalid:
3339 case KeyInfo::headRemove:
3340 // These two cases cannot happen, already handled
3343 // LYXERR(Debug::INFO, "Unhandled keytype");
3344 nextKeyIdx = getNextKey();
3351 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
3353 int end = interval_.nextNotIgnored(actual._dataEnd);
3354 int oldStart = actual._dataStart;
3355 int nextKeyIdx = getNextKey();
3357 if ((nextKeyIdx < 0) ||
3358 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
3359 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
3360 if (oldStart <= end) {
3361 processRegion(oldStart, end);
3366 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
3368 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
3369 (void) dispatch(os, actual._dataStart, nextKey);
3370 end = nextKey._tokenstart;
3373 processRegion(oldStart, nextKey._tokenstart);
3374 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
3376 oldStart = nextKey._dataEnd+1;
3378 // now nextKey is either invalid or is outside of actual._dataEnd
3379 // output the remaining and discard myself
3380 if (oldStart <= end) {
3381 processRegion(oldStart, end);
3383 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
3385 // This is the normal case.
3386 // But if using the firstlanguage, the closing may be missing
3388 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
3390 if (actual._dataEnd < end)
3391 output_end = interval_.nextNotIgnored(actual._dataEnd);
3392 else if (interval_.par.size() > (size_t) end)
3393 output_end = interval_.nextNotIgnored(end);
3395 output_end = interval_.par.size();
3396 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
3397 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
3399 // Remove possible empty data
3400 int dstart = interval_.nextNotIgnored(actual._dataStart);
3401 while (interval_.isOpeningPar(dstart) == 1) {
3402 interval_.addIntervall(dstart, dstart+1);
3403 int dend = interval_.findclosing(dstart+1, output_end);
3404 interval_.addIntervall(dend, dend+1);
3405 dstart = interval_.nextNotIgnored(dstart+1);
3407 if (dstart < output_end)
3408 interval_.output(os, output_end);
3410 interval_.addIntervall(0, end);
3412 interval_.addIntervall(actual._tokenstart, end);
3416 string splitOnKnownMacros(string par, bool isPatternString)
3419 LatexInfo li(par, isPatternString);
3420 // LYXERR(Debug::INFO, "Berfore split: " << par);
3421 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
3423 DummyKey._tokensize = 0;
3424 DummyKey._dataStart = 0;
3425 DummyKey._dataEnd = par.length();
3426 DummyKey.disabled = true;
3427 int firstkeyIdx = li.getFirstKey();
3429 if (firstkeyIdx >= 0) {
3430 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
3431 DummyKey._tokenstart = firstKey._tokenstart;
3433 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
3434 // Use dummy firstKey
3435 firstKey = DummyKey;
3436 (void) li.setNextKey(firstkeyIdx);
3439 if (par.substr(firstKey._dataStart, 2) == "% ")
3440 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
3442 nextkeyIdx = li.process(os, firstKey);
3443 while (nextkeyIdx >= 0) {
3444 // Check for a possible gap between the last
3445 // entry and this one
3446 int datastart = li.nextNotIgnored(firstKey._dataStart);
3447 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
3448 if ((nextKey._tokenstart > datastart)) {
3450 firstKey._dataStart = datastart;
3451 firstKey._dataEnd = par.length();
3452 (void) li.setNextKey(nextkeyIdx);
3453 // Fake the last opened parenthesis
3454 li.setForDefaultLang(firstKey);
3455 nextkeyIdx = li.process(os, firstKey);
3458 if (nextKey.keytype != KeyInfo::isMain) {
3459 firstKey._dataStart = datastart;
3460 firstKey._dataEnd = nextKey._dataEnd+1;
3461 (void) li.setNextKey(nextkeyIdx);
3462 li.setForDefaultLang(firstKey);
3463 nextkeyIdx = li.process(os, firstKey);
3466 nextkeyIdx = li.process(os, nextKey);
3470 // Handle the remaining
3471 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
3472 firstKey._dataEnd = par.length();
3474 if ((firstKey._dataStart < firstKey._dataEnd) &&
3475 (par[firstKey._dataStart] != '}')) {
3476 li.setForDefaultLang(firstKey);
3477 (void) li.process(os, firstKey);
3480 // return string definitelly impossible to match, but should be known
3483 s = par; /* no known macros found */
3484 // LYXERR(Debug::INFO, "After split: " << s);
3489 * Try to unify the language specs in the latexified text.
3490 * Resulting modified string is set to "", if
3491 * the searched tex does not contain all the features in the search pattern
3493 static string correctlanguagesetting(string par, bool isPatternString, bool withformat, lyx::Buffer *pbuf = nullptr)
3495 static Features regex_f;
3496 static int missed = 0;
3497 static bool regex_with_format = false;
3499 int parlen = par.length();
3501 while ((parlen > 0) && (par[parlen-1] == '\n')) {
3505 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
3506 // Happens to be there in case of description or labeling environment
3512 // Split the latex input into pieces which
3513 // can be digested by our search engine
3514 LYXERR(Debug::FINDVERBOSE, "input: \"" << par << "\"");
3515 if (isPatternString && (pbuf != nullptr)) { // Check if we should disable/enable test for language
3516 // We check for polyglossia, because in runparams.flavor we use Flavor::XeTeX
3517 string doclang = pbuf->params().language->polyglossia();
3518 static regex langre("\\\\(foreignlanguage)\\{([^\\}]+)\\}");
3520 bool toIgnoreLang = true;
3521 for (sregex_iterator it(par.begin(), par.end(), langre), end; it != end; ++it) {
3523 if (sub.str(2) != doclang) {
3524 toIgnoreLang = false;
3528 setIgnoreFormat("language", toIgnoreLang, false);
3531 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
3532 LYXERR(Debug::FINDVERBOSE, "After splitOnKnownMacros:\n\"" << result << "\"");
3535 result = par.substr(0, parlen);
3536 if (isPatternString) {
3539 regex_f = identifyFeatures(result);
3540 string features = "";
3541 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3542 string a = it->first;
3543 regex_with_format = true;
3544 features += " " + a;
3545 // LYXERR(Debug::INFO, "Identified regex format:" << a);
3547 LYXERR(Debug::FINDVERBOSE, "Identified Features" << features);
3550 } else if (regex_with_format) {
3551 Features info = identifyFeatures(result);
3552 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
3553 string a = it->first;
3554 bool b = it->second;
3555 if (b && ! info[a]) {
3557 LYXERR(Debug::FINDVERBOSE, "Missed(" << missed << " " << a <<", srclen = " << parlen );
3564 // LYXERR(Debug::INFO, "No regex formats");
3570 // Remove trailing closure of math, macros and environments, so to catch parts of them.
3571 static void identifyClosing(string & t, bool ignoreformat)
3574 LYXERR(Debug::FINDVERBOSE, "identifyClosing(): t now is '" << t << "'");
3575 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
3577 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
3579 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]+\\*?\\}$", "$1"))
3581 if (! ignoreformat) {
3582 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1"))
3590 static int num_replaced = 0;
3591 static bool previous_single_replace = true;
3593 void MatchStringAdv::CreateRegexp(FindAndReplaceOptions const & opt, string regexp_str, string regexp2_str, string par_as_string)
3596 if (regexp_str.empty() || regexp2_str.empty()) {
3597 regexIsValid = false;
3598 regexError = "Invalid empty regex";
3601 // Handle \w properly
3602 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3603 if (! opt.casesensitive) {
3604 popts |= QRegularExpression::CaseInsensitiveOption;
3606 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3607 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3609 if (regexp.isValid() && regexp2.isValid()) {
3610 regexIsValid = true;
3611 // Check '{', '}' pairs inside the regex
3614 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3615 char c = par_as_string[i];
3622 else if (c == '}') {
3629 if (balanced != 0) {
3630 regexIsValid = false;
3631 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3635 regexIsValid = false;
3636 if (!regexp.isValid())
3637 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3639 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3642 (void)par_as_string;
3643 if (opt.casesensitive) {
3644 regexp = regex(regexp_str);
3645 regexp2 = regex(regexp2_str);
3648 regexp = regex(regexp_str, std::regex_constants::icase);
3649 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3654 static void modifyRegexForMatchWord(string &t)
3657 regex wordre("(\\\\)*((\\.|\\\\b))");
3660 for (sregex_iterator it(t.begin(), t.end(), wordre), end; it != end; ++it) {
3662 if ((sub.position(2) - sub.position(0)) % 2 == 1) {
3665 else if (sub.str(2) == "\\\\b")
3667 if (lastpos < (size_t) sub.position(2))
3668 s += t.substr(lastpos, sub.position(2) - lastpos);
3670 lastpos = sub.position(2) + sub.length(2);
3673 s = "\\b" + t + "\\b";
3677 else if (lastpos < t.length())
3678 s += t.substr(lastpos, t.length() - lastpos);
3679 t = "\\b" + s + "\\b";
3682 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions & opt)
3683 : p_buf(&buf), p_first_buf(&buf), opt(opt)
3685 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
3686 docstring const & ds = stringifySearchBuffer(find_buf, opt);
3688 CreateRegexp(opt, "", "", "");
3691 use_regexp = ds.find(from_utf8("\\regexp{")) != std::string::npos;
3692 if (opt.replace_all && previous_single_replace) {
3693 previous_single_replace = false;
3696 else if (!opt.replace_all) {
3697 num_replaced = 0; // count number of replaced strings
3698 previous_single_replace = true;
3700 // When using regexp, braces are hacked already by escape_for_regex()
3701 par_as_string = convertLF2Space(ds, opt.ignoreformat);
3703 size_t lead_size = 0;
3704 // correct the language settings
3705 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat, &buf);
3706 if (par_as_string.empty()) {
3707 CreateRegexp(opt, "", "", "");
3710 opt.matchAtStart = false;
3712 identifyClosing(par_as_string, opt.ignoreformat); // Removes math closings ($, ], ...) at end of string
3713 if (opt.ignoreformat) {
3717 lead_size = identifyLeading(par_as_string);
3719 lead_as_string = par_as_string.substr(0, lead_size);
3720 string lead_as_regex_string = string2regex(lead_as_string);
3721 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3722 string par_as_regex_string_nolead = string2regex(par_as_string_nolead);
3723 /* Handle whole words too in this case
3725 if (opt.matchword) {
3726 par_as_regex_string_nolead = "\\b" + par_as_regex_string_nolead + "\\b";
3727 opt.matchword = false;
3729 string regexp_str = "(" + lead_as_regex_string + ")()" + par_as_regex_string_nolead;
3730 string regexp2_str = "(" + lead_as_regex_string + ")(.*?)" + par_as_regex_string_nolead;
3731 CreateRegexp(opt, regexp_str, regexp2_str);
3733 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3734 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3738 if (!opt.ignoreformat) {
3739 lead_size = identifyLeading(par_as_string);
3740 LYXERR(Debug::FINDVERBOSE, "Lead_size: " << lead_size);
3741 lead_as_string = par_as_string.substr(0, lead_size);
3742 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
3745 // Here we are using regexp
3746 LASSERT(use_regexp, /**/);
3748 string lead_as_regexp;
3749 if (lead_size > 0) {
3750 lead_as_regexp = string2regex(par_as_string.substr(0, lead_size));
3751 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "\\$$", "");
3752 (void)regex_replace(par_as_string_nolead, par_as_string_nolead, "}$", "");
3753 par_as_string = par_as_string_nolead;
3754 LYXERR(Debug::FINDVERBOSE, "lead_as_regexp is '" << lead_as_regexp << "'");
3755 LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3757 // LYXERR(Debug::FINDVERBOSE, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
3758 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
3759 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
3760 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3762 size_t lng = par_as_string.size();
3763 if (!opt.ignoreformat) {
3764 // Remove extra '\}' at end if not part of \{\.\}
3766 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
3768 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
3777 if (lng < par_as_string.size())
3778 par_as_string.resize(lng);
3780 LYXERR(Debug::FINDVERBOSE, "par_as_string after correctRegex is '" << par_as_string << "'");
3781 if ((lng > 0) && (par_as_string[0] == '^')) {
3782 par_as_string = par_as_string.substr(1);
3784 opt.matchAtStart = true;
3786 // LYXERR(Debug::FINDVERBOSE, "par_as_string now is '" << par_as_string << "'");
3787 // LYXERR(Debug::FINDVERBOSE, "Open braces: " << open_braces);
3788 // LYXERR(Debug::FINDVERBOSE, "Replaced text (to be used as regex): " << par_as_string);
3790 // If entered regexp must match at begin of searched string buffer
3791 // Kornel: Added parentheses to use $1 for size of the leading string
3795 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3796 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3797 // so the convert has no effect in that case
3798 for (int i = 7; i > 0; --i) {
3799 string orig = "\\\\" + std::to_string(i);
3800 string dest = "\\" + std::to_string(i+2);
3801 while (regex_replace(par_as_string, par_as_string, orig, dest));
3803 if (opt.matchword) {
3804 modifyRegexForMatchWord(par_as_string);
3805 // opt.matchword = false;
3807 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3808 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3810 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3811 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3812 CreateRegexp(opt, regexp_str, regexp2_str, par_as_string);
3816 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3820 mres.searched_size = len;
3822 docstring docstr = stringifyFromForSearch(opt, cur, len);
3824 str = convertLF2Space(docstr, opt.ignoreformat);
3825 if (!opt.ignoreformat) {
3826 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3827 // remove closing '}' and '\n' to allow for use of '$' in regex
3828 size_t lng = str.size();
3829 while ((lng > 1) && ((str[lng -1] == '}') || (str[lng -1] == '\n')))
3831 if (lng != str.size()) {
3832 str = str.substr(0, lng);
3834 // Replace occurences of '~' to ' '
3835 static std::regex specialChars { R"(~)" };
3836 str = std::regex_replace(str, specialChars, R"( )" );
3839 mres.match_len = -1;
3842 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "After normalization: Matching against:\n'" << str << "'");
3844 LASSERT(use_regexp, /**/);
3846 // use_regexp always true
3847 LYXERR(Debug::FINDVERBOSE, "Searching in regexp mode: at_begin=" << matchTypeAsString(at_begin));
3849 QString qstr = QString::fromStdString(str);
3850 QRegularExpression const *p_regexp;
3851 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3852 if (at_begin == MatchStringAdv::MatchFromStart) {
3855 p_regexp = ®exp2;
3857 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3858 if (!match.hasMatch())
3861 regex const *p_regexp;
3862 regex_constants::match_flag_type flags;
3863 if (at_begin == MatchStringAdv::MatchFromStart) {
3864 flags = regex_constants::match_continuous;
3867 flags = regex_constants::match_default;
3868 p_regexp = ®exp2;
3870 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3871 if (re_it == sregex_iterator())
3873 match_results<string::const_iterator> const & m = *re_it;
3875 // Whole found string, including the leading
3876 // std: m[0].second - m[0].first
3877 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3879 // Size of the leading string
3880 // std: m[1].second - m[1].first
3881 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3882 int leadingsize = 0;
3884 if (match.lastCapturedIndex() > 0) {
3885 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3890 leadingsize = m[1].second - m[1].first;
3894 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3895 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3896 // because of different number of closing at end of string
3897 // we have to 'unify' the length of the post-match.
3898 // Done by ignoring closing parenthesis and linefeeds at string end
3899 int matchend = match.capturedEnd(0);
3900 size_t strsize = qstr.size();
3901 if (!opt.ignoreformat) {
3902 while (mres.match_len > 1) {
3903 QChar c = qstr.at(matchend - 1);
3904 if ((c == '\n') || (c == '}') || (c == '{')) {
3911 while (strsize > (size_t) match.capturedEnd(0)) {
3912 QChar c = qstr.at(strsize-1);
3913 if ((c == '\n') || (c == '}')) {
3920 // LYXERR0(qstr.toStdString());
3921 mres.match2end = strsize - matchend;
3922 mres.pos = match.capturedStart(2);
3924 mres.match_prefix = m[2].second - m[2].first;
3925 mres.match_len = m[0].second - m[2].second;
3926 // ignore closing parenthesis and linefeeds at string end
3927 size_t strend = m[0].second - m[0].first;
3928 int matchend = strend;
3929 size_t strsize = str.size();
3930 if (!opt.ignoreformat) {
3931 while (mres.match_len > 1) {
3932 char c = str.at(matchend - 1);
3933 if ((c == '\n') || (c == '}') || (c == '{')) {
3940 while (strsize > strend) {
3941 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3949 mres.match2end = strsize - matchend;
3950 mres.pos = m[2].first - m[0].first;;
3952 if (mres.match2end < 0)
3954 mres.leadsize = leadingsize;
3956 if (mres.match_len > 0) {
3957 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3958 mres.result.push_back(a0);
3959 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3960 mres.result.push_back(match.captured(i).toStdString());
3964 if (mres.match_len > 0) {
3965 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3966 mres.result.push_back(a0);
3967 for (size_t i = 3; i < m.size(); i++) {
3968 mres.result.push_back(m[i]);
3977 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, MatchStringAdv::matchType at_begin) const
3979 MatchResult mres = findAux(cur, len, at_begin);
3980 LYXERR(Debug::FINDVERBOSE,
3981 "res=" << mres.match_len << ", at_begin=" << matchTypeAsString(at_begin)
3982 << ", matchAtStart=" << opt.matchAtStart
3983 << ", inTexted=" << cur.inTexted());
3984 if (mres.match_len > 0) {
3985 if (opt.matchAtStart) {
3986 if (cur.pos() > 0 || mres.match_prefix > 0)
3994 static bool simple_replace(string &t, string from, string to)
3996 regex repl("(\\\\)*(" + from + ")");
4000 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
4002 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4004 if (lastpos < (size_t) sub.position(2))
4005 s += t.substr(lastpos, sub.position(2) - lastpos);
4007 lastpos = sub.position(2) + sub.length(2);
4011 else if (lastpos < t.length())
4012 s += t.substr(lastpos, t.length() - lastpos);
4018 string MatchStringAdv::convertLF2Space(docstring const &s, bool ignore_format) const
4020 // Using original docstring to handle '\n'
4022 if (s.size() == 0) return "";
4026 size_t end = s.size() - 1;
4027 if (!ignore_format) {
4028 while (s[start] == '\n' && start <= end)
4030 while (end >= start && s[end] == '\n')
4032 if (start >= end + 1)
4036 bool dospace = true;
4038 pos = s.find('\n', start);
4040 t << lyx::to_utf8(s.substr(start, end + 1 - start));
4043 if (!ignore_format) {
4044 if ((pos > start + 1) &&
4048 if ((pos > start + 2) &&
4049 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4050 s[pos-3] == '~' || isSpace(s[pos-3]))) {
4051 // discard "\\\\\n", do not replace with space
4055 else if (pos > start) {
4056 if (s[pos-1] == '%') {
4058 while ((pos > start+skip) && (s[pos-1-skip] == '%'))
4060 if ((pos > start+skip) &&
4061 (s[pos+1] == '~' || isSpace(s[pos+1]) ||
4062 s[pos-1-skip] == '~' || isSpace(s[pos-1-skip]))) {
4063 // discard '%%%%%\n'
4067 else if (!isAlnumASCII(s[pos+1]) || !isAlnumASCII(s[pos-1])) {
4069 skip = 0; // remove the '\n' only
4077 t << lyx::to_utf8(s.substr(start, pos-skip-start));
4081 } while (start <= end);
4085 docstring stringifyFromCursor(DocIterator const & cur, int len)
4087 LYXERR(Debug::FINDVERBOSE, "Stringifying with len=" << len << " from cursor at pos: " << cur);
4088 if (cur.inTexted()) {
4089 Paragraph const & par = cur.paragraph();
4090 // TODO what about searching beyond/across paragraph breaks ?
4091 // TODO Try adding a AS_STR_INSERTS as last arg
4092 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
4093 int(par.size()) : cur.pos() + len;
4094 // OutputParams runparams(&cur.buffer()->params().encoding());
4095 OutputParams runparams(encodings.fromLyXName("utf8"));
4096 runparams.nice = true;
4097 setFindParams(runparams);
4098 int option = AS_STR_INSETS | AS_STR_PLAINTEXT;
4099 if (ignoreFormats.getDeleted()) {
4100 option |= AS_STR_SKIPDELETE;
4101 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4104 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4106 if (ignoreFormats.getNonContent()) {
4107 runparams.find_add_feature(OutputParams::SearchNonOutput);
4109 LYXERR(Debug::FINDVERBOSE, "Stringifying with cur: "
4110 << cur << ", from pos: " << cur.pos() << ", end: " << end);
4111 docstring res = from_utf8(latexNamesToUtf8(par.asString(cur.pos(), end,
4113 &runparams), false));
4114 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified text from pos(" << cur.pos() << ") len(" << len << "): " << res);
4116 } else if (cur.inMathed()) {
4117 CursorSlice cs = cur.top();
4118 MathData md = cs.cell();
4119 MathData::const_iterator it_end =
4120 (( len == -1 || cs.pos() + len > int(md.size()))
4122 : md.begin() + cs.pos() + len );
4124 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
4126 docstring res = from_utf8(latexNamesToUtf8(asString(md2), false));
4127 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Stringified math from pos(" << cur.pos() << ") len(" << len << "): " << res);
4130 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4134 /** Computes the LaTeX export of buf starting from cur and ending len positions
4135 * after cur, if len is positive, or at the paragraph or innermost inset end
4138 docstring latexifyFromCursor(DocIterator const & cur, int len)
4141 LYXERR(Debug::FINDVERBOSE, "Latexifying with len=" << len << " from cursor at pos: " << cur);
4142 LYXERR(Debug::FINDVERBOSE, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
4143 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
4145 Buffer const & buf = *cur.buffer();
4147 odocstringstream ods;
4149 //OutputParams runparams(&buf.params().encoding());
4150 OutputParams runparams(encodings.fromLyXName("utf8"));
4151 runparams.nice = false;
4152 setFindParams(runparams);
4153 if (ignoreFormats.getDeleted()) {
4154 runparams.find_set_feature(OutputParams::SearchWithoutDeleted);
4157 runparams.find_set_feature(OutputParams::SearchWithDeleted);
4159 if (ignoreFormats.getNonContent()) {
4160 runparams.find_add_feature(OutputParams::SearchNonOutput);
4163 if (cur.inTexted()) {
4164 // @TODO what about searching beyond/across paragraph breaks ?
4165 pos_type endpos = cur.paragraph().size();
4166 if (len != -1 && endpos > cur.pos() + len)
4167 endpos = cur.pos() + len;
4168 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
4169 string(), cur.pos(), endpos, true);
4170 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified text from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4172 } else if (cur.inMathed()) {
4173 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
4174 for (int s = cur.depth() - 1; s >= 0; --s) {
4175 CursorSlice const & cs = cur[s];
4176 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
4177 TeXMathStream ws(os);
4178 cs.asInsetMath()->asHullInset()->header_write(ws);
4183 CursorSlice const & cs = cur.top();
4184 MathData md = cs.cell();
4185 MathData::const_iterator it_end =
4186 ((len == -1 || cs.pos() + len > int(md.size()))
4188 : md.begin() + cs.pos() + len);
4190 for (MathData::const_iterator it = md.begin() + cs.pos();
4194 ods << asString(md2);
4195 // Retrieve the math environment type, and add '$' or '$]'
4196 // or others (\end{equation}) accordingly
4197 for (int s = cur.depth() - 1; s >= 0; --s) {
4198 CursorSlice const & cs2 = cur[s];
4199 InsetMath * inset = cs2.asInsetMath();
4200 if (inset && inset->asHullInset()) {
4201 TeXMathStream ws(os);
4202 inset->asHullInset()->footer_write(ws);
4206 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Latexified math from pos(" << cur.pos() << ") len(" << len << "): " << ods.str());
4208 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Don't know how to stringify from here: " << cur);
4213 #if defined(ResultsDebug)
4215 static void displayMResult(MatchResult &mres, string from, DocIterator & cur)
4217 LYXERR0( "from:\t\t\t" << from);
4219 if (mres.pos_len > 0) {
4221 status = "FINALSEARCH";
4224 if (mres.match_len > 0) {
4225 if ((mres.match_prefix == 0) && (mres.pos == mres.leadsize))
4226 status = "Good Match";
4228 status = "Matched in";
4231 status = "MissedSearch";
4234 LYXERR0( status << "(" << cur.pos() << " ... " << mres.searched_size + cur.pos() << ") cur.lastpos(" << cur.lastpos() << ")");
4235 if ((mres.leadsize > 0) || (mres.match_len > 0) || (mres.match2end > 0))
4236 LYXERR0( "leadsize(" << mres.leadsize << ") match_len(" << mres.match_len << ") match2end(" << mres.match2end << ")");
4237 if ((mres.pos > 0) || (mres.match_prefix > 0))
4238 LYXERR0( "pos(" << mres.pos << ") match_prefix(" << mres.match_prefix << ")");
4239 for (size_t i = 0; i < mres.result.size(); i++)
4240 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
4242 #define displayMres(s, txt, cur) displayMResult(s, txt, cur);
4244 #define displayMres(s, txt, cur)
4247 /** Finalize an advanced find operation, advancing the cursor to the innermost
4248 ** position that matches, plus computing the length of the matching text to
4250 ** Return the cur.pos() difference between start and end of found match
4252 MatchResult findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
4254 // Search the foremost position that matches (avoids find of entire math
4255 // inset when match at start of it)
4256 DocIterator old_cur(cur.buffer());
4258 static MatchResult fail = MatchResult();
4259 MatchResult max_match;
4260 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
4261 // Happens with e.g. hyperlinks
4262 // either one sees "http://www.bla.bla" or nothing
4263 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
4264 // and although we search for only 3 chars, we find the whole hyperlink inset
4265 MatchStringAdv::matchType at_begin = (expected.match_prefix == 0) ? MatchStringAdv::MatchFromStart : MatchStringAdv::MatchAnyPlace;
4266 if (!match.opt.forward && match.opt.ignoreformat) {
4267 if (expected.pos > 0)
4270 LASSERT(at_begin == MatchStringAdv::MatchFromStart, /**/);
4271 if (expected.match_len > 0 && at_begin == MatchStringAdv::MatchFromStart) {
4272 // Search for deepest match
4274 max_match = expected;
4276 size_t d = cur.depth();
4280 if (cur.depth() < d)
4282 if (cur.depth() == d)
4285 while (cur && cur.depth() > lastd) {
4286 lastd = cur.depth();
4287 mres = match(cur, -1, at_begin);
4288 displayMres(mres, "Checking innermost", cur);
4289 if (mres.match_len > 0)
4294 if (mres.match_len < expected.match_len)
4302 // (expected.match_len <= 0)
4303 mres = match(cur, -1, MatchStringAdv::MatchFromStart); /* match valid only if not searching whole words */
4304 displayMres(mres, "Start with negative match", cur);
4307 // Only now we are really at_begin
4308 if ((max_match.match_len <= 0) ||
4309 (match.opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()))
4311 LYXERR(Debug::FINDVERBOSE, "Ok");
4313 // Compute the match length
4315 if (cur.pos() + len > cur.lastpos())
4318 LASSERT(match.use_regexp, /**/);
4321 int maxl = cur.lastpos() - cur.pos();
4322 // Greedy behaviour while matching regexps
4323 while (maxl > minl) {
4325 mres2 = match(cur, len, at_begin);
4326 displayMres(mres2, "Finalize loop", cur);
4327 int actual_match_len = mres2.match_len;
4328 if (actual_match_len >= max_match.match_len) {
4329 // actual_match_len > max_match _can_ happen,
4330 // if the search area splits
4331 // some following word so that the regex
4332 // (e.g. 'r.*r\b' matches 'r' from the middle of the
4334 // This means, the len value is too big
4335 actual_match_len = max_match.match_len;
4337 max_match.match_len = actual_match_len;
4339 if (maxl - minl < 4)
4340 len = (maxl + minl)/2;
4342 len = minl + (maxl - minl + 3)/4;
4345 // (actual_match_len < max_match.match_len)
4347 len = (maxl + minl)/2;
4352 // Search for real start of matched characters
4354 MatchResult actual_match;
4357 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
4358 if (cur.depth() < old_cur.depth()) {
4360 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
4363 if (cur.pos() != old_cur.pos()) {
4364 // OK, forwarded 1 pos in actual inset
4365 actual_match = match(cur, len-1, at_begin);
4366 if (actual_match.match_len == max_match.match_len) {
4367 // Ha, got it! The shorter selection has the same match length
4370 max_match = actual_match;
4373 // OK, the shorter selection matches less chars, revert to previous value
4379 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
4380 actual_match = match(cur, len, at_begin);
4381 if (actual_match.match_len == max_match.match_len) {
4383 max_match = actual_match;
4390 max_match.pos_len = len;
4391 displayMres(max_match, "SEARCH RESULT", cur)
4398 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
4403 DocIterator orig_cur; // to be used if repeat not successful
4404 MatchResult orig_mres;
4408 } while (cur.depth() > orig_cur.depth());
4410 while (!theApp()->longOperationCancelled() && cur) {
4411 //(void) findAdvForwardInnermost(cur);
4412 LYXERR(Debug::FINDVERBOSE, "findForwardAdv() cur: " << cur);
4413 MatchResult mres = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4414 string msg = "Starting";
4417 displayMres(mres, msg + " findForwardAdv", cur)
4418 int match_len = mres.match_len;
4419 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
4420 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
4423 if (match_len <= 0) {
4428 // This should exit nested insets, if any, or otherwise undefine the currsor.
4429 cur.pos() = cur.lastpos();
4431 LYXERR(Debug::FINDVERBOSE, "Advancing pos: cur=" << cur);
4434 else { // match_len > 0
4435 // Try to find the begin of searched string
4437 int firstInvalid = cur.lastpos() - cur.pos();
4439 int incrmatch = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
4440 int incrcur = (firstInvalid + 1 )*3/4;
4441 if (incrcur < incrmatch)
4442 increment = incrcur;
4444 increment = incrmatch;
4448 LYXERR(Debug::FINDVERBOSE, "Set increment to " << increment);
4449 while (increment > 0) {
4450 DocIterator old_cur = cur;
4451 if (cur.pos() + increment >= cur.lastpos()) {
4455 cur.pos() = cur.pos() + increment;
4456 MatchResult mres2 = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4457 displayMres(mres2, "findForwardAdv loop", cur)
4458 switch (interpretMatch(mres, mres2)) {
4459 case MatchResult::newIsTooFar:
4460 // behind the expected match
4461 firstInvalid = increment;
4465 case MatchResult::newIsBetter:
4466 // not reached yet, but cur.pos()+increment is better
4468 firstInvalid -= increment;
4469 if (increment > firstInvalid*3/4)
4470 increment = firstInvalid*3/4;
4471 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
4472 if (increment >= mres2.match_prefix)
4473 increment = (mres2.match_prefix+1)*3/4;
4478 // Handle not like MatchResult::newIsTooFar
4479 LYXERR(Debug::FINDVERBOSE, "Probably too far: Increment = " << increment << " match_prefix = " << mres.match_prefix);
4481 increment = increment*3/4;
4486 if (mres.match_len > 0) {
4487 if (mres.match_prefix + mres.pos - mres.leadsize > 0) {
4488 // The match seems to indicate some deeper level
4496 else if (repeat > 0) {
4497 // should never be reached.
4501 // LYXERR0("Leaving first loop");
4502 LYXERR(Debug::FINDVERBOSE, "Finalizing 1");
4503 MatchResult found_match = findAdvFinalize(cur, match, mres);
4504 if (found_match.match_len > 0) {
4505 match.FillResults(found_match);
4506 return found_match.pos_len;
4509 // try next possible match
4520 /// Find the most backward consecutive match within same paragraph while searching backwards.
4521 MatchResult findMostBackwards(DocIterator & cur, MatchStringAdv const & match, MatchResult &expected)
4523 DocIterator cur_begin = cur;
4524 cur_begin.pos() = 0;
4525 DocIterator tmp_cur = cur;
4526 MatchResult mr = findAdvFinalize(tmp_cur, match, expected);
4527 Inset & inset = cur.inset();
4528 for (; cur != cur_begin; cur.backwardPos()) {
4529 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): cur=" << cur);
4530 DocIterator new_cur = cur;
4531 new_cur.backwardPos();
4532 if (new_cur == cur || &new_cur.inset() != &inset
4533 || match(new_cur, -1, MatchStringAdv::MatchFromStart).match_len <= 0)
4535 MatchResult new_mr = findAdvFinalize(new_cur, match, expected);
4536 if (new_mr.match_len == mr.match_len)
4540 LYXERR(Debug::FINDVERBOSE, "findMostBackwards(): exiting with cur=" << cur);
4546 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
4550 // Backup of original position
4551 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
4552 if (cur == cur_begin)
4555 DocIterator cur_orig(cur);
4556 bool pit_changed = false;
4559 MatchResult found_match = match(cur, -1, MatchStringAdv::MatchAnyPlace);
4561 if (found_match.match_len > 0) {
4563 cur.pos() = cur.lastpos();
4565 cur.pos() = cur_orig.pos();
4566 LYXERR(Debug::FINDVERBOSE, "findBackAdv2: cur: " << cur);
4567 DocIterator cur_prev_iter;
4569 found_match = match(cur, -1, MatchStringAdv::MatchFromStart);
4570 LYXERR(Debug::FINDVERBOSE, "findBackAdv3: found_match="
4571 << (found_match.match_len > 0) << ", cur: " << cur);
4572 if (found_match.match_len > 0) {
4573 MatchResult found_mr = findMostBackwards(cur, match, found_match);
4574 if (found_mr.pos_len > 0) {
4575 match.FillResults(found_mr);
4576 return found_mr.pos_len;
4580 // Stop if begin of document reached
4581 if (cur == cur_begin)
4583 cur_prev_iter = cur;
4587 if (cur == cur_begin)
4594 } while (!theApp()->longOperationCancelled());
4602 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
4603 DocIterator const & cur, int len)
4605 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
4607 if (!opt.ignoreformat)
4608 return latexifyFromCursor(cur, len);
4610 return stringifyFromCursor(cur, len);
4614 FindAndReplaceOptions::FindAndReplaceOptions(
4615 docstring const & _find_buf_name, bool _casesensitive,
4616 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
4617 docstring const & _repl_buf_name, bool _keep_case,
4618 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
4619 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
4620 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
4621 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4629 /** Check if 'len' letters following cursor are all non-lowercase */
4630 static bool allNonLowercase(Cursor const & cur, int len)
4632 pos_type beg_pos = cur.selectionBegin().pos();
4633 pos_type end_pos = cur.selectionBegin().pos() + len;
4634 if (len > cur.lastpos() + 1 - beg_pos) {
4635 LYXERR(Debug::FINDVERBOSE, "This should not happen, more debug needed");
4636 len = cur.lastpos() + 1 - beg_pos;
4637 end_pos = beg_pos + len;
4639 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4640 if (isLowerCase(cur.paragraph().getChar(pos)))
4646 /** Check if first letter is upper case and second one is lower case */
4647 static bool firstUppercase(Cursor const & cur)
4650 pos_type pos = cur.selectionBegin().pos();
4651 if (pos >= cur.lastpos() - 1) {
4652 LYXERR(Debug::FINDVERBOSE, "No upper-case at cur: " << cur);
4655 ch1 = cur.paragraph().getChar(pos);
4656 ch2 = cur.paragraph().getChar(pos + 1);
4657 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4658 LYXERR(Debug::FINDVERBOSE, "firstUppercase(): "
4659 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4660 << ch2 << "(" << char(ch2) << ")"
4661 << ", result=" << result << ", cur=" << cur);
4666 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4668 ** \fixme What to do with possible further paragraphs in replace buffer ?
4670 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4672 ParagraphList::iterator pit = buffer.paragraphs().begin();
4673 LASSERT(!pit->empty(), /**/);
4674 pos_type right = pos_type(1);
4675 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4676 right = pit->size();
4677 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4681 static bool replaceMatches(string &t, int maxmatchnum, vector <string> const & replacements)
4683 // Should replace the string "$" + std::to_string(matchnum) with replacement
4684 // if the char '$' is not prefixed with odd number of char '\\'
4685 static regex const rematch("(\\\\)*(\\$\\$([0-9]))");
4689 for (sregex_iterator it(t.begin(), t.end(), rematch), end; it != end; ++it) {
4691 if ((sub.position(2) - sub.position(0)) % 2 == 1)
4693 int num = stoi(sub.str(3), nullptr, 10);
4694 if (num >= maxmatchnum)
4696 if (lastpos < (size_t) sub.position(2))
4697 s += t.substr(lastpos, sub.position(2) - lastpos);
4698 s += replacements[num];
4699 lastpos = sub.position(2) + sub.length(2);
4703 else if (lastpos < t.length())
4704 s += t.substr(lastpos, t.length() - lastpos);
4710 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4712 Cursor & cur = bv->cursor();
4713 if (opt.repl_buf_name.empty()
4714 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4715 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4718 DocIterator sel_beg = cur.selectionBegin();
4719 DocIterator sel_end = cur.selectionEnd();
4720 if (&sel_beg.inset() != &sel_end.inset()
4721 || sel_beg.pit() != sel_end.pit()
4722 || sel_beg.idx() != sel_end.idx())
4724 int sel_len = sel_end.pos() - sel_beg.pos();
4725 LYXERR(Debug::FINDVERBOSE, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4726 << ", sel_len: " << sel_len << endl);
4729 LASSERT(sel_len > 0, return 0);
4731 if (matchAdv(sel_beg, sel_len, MatchStringAdv::MatchFromStart).match_len <= 0)
4734 // Build a copy of the replace buffer, adapted to the KeepCase option
4735 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4737 repl_buffer_orig.write(oss);
4738 string lyx = oss.str();
4739 if (matchAdv.valid_matches > 0)
4740 replaceMatches(lyx, matchAdv.valid_matches, matchAdv.matches);
4741 Buffer repl_buffer(string(), false);
4742 repl_buffer.setInternal(true);
4743 repl_buffer.setUnnamed(true);
4744 LASSERT(repl_buffer.readString(lyx), return 0);
4745 if (opt.keep_case && sel_len >= 2) {
4746 LYXERR(Debug::FINDVERBOSE, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4747 if (cur.inTexted()) {
4748 if (firstUppercase(cur))
4749 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4750 else if (allNonLowercase(cur, sel_len))
4751 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4754 cap::cutSelection(cur, false);
4755 if (cur.inTexted()) {
4756 repl_buffer.changeLanguage(
4757 repl_buffer.language(),
4758 cur.getFont().language());
4759 LYXERR(Debug::FINDVERBOSE, "Replacing by pasteParagraphList()ing repl_buffer");
4760 LYXERR(Debug::FINDVERBOSE, "Before pasteParagraphList() cur=" << cur << endl);
4761 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4762 repl_buffer.params().documentClassPtr(),
4763 repl_buffer.params().authors(),
4764 bv->buffer().errorList("Paste"));
4765 LYXERR(Debug::FINDVERBOSE, "After pasteParagraphList() cur=" << cur << endl);
4766 sel_len = repl_buffer.paragraphs().begin()->size();
4767 } else if (cur.inMathed()) {
4768 odocstringstream ods;
4770 // OutputParams runparams(&repl_buffer.params().encoding());
4771 OutputParams runparams(encodings.fromLyXName("utf8"));
4772 runparams.nice = false;
4773 setFindParams(runparams);
4774 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams, string(), -1, -1, true);
4775 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4776 docstring repl_latex = ods.str();
4777 LYXERR(Debug::FINDVERBOSE, "Latexified replace_buffer: '" << repl_latex << "'");
4779 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4780 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4781 repl_latex = from_utf8(s);
4782 LYXERR(Debug::FINDVERBOSE, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4783 MathData ar(cur.buffer());
4784 asArray(repl_latex, ar, Parse::NORMAL);
4786 sel_len = ar.size();
4787 LYXERR(Debug::FINDVERBOSE, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4789 if (cur.pos() >= sel_len)
4790 cur.pos() -= sel_len;
4793 LYXERR(Debug::FINDVERBOSE, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4794 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4795 bv->processUpdateFlags(Update::Force);
4799 static bool isWordChar(char_type c)
4801 return isLetterChar(c) || isNumberChar(c);
4804 /// Perform a FindAdv operation.
4805 bool findAdv(BufferView * bv, FindAndReplaceOptions & opt)
4810 // e.g., when invoking word-findadv from mini-buffer wither with
4811 // wrong options syntax or before ever opening advanced F&R pane
4812 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4816 MatchStringAdv matchAdv(bv->buffer(), opt);
4818 if (!matchAdv.regexIsValid) {
4819 bv->message(lyx::from_utf8(matchAdv.regexError));
4823 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4825 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4826 num_replaced += findAdvReplace(bv, opt, matchAdv);
4829 if (opt.matchword && cur.pos() > 0) { // Skip word-characters if we are in the mid of a word
4830 if (cur.inTexted()) {
4831 Paragraph const & par = cur.paragraph();
4832 int len_limit, new_pos;
4833 if (cur.lastpos() < par.size())
4834 len_limit = cur.lastpos();
4836 len_limit = par.size();
4837 for (new_pos = cur.pos() - 1; new_pos < len_limit; new_pos++) {
4838 if (!isWordChar(par.getChar(new_pos)))
4841 if (new_pos > cur.pos())
4842 cur.pos() = new_pos;
4844 else if (cur.inMathed()) {
4845 // Check if 'cur.pos()-1' and 'cur.pos()' both point to a letter,
4846 // I am not sure, we should consider the selection
4847 bool sel = bv->cursor().selection();
4848 if (!sel && cur.pos() < cur.lastpos()) {
4849 CursorSlice const & cs = cur.top();
4850 MathData md = cs.cell();
4852 MathData::const_iterator it_end = md.end();
4854 // Start the check with one character before actual cursor position
4855 for (MathData::const_iterator it = md.begin() + cs.pos() - 1;
4858 docstring inp = asString(md2);
4859 for (len = 0; (unsigned) len < inp.size() && len + cur.pos() <= cur.lastpos(); len++) {
4860 if (!isWordChar(inp[len]))
4863 // len == 0 means previous char was a word separator
4864 // len == 1 search starts with a word separator
4865 // len == 2 ... we have to skip len -1 chars
4867 cur.pos() = cur.pos() + len - 1;
4870 opt.matchword = false;
4872 pos_len = findForwardAdv(cur, matchAdv);
4875 pos_len = findBackwardsAdv(cur, matchAdv);
4876 } catch (exception & ex) {
4877 bv->message(from_utf8(ex.what()));
4882 if (num_replaced > 0) {
4883 switch (num_replaced)
4886 bv->message(_("One match has been replaced."));
4889 bv->message(_("Two matches have been replaced."));
4892 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4898 bv->message(_("Match not found."));
4903 if (num_replaced > 0)
4904 bv->message(_("Match has been replaced."));
4906 bv->message(_("Match found."));
4908 if (cur.pos() + pos_len > cur.lastpos()) {
4909 // Prevent crash in bv->putSelectionAt()
4910 // Should never happen, maybe LASSERT() here?
4911 pos_len = cur.lastpos() - cur.pos();
4913 LYXERR(Debug::FINDVERBOSE|Debug::FIND, "Putting selection at cur=" << cur << " with len: " << pos_len);
4914 bv->putSelectionAt(cur, pos_len, !opt.forward);
4920 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4922 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4923 << opt.casesensitive << ' '
4924 << opt.matchword << ' '
4925 << opt.forward << ' '
4926 << opt.expandmacros << ' '
4927 << opt.ignoreformat << ' '
4928 << opt.replace_all << ' '
4929 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4930 << opt.keep_case << ' '
4931 << int(opt.scope) << ' '
4934 LYXERR(Debug::FINDVERBOSE, "built: " << os.str());
4940 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4942 // LYXERR(Debug::FINDVERBOSE, "parsing");
4946 while (line != "EOSS") {
4950 if (is.eof()) // Tolerate malformed request
4954 // LYXERR(Debug::FINDVERBOSE, "file_buf_name: '" << s << "'");
4955 opt.find_buf_name = from_utf8(s);
4956 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4957 is.get(); // Waste space before replace string
4960 while (line != "EOSS") {
4964 if (is.eof()) // Tolerate malformed request
4968 // LYXERR(Debug::FINDVERBOSE, "repl_buf_name: '" << s << "'");
4969 opt.repl_buf_name = from_utf8(s);
4970 is >> opt.keep_case;
4973 opt.scope = FindAndReplaceOptions::SearchScope(i);
4975 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4978 LYXERR(Debug::FINDVERBOSE, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4979 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4980 << opt.scope << ' ' << opt.restr);