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.
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
35 #include "frontends/Application.h"
36 #include "frontends/alert.h"
38 #include "mathed/InsetMath.h"
39 #include "mathed/InsetMathHull.h"
40 #include "mathed/MathData.h"
41 #include "mathed/MathStream.h"
42 #include "mathed/MathSupport.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/FileName.h"
47 #include "support/gettext.h"
48 #include "support/lassert.h"
49 #include "support/lstrings.h"
50 #include "support/textutils.h"
55 //#define ResultsDebug
56 #define USE_QT_FOR_SEARCH
57 #if defined(USE_QT_FOR_SEARCH)
58 #include <QtCore> // sets QT_VERSION
59 #if (QT_VERSION >= 0x050000)
60 #include <QRegularExpression>
70 using namespace lyx::support;
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 getUnderline() const { return ignoreUnderline_; }
89 bool getMarkUp() const { return ignoreMarkUp_; }
91 bool getStrikeOut() const { return ignoreStrikeOut_; }
93 bool getSectioning() const { return ignoreSectioning_; }
95 bool getFrontMatter() const { return ignoreFrontMatter_; }
97 bool getColor() const { return ignoreColor_; }
99 bool getLanguage() const { return ignoreLanguage_; }
101 void setIgnoreFormat(string const & type, bool value);
105 bool ignoreFamily_ = false;
107 bool ignoreSeries_ = false;
109 bool ignoreShape_ = false;
111 bool ignoreUnderline_ = false;
113 bool ignoreMarkUp_ = false;
115 bool ignoreStrikeOut_ = false;
117 bool ignoreSectioning_ = false;
119 bool ignoreFrontMatter_ = false;
121 bool ignoreColor_ = false;
123 bool ignoreLanguage_ = false;
127 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
129 if (type == "color") {
130 ignoreColor_ = value;
132 else if (type == "language") {
133 ignoreLanguage_ = value;
135 else if (type == "sectioning") {
136 ignoreSectioning_ = value;
137 ignoreFrontMatter_ = value;
139 else if (type == "font") {
140 ignoreSeries_ = value;
141 ignoreShape_ = value;
142 ignoreFamily_ = value;
144 else if (type == "series") {
145 ignoreSeries_ = value;
147 else if (type == "shape") {
148 ignoreShape_ = value;
150 else if (type == "family") {
151 ignoreFamily_ = value;
153 else if (type == "markup") {
154 ignoreMarkUp_ = value;
156 else if (type == "underline") {
157 ignoreUnderline_ = value;
159 else if (type == "strike") {
160 ignoreStrikeOut_ = value;
164 // The global variable that can be changed from outside
165 IgnoreFormats ignoreFormats;
168 void setIgnoreFormat(string const & type, bool value)
170 ignoreFormats.setIgnoreFormat(type, value);
176 bool parse_bool(docstring & howto)
181 howto = split(howto, var, ' ');
189 MatchString(docstring const & s, bool cs, bool mw)
190 : str(s), case_sens(cs), whole_words(mw)
193 // returns true if the specified string is at the specified position
194 // del specifies whether deleted strings in ct mode will be considered
195 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
197 return par.find(str, case_sens, whole_words, pos, del);
205 // match whole words only
210 int findForward(DocIterator & cur, MatchString const & match,
211 bool find_del = true)
213 for (; cur; cur.forwardChar())
214 if (cur.inTexted()) {
215 int len = match(cur.paragraph(), cur.pos(), find_del);
223 int findBackwards(DocIterator & cur, MatchString const & match,
224 bool find_del = true)
228 if (cur.inTexted()) {
229 int len = match(cur.paragraph(), cur.pos(), find_del);
238 bool searchAllowed(docstring const & str)
241 frontend::Alert::error(_("Search error"), _("Search string is empty"));
248 bool findOne(BufferView * bv, docstring const & searchstr,
249 bool case_sens, bool whole, bool forward,
250 bool find_del = true, bool check_wrap = false)
252 if (!searchAllowed(searchstr))
255 DocIterator cur = forward
256 ? bv->cursor().selectionEnd()
257 : bv->cursor().selectionBegin();
259 MatchString const match(searchstr, case_sens, whole);
261 int match_len = forward
262 ? findForward(cur, match, find_del)
263 : findBackwards(cur, match, find_del);
266 bv->putSelectionAt(cur, match_len, !forward);
267 else if (check_wrap) {
268 DocIterator cur_orig(bv->cursor());
271 q = _("End of file reached while searching forward.\n"
272 "Continue searching from the beginning?");
274 q = _("Beginning of file reached while searching backward.\n"
275 "Continue searching from the end?");
276 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
277 q, 0, 1, _("&Yes"), _("&No"));
278 if (wrap_answer == 0) {
280 bv->cursor().clear();
281 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
283 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
284 bv->cursor().backwardPos();
286 bv->clearSelection();
287 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
290 bv->cursor().setCursor(cur_orig);
294 return match_len > 0;
298 int replaceAll(BufferView * bv,
299 docstring const & searchstr, docstring const & replacestr,
300 bool case_sens, bool whole)
302 Buffer & buf = bv->buffer();
304 if (!searchAllowed(searchstr) || buf.isReadonly())
307 DocIterator cur_orig(bv->cursor());
309 MatchString const match(searchstr, case_sens, whole);
312 int const rsize = replacestr.size();
313 int const ssize = searchstr.size();
316 cur.setCursor(doc_iterator_begin(&buf));
317 int match_len = findForward(cur, match, false);
318 while (match_len > 0) {
319 // Backup current cursor position and font.
320 pos_type const pos = cur.pos();
321 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
323 int striked = ssize -
324 cur.paragraph().eraseChars(pos, pos + match_len,
325 buf.params().track_changes);
326 cur.paragraph().insert(pos, replacestr, font,
327 Change(buf.params().track_changes
329 : Change::UNCHANGED));
330 for (int i = 0; i < rsize + striked; ++i)
333 match_len = findForward(cur, match, false);
336 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
338 cur_orig.fixIfBroken();
339 bv->setCursor(cur_orig);
345 // the idea here is that we are going to replace the string that
346 // is selected IF it is the search string.
347 // if there is a selection, but it is not the search string, then
348 // we basically ignore it. (FIXME We ought to replace only within
350 // if there is no selection, then:
351 // (i) if some search string has been provided, then we find it.
352 // (think of how the dialog works when you hit "replace" the
354 // (ii) if no search string has been provided, then we treat the
355 // word the cursor is in as the search string. (why? i have no
356 // idea.) but this only works in text?
358 // returns the number of replacements made (one, if any) and
359 // whether anything at all was done.
360 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
361 docstring const & replacestr, bool case_sens,
362 bool whole, bool forward, bool findnext)
364 Cursor & cur = bv->cursor();
365 if (!cur.selection()) {
366 // no selection, non-empty search string: find it
367 if (!searchstr.empty()) {
368 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
369 return make_pair(found, 0);
371 // empty search string
374 return make_pair(false, 0);
375 // select current word and treat it as the search string.
376 // This causes a minor bug as undo will restore this selection,
377 // which the user did not create (#8986).
378 cur.innerText()->selectWord(cur, WHOLE_WORD);
379 searchstr = cur.selectionAsString(false);
382 // if we still don't have a search string, report the error
384 if (!searchAllowed(searchstr))
385 return make_pair(false, 0);
387 bool have_selection = cur.selection();
388 docstring const selected = cur.selectionAsString(false);
391 ? searchstr == selected
392 : compare_no_case(searchstr, selected) == 0;
394 // no selection or current selection is not search word:
395 // just find the search word
396 if (!have_selection || !match) {
397 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
398 return make_pair(found, 0);
401 // we're now actually ready to replace. if the buffer is
402 // read-only, we can't, though.
403 if (bv->buffer().isReadonly())
404 return make_pair(false, 0);
406 cap::replaceSelectionWithString(cur, replacestr);
408 cur.pos() += replacestr.length();
409 LASSERT(cur.pos() <= cur.lastpos(),
410 cur.pos() = cur.lastpos());
413 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
415 return make_pair(true, 1);
421 docstring const find2string(docstring const & search,
422 bool casesensitive, bool matchword, bool forward)
426 << int(casesensitive) << ' '
427 << int(matchword) << ' '
433 docstring const replace2string(docstring const & replace,
434 docstring const & search,
435 bool casesensitive, bool matchword,
436 bool all, bool forward, bool findnext)
439 ss << replace << '\n'
441 << int(casesensitive) << ' '
442 << int(matchword) << ' '
444 << int(forward) << ' '
450 bool lyxfind(BufferView * bv, FuncRequest const & ev)
452 if (!bv || ev.action() != LFUN_WORD_FIND)
455 //lyxerr << "find called, cmd: " << ev << endl;
457 // data is of the form
459 // <casesensitive> <matchword> <forward>"
461 docstring howto = split(ev.argument(), search, '\n');
463 bool casesensitive = parse_bool(howto);
464 bool matchword = parse_bool(howto);
465 bool forward = parse_bool(howto);
467 return findOne(bv, search, casesensitive, matchword, forward, true, true);
471 bool lyxreplace(BufferView * bv,
472 FuncRequest const & ev, bool has_deleted)
474 if (!bv || ev.action() != LFUN_WORD_REPLACE)
477 // data is of the form
480 // <casesensitive> <matchword> <all> <forward> <findnext>"
483 docstring howto = split(ev.argument(), rplc, '\n');
484 howto = split(howto, search, '\n');
486 bool casesensitive = parse_bool(howto);
487 bool matchword = parse_bool(howto);
488 bool all = parse_bool(howto);
489 bool forward = parse_bool(howto);
490 bool findnext = howto.empty() ? true : parse_bool(howto);
495 int replace_count = 0;
497 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
498 update = replace_count > 0;
501 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
503 replace_count = rv.second;
506 Buffer const & buf = bv->buffer();
508 // emit message signal.
509 buf.message(_("String not found."));
511 if (replace_count == 0) {
512 buf.message(_("String found."));
513 } else if (replace_count == 1) {
514 buf.message(_("String has been replaced."));
516 docstring const str =
517 bformat(_("%1$d strings have been replaced."), replace_count);
521 } else if (findnext) {
522 // if we have deleted characters, we do not replace at all, but
523 // rather search for the next occurence
524 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
527 bv->message(_("String not found."));
533 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
535 for (; cur; cur.forwardPos())
536 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
540 DocIterator cur_orig(bv->cursor());
541 docstring q = _("End of file reached while searching forward.\n"
542 "Continue searching from the beginning?");
543 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
544 q, 0, 1, _("&Yes"), _("&No"));
545 if (wrap_answer == 0) {
546 bv->cursor().clear();
547 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
548 bv->clearSelection();
549 cur.setCursor(bv->cursor().selectionBegin());
550 if (findNextChange(bv, cur, false))
553 bv->cursor().setCursor(cur_orig);
560 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
562 for (cur.backwardPos(); cur; cur.backwardPos()) {
563 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
568 DocIterator cur_orig(bv->cursor());
569 docstring q = _("Beginning of file reached while searching backward.\n"
570 "Continue searching from the end?");
571 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
572 q, 0, 1, _("&Yes"), _("&No"));
573 if (wrap_answer == 0) {
574 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
575 bv->cursor().backwardPos();
576 bv->clearSelection();
577 cur.setCursor(bv->cursor().selectionBegin());
578 if (findPreviousChange(bv, cur, false))
581 bv->cursor().setCursor(cur_orig);
588 bool selectChange(Cursor & cur, bool forward)
590 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
592 Change ch = cur.paragraph().lookupChange(cur.pos());
594 CursorSlice tip1 = cur.top();
595 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
596 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
597 if (!ch2.isSimilarTo(ch))
600 CursorSlice tip2 = cur.top();
601 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
603 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
604 if (!ch2.isSimilarTo(ch)) {
605 // take a step forward to correctly set the selection
613 cur.bv().mouseSetCursor(cur, false);
615 cur.bv().mouseSetCursor(cur, true);
623 bool findChange(BufferView * bv, bool forward)
626 cur.setCursor(forward ? bv->cursor().selectionEnd()
627 : bv->cursor().selectionBegin());
628 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
629 return selectChange(cur, forward);
634 bool findNextChange(BufferView * bv)
636 return findChange(bv, true);
640 bool findPreviousChange(BufferView * bv)
642 return findChange(bv, false);
649 typedef vector<pair<string, string> > Escapes;
651 /// A map of symbols and their escaped equivalent needed within a regex.
652 /// @note Beware of order
653 Escapes const & get_regexp_escapes()
655 typedef std::pair<std::string, std::string> P;
657 static Escapes escape_map;
658 if (escape_map.empty()) {
659 escape_map.push_back(P("$", "_x_$"));
660 escape_map.push_back(P("{", "_x_{"));
661 escape_map.push_back(P("}", "_x_}"));
662 escape_map.push_back(P("[", "_x_["));
663 escape_map.push_back(P("]", "_x_]"));
664 escape_map.push_back(P("(", "_x_("));
665 escape_map.push_back(P(")", "_x_)"));
666 escape_map.push_back(P("+", "_x_+"));
667 escape_map.push_back(P("*", "_x_*"));
668 escape_map.push_back(P(".", "_x_."));
669 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
670 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
671 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
672 escape_map.push_back(P("_x_", "\\"));
677 /// A map of lyx escaped strings and their unescaped equivalent.
678 Escapes const & get_lyx_unescapes()
680 typedef std::pair<std::string, std::string> P;
682 static Escapes escape_map;
683 if (escape_map.empty()) {
684 escape_map.push_back(P("\\%", "%"));
685 escape_map.push_back(P("\\{", "{"));
686 escape_map.push_back(P("\\}", "}"));
687 escape_map.push_back(P("\\mathcircumflex ", "^"));
688 escape_map.push_back(P("\\mathcircumflex", "^"));
689 escape_map.push_back(P("\\backslash ", "\\"));
690 escape_map.push_back(P("\\backslash", "\\"));
691 escape_map.push_back(P("\\sim ", "~"));
692 escape_map.push_back(P("\\sim", "~"));
697 /// A map of escapes turning a regexp matching text to one matching latex.
698 Escapes const & get_regexp_latex_escapes()
700 typedef std::pair<std::string, std::string> P;
702 static Escapes escape_map;
703 if (escape_map.empty()) {
704 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
705 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
706 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
707 escape_map.push_back(P("\\[", "\\{\\[\\}"));
708 escape_map.push_back(P("\\]", "\\{\\]\\}"));
709 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
710 escape_map.push_back(P("%", "\\\\\\%"));
711 escape_map.push_back(P("#", "\\\\#"));
716 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
717 ** the found occurrence were escaped.
719 string apply_escapes(string s, Escapes const & escape_map)
721 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
722 Escapes::const_iterator it;
723 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
724 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
725 unsigned int pos = 0;
726 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
727 s.replace(pos, it->first.length(), it->second);
728 LYXERR(Debug::FIND, "After escape: " << s);
729 pos += it->second.length();
730 // LYXERR(Debug::FIND, "pos: " << pos);
733 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
738 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
739 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
740 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
741 string escape_for_regex(string s, bool match_latex)
744 while (pos < s.size()) {
745 size_t new_pos = s.find("\\regexp{", pos);
746 if (new_pos == string::npos)
751 LYXERR(Debug::FIND, "new_pos: " << new_pos);
752 t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
753 LYXERR(Debug::FIND, "t [lyx]: " << t);
754 t = apply_escapes(t, get_regexp_escapes());
755 LYXERR(Debug::FIND, "t [rxp]: " << t);
756 s.replace(pos, new_pos - pos, t);
757 new_pos = pos + t.size();
758 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
759 LYXERR(Debug::FIND, "new_pos: " << new_pos);
760 if (new_pos == s.size())
763 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
764 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
765 LYXERR(Debug::FIND, "end_pos: " << end_pos);
766 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
767 LYXERR(Debug::FIND, "t in regexp : " << t);
768 t = apply_escapes(t, get_lyx_unescapes());
769 LYXERR(Debug::FIND, "t in regexp after unescapes [lyx]: " << t);
771 t = apply_escapes(t, get_regexp_latex_escapes());
772 LYXERR(Debug::FIND, "t in regexp after latex_escapes [ltx]: " << t);
774 if (end_pos == s.size()) {
775 s.replace(new_pos, end_pos - new_pos, t);
776 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
779 s.replace(new_pos, end_pos + 13 - new_pos, t);
780 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
781 pos = new_pos + t.size();
782 LYXERR(Debug::FIND, "pos: " << pos);
788 /// Wrapper for lyx::regex_replace with simpler interface
789 bool regex_replace(string const & s, string & t, string const & searchstr,
790 string const & replacestr)
792 regex e(searchstr, regex_constants::ECMAScript);
794 ostream_iterator<char, char> it(oss);
795 regex_replace(it, s.begin(), s.end(), e, replacestr);
796 // tolerate t and s be references to the same variable
797 bool rv = (s != oss.str());
803 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
805 ** Verify that closed braces exactly match open braces. This avoids that, for example,
806 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
809 ** Number of open braces that must remain open at the end for the verification to succeed.
812 bool braces_match(QString const & beg,
815 bool braces_match(string const & beg,
821 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg.toStdString() << "'");
823 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << beg << "'");
825 int lastidx = beg.size();
826 for (int i=0; i < lastidx; ++i) {
827 // Skip escaped braces in the count
837 } else if (c == '{') {
839 } else if (c == '}') {
840 if (open_pars == 0) {
841 LYXERR(Debug::FIND, "Found unmatched closed brace");
847 if (open_pars != unmatched) {
848 LYXERR(Debug::FIND, "Found " << open_pars
849 << " instead of " << unmatched
850 << " unmatched open braces at the end of count");
853 LYXERR(Debug::FIND, "Braces match as expected");
870 vector <string> result = vector <string>();
871 MatchResult(int len = 0): match_len(len),match_prefix(0),match2end(0), pos(0),leadsize(0) {};
874 static MatchResult::range interpretMatch(MatchResult &oldres, MatchResult &newres)
876 int range = oldres.match_len;
877 if (range < 2) range = 2;
878 if (newres.match2end < oldres.match2end - oldres.match_len)
879 return MatchResult::newIsTooFar;
880 if (newres.match_len < oldres.match_len)
881 return MatchResult::newIsTooFar;
882 if ((newres.match_len == oldres.match_len) &&
883 (newres.match2end < oldres.match2end + range) &&
884 (newres.match2end > oldres.match2end - range)) {
885 return MatchResult::newIsBetter;
887 return MatchResult::newIsInvalid;
890 /** The class performing a match between a position in the document and the FindAdvOptions.
893 class MatchStringAdv {
895 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
897 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
898 ** constructor as opt.search, under the opt.* options settings.
901 ** If set, then match is searched only against beginning of text starting at cur.
902 ** If unset, then match is searched anywhere in text starting at cur.
905 ** The length of the matching text, or zero if no match was found.
907 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
916 /// first buffer on which search was started
917 lyx::Buffer * const p_first_buf;
919 FindAndReplaceOptions const & opt;
922 /// Auxiliary find method (does not account for opt.matchword)
923 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
925 /** Normalize a stringified or latexified LyX paragraph.
929 ** <li>if search is not casesensitive, then lowercase the string;
930 ** <li>remove any newline at begin or end of the string;
931 ** <li>replace any newline in the middle of the string with a simple space;
932 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
935 ** @todo Normalization should also expand macros, if the corresponding
936 ** search option was checked.
938 string normalize(docstring const & s, bool hack_braces) const;
939 // normalized string to search
940 string par_as_string;
941 // regular expression to use for searching
942 // regexp2 is same as regexp, but prefixed with a ".*?"
944 QRegularExpression regexp;
945 QRegularExpression regexp2;
950 // leading format material as string
951 string lead_as_string;
952 // par_as_string after removal of lead_as_string
953 string par_as_string_nolead;
954 // unmatched open braces in the search string/regexp
956 // number of (.*?) subexpressions added at end of search regexp for closing
957 // environments, math mode, styles, etc...
960 // Are we searching with regular expressions ?
963 vector <string> matches = vector <string>(10);
964 void FillResults(MatchResult &found_mr);
967 void MatchStringAdv::FillResults(MatchResult &found_mr)
969 if (found_mr.match_len > 0) {
970 valid_matches = found_mr.result.size();
971 for (size_t i = 0; i < found_mr.result.size(); i++)
972 matches[i] = found_mr.result[i];
978 static docstring buffer_to_latex(Buffer & buffer)
980 //OutputParams runparams(&buffer.params().encoding());
981 OutputParams runparams(encodings.fromLyXName("utf8"));
982 odocstringstream ods;
984 runparams.nice = true;
985 runparams.flavor = Flavor::XeTeX;
986 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
987 // No side effect of file copying and image conversion
988 runparams.dryrun = true;
989 runparams.for_search = true;
990 pit_type const endpit = buffer.paragraphs().size();
991 for (pit_type pit = 0; pit != endpit; ++pit) {
992 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
993 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
999 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
1002 if (!opt.ignoreformat) {
1003 str = buffer_to_latex(buffer);
1005 // OutputParams runparams(&buffer.params().encoding());
1006 OutputParams runparams(encodings.fromLyXName("utf8"));
1007 runparams.nice = true;
1008 runparams.flavor = Flavor::XeTeX;
1009 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
1010 runparams.dryrun = true;
1011 runparams.for_search = true;
1012 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
1013 Paragraph const & par = buffer.paragraphs().at(pit);
1014 LYXERR(Debug::FIND, "Adding to search string: '"
1015 << par.asString(pos_type(0), par.size(),
1016 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1019 str += par.asString(pos_type(0), par.size(),
1020 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1023 // Even in ignore-format we have to remove "\text{}, \lyxmathsym{}" parts
1024 string t = to_utf8(str);
1025 while (regex_replace(t, t, "\\\\(text|lyxmathsym)\\{([^\\}]*)\\}", "$2"));
1032 /// Return separation pos between the leading material and the rest
1033 static size_t identifyLeading(string const & s)
1036 // @TODO Support \item[text]
1037 // Kornel: Added textsl, textsf, textit, texttt and noun
1038 // + allow to search for colored text too
1039 while (regex_replace(t, t, "^\\\\(("
1040 "(author|title|subtitle|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|"
1041 "lyxaddress|lyxrightaddress|"
1042 "footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1043 "emph|noun|minisec|text(bf|md|sl|sf|it|tt))|"
1044 "((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|"
1045 "(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
1046 || regex_replace(t, t, "^\\$", "")
1047 || regex_replace(t, t, "^\\\\\\[", "")
1048 || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
1049 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
1051 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
1056 * Given a latexified string, retrieve some handled features
1057 * The features of the regex will later be compared with the features
1058 * of the searched text. If the regex features are not a
1059 * subset of the analized, then, in not format ignoring search
1060 * we can early stop the search in the relevant inset.
1062 typedef map<string, bool> Features;
1064 static Features identifyFeatures(string const & s)
1066 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
1067 static regex const valid("^("
1069 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
1070 "emph|noun|text(bf|md|sl|sf|it|tt)|"
1071 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
1072 "(u|uu)line|(s|x)out|uwave|"
1073 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
1074 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1079 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1082 if (sub.str(1).compare("regexp") == 0) {
1086 string token = sub.str(1);
1088 if (regex_match(token, sub2, valid)) {
1096 if (sub.str(1).compare("endregexp") == 0) {
1106 * defines values features of a key "\\[a-z]+{"
1111 /* Char type with content discarded
1112 * like \hspace{1cm} */
1114 /* Char, like \backslash */
1116 /* replace starting backslash with '#' */
1118 /* \part, \section*, ... */
1120 /* title, author etc */
1122 /* \foreignlanguage{ngerman}, ... */
1125 * to discard language in content */
1128 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1130 /* fonts, colors, markups, ... */
1132 /* footnotesize, ... large, ...
1133 * Ignore all of them */
1136 /* inputencoding, ...
1137 * Discard also content, because they do not help in search */
1140 * like remove, but also all arguments */
1142 /* item, listitem */
1144 /* tex, latex, ... like isChar */
1146 /* like \lettrine[lines=5]{}{} */
1148 // like isStandard, but always remove head
1150 /* End of arguments marker for lettrine,
1151 * so that they can be ignored */
1154 KeyInfo() = default;
1155 KeyInfo(KeyType type, int parcount, bool disable)
1157 parenthesiscount(parcount),
1158 disabled(disable) {}
1159 KeyType keytype = invalid;
1161 int _tokensize = -1;
1162 int _tokenstart = -1;
1163 int _dataStart = -1;
1165 int parenthesiscount = 1;
1166 bool disabled = false;
1167 bool used = false; /* by pattern */
1172 Border(int l=0, int u=0) : low(l), upper(u) {};
1177 #define MAXOPENED 30
1179 bool isPatternString_;
1181 explicit Intervall(bool isPattern, string const & p) :
1182 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1183 hasTitle(false), langcount(0)
1191 static vector<Border> borders;
1192 int depts[MAXOPENED];
1193 int closes[MAXOPENED];
1194 int actualdeptindex;
1195 int previousNotIgnored(int) const;
1196 int nextNotIgnored(int) const;
1197 void handleOpenP(int i);
1198 void handleCloseP(int i, bool closingAllowed);
1199 void resetOpenedP(int openPos);
1200 void addIntervall(int upper);
1201 void addIntervall(int low, int upper); /* if explicit */
1202 void removeAccents();
1203 void setForDefaultLang(KeyInfo const & defLang) const;
1204 int findclosing(int start, int end, char up, char down, int repeat);
1205 void handleParentheses(int lastpos, bool closingAllowed);
1207 int langcount; // Number of disabled language specs up to current position in actual interval
1208 int isOpeningPar(int pos) const;
1210 void output(ostringstream &os, int lastpos);
1211 // string show(int lastpos);
1214 vector<Border> Intervall::borders = vector<Border>(30);
1216 int Intervall::isOpeningPar(int pos) const
1218 if ((pos < 0) || (size_t(pos) >= par.size()))
1220 if (par[pos] != '{')
1222 if (size_t(pos) + 2 >= par.size())
1224 if (par[pos+2] != '}')
1226 if (par[pos+1] == '[' || par[pos+1] == ']')
1231 void Intervall::setForDefaultLang(KeyInfo const & defLang) const
1233 // Enable the use of first token again
1234 if (ignoreidx >= 0) {
1235 int value = defLang._tokenstart + defLang._tokensize;
1241 if (borders[borderidx].low < value)
1242 borders[borderidx].low = value;
1243 if (borders[borderidx].upper < value)
1244 borders[borderidx].upper = value;
1249 static void checkDepthIndex(int val)
1251 static int maxdepthidx = MAXOPENED-2;
1252 static int lastmaxdepth = 0;
1253 if (val > lastmaxdepth) {
1254 LYXERR(Debug::INFO, "Depth reached " << val);
1257 if (val > maxdepthidx) {
1259 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1264 // Not needed, because borders are now dynamically expanded
1265 static void checkIgnoreIdx(int val)
1267 static int lastmaxignore = -1;
1268 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1269 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1270 lastmaxignore = val;
1276 * Expand the region of ignored parts of the input latex string
1277 * The region is only relevant in output()
1279 void Intervall::addIntervall(int low, int upper)
1282 if (low == upper) return;
1283 for (idx = ignoreidx+1; idx > 0; --idx) {
1284 if (low > borders[idx-1].upper) {
1288 Border br(low, upper);
1289 if (idx > ignoreidx) {
1290 if (borders.size() <= size_t(idx)) {
1291 borders.push_back(br);
1297 // checkIgnoreIdx(ignoreidx);
1301 // Expand only if one of the new bound is inside the interwall
1302 // We know here that br.low > borders[idx-1].upper
1303 if (br.upper < borders[idx].low) {
1304 // We have to insert at this pos
1305 if (size_t(ignoreidx+1) >= borders.size()) {
1306 borders.push_back(borders[ignoreidx]);
1309 borders[ignoreidx+1] = borders[ignoreidx];
1311 for (int i = ignoreidx; i > idx; --i) {
1312 borders[i] = borders[i-1];
1316 // checkIgnoreIdx(ignoreidx);
1319 // Here we know, that we are overlapping
1320 if (br.low > borders[idx].low)
1321 br.low = borders[idx].low;
1322 // check what has to be concatenated
1324 for (int i = idx; i <= ignoreidx; i++) {
1325 if (br.upper >= borders[i].low) {
1327 if (br.upper < borders[i].upper)
1328 br.upper = borders[i].upper;
1334 // count should be >= 1 here
1337 for (int i = idx + count; i <= ignoreidx; i++) {
1338 borders[i-count+1] = borders[i];
1340 ignoreidx -= count - 1;
1346 typedef map<string, string> AccentsMap;
1347 static AccentsMap accents = map<string, string>();
1349 static void buildaccent(string n, string param, string values)
1353 const char delim = '|';
1354 while (getline(s, name, delim)) {
1356 for (char c : param) {
1357 string key = name + "{" + c + "}";
1358 // get the corresponding utf8-value
1359 if ((values[start] & 0xc0) != 0xc0) {
1360 // should not happen, utf8 encoding starts at least with 11xxxxxx
1361 // but value for '\dot{i}' is 'i', which is ascii
1362 if ((values[start] & 0x80) == 0) {
1364 accents[key] = values.substr(start, 1);
1365 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1370 for (int j = 1; ;j++) {
1371 if (start + j >= values.size()) {
1372 accents[key] = values.substr(start, j);
1373 start = values.size() - 1;
1376 else if ((values[start+j] & 0xc0) != 0x80) {
1377 // This is the first byte of following utf8 char
1378 accents[key] = values.substr(start, j);
1380 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1389 static string getutf8(unsigned uchar)
1392 string ret = string();
1394 if (uchar <= 0x7f) {
1395 c[maxc-1] = uchar & 0x7f;
1398 unsigned char rest = 0x40;
1399 unsigned char first = 0x80;
1401 for (int i = start; i >=0; --i) {
1403 c[i] = first + uchar;
1406 c[i] = 0x80 | (uchar & 0x3f);
1413 for (int i = 0; i < maxc; i++) {
1414 if (c[i] == 0) continue;
1420 static void buildAccentsMap()
1422 accents["imath"] = "ı";
1424 accents["jmath"] = "ȷ";
1425 accents["cdot"] = "·";
1426 accents["guillemotright"] = "»";
1427 accents["guillemotleft"] = "«";
1428 accents["hairspace"] = getutf8(0xf0000); // select from free unicode plane 15
1429 accents["thinspace"] = getutf8(0xf0002); // and used _only_ by findadv
1430 accents["negthinspace"] = getutf8(0xf0003); // to omit backslashed latex macros
1431 accents["medspace"] = getutf8(0xf0004); // See https://en.wikipedia.org/wiki/Private_Use_Areas
1432 accents["negmedspace"] = getutf8(0xf0005);
1433 accents["thickspace"] = getutf8(0xf0006);
1434 accents["negthickspace"] = getutf8(0xf0007);
1435 accents["lyx"] = getutf8(0xf0010); // Used logos
1436 accents["LyX"] = getutf8(0xf0010);
1437 accents["tex"] = getutf8(0xf0011);
1438 accents["TeX"] = getutf8(0xf0011);
1439 accents["latex"] = getutf8(0xf0012);
1440 accents["LaTeX"] = getutf8(0xf0012);
1441 accents["latexe"] = getutf8(0xf0013);
1442 accents["LaTeXe"] = getutf8(0xf0013);
1443 accents["lyxarrow"] = getutf8(0xf0020);
1444 accents["backslash lyx"] = getutf8(0xf0010); // Used logos inserted with starting \backslash
1445 accents["backslash LyX"] = getutf8(0xf0010);
1446 accents["backslash tex"] = getutf8(0xf0011);
1447 accents["backslash TeX"] = getutf8(0xf0011);
1448 accents["backslash latex"] = getutf8(0xf0012);
1449 accents["backslash LaTeX"] = getutf8(0xf0012);
1450 accents["backslash latexe"] = getutf8(0xf0013);
1451 accents["backslash LaTeXe"] = getutf8(0xf0013);
1452 accents["backslash lyxarrow"] = getutf8(0xf0020);
1453 accents["ddot{\\imath}"] = "ï";
1454 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1455 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1456 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1457 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1458 accents["acute{\\imath}"] = "í";
1459 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1460 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1461 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1462 buildaccent("mathring|r", "aAuUwy",
1464 accents["check{\\imath}"] = "ǐ";
1465 accents["check{\\jmath}"] = "ǰ";
1466 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1467 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1468 accents["hat{\\imath}"] = "î";
1469 accents["hat{\\jmath}"] = "ĵ";
1470 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1471 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1472 accents["bar{\\imath}"] = "ī";
1473 buildaccent("bar|=", "aAeEiIoOuUyY",
1474 "āĀēĒīĪōŌūŪȳȲ"); // macron
1475 accents["tilde{\\imath}"] = "ĩ";
1476 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1477 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1478 accents["breve{\\imath}"] = "ĭ";
1479 buildaccent("breve|u", "aAeEgGiIoOuU",
1480 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1481 accents["grave{\\imath}"] = "ì";
1482 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1483 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1484 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1485 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1486 buildaccent("ogonek|k", "AaEeIiUuOo",
1487 "ĄąĘęĮįŲųǪǫ"); // ogonek
1488 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1489 "ÇçĢģĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1490 buildaccent("subring|textsubring", "Aa",
1492 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1493 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1494 buildaccent("subtilde|textsubtilde", "EeIiUu",
1495 "ḚḛḬḭṴṵ"); // subtilde
1496 accents["dgrave{\\imath}"] = "ȉ";
1497 accents["textdoublegrave{\\i}"] = "ȉ";
1498 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1499 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1500 accents["rcap{\\imath}"] = "ȉ";
1501 accents["textroundcap{\\i}"] = "ȉ";
1502 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1503 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1504 buildaccent("slashed", "oO",
1509 * Created accents in math or regexp environment
1510 * are macros, but we need the utf8 equivalent
1512 void Intervall::removeAccents()
1514 if (accents.empty())
1516 static regex const accre("\\\\(([\\S]|grave|breve|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|"
1517 "cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}"
1518 "|((i|imath|jmath|cdot|[a-z]+space)|((backslash )?([lL]y[xX]|[tT]e[xX]|[lL]a[tT]e[xX]e?|lyxarrow))|guillemot(left|right))(?![a-zA-Z]))");
1520 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1522 string key = sub.str(1);
1523 if (accents.find(key) != accents.end()) {
1524 string val = accents[key];
1525 size_t pos = sub.position(size_t(0));
1526 for (size_t i = 0; i < val.size(); i++) {
1527 par[pos+i] = val[i];
1529 // Remove possibly following space too
1530 if (par[pos+sub.str(0).size()] == ' ')
1531 addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
1533 addIntervall(pos+val.size(), pos + sub.str(0).size());
1534 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1535 // remove traces of any remaining chars
1540 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1545 void Intervall::handleOpenP(int i)
1548 depts[actualdeptindex] = i+1;
1549 closes[actualdeptindex] = -1;
1550 checkDepthIndex(actualdeptindex);
1553 void Intervall::handleCloseP(int i, bool closingAllowed)
1555 if (actualdeptindex <= 0) {
1556 if (! closingAllowed)
1557 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1558 // if we are at the very end
1559 addIntervall(i, i+1);
1562 closes[actualdeptindex] = i+1;
1567 void Intervall::resetOpenedP(int openPos)
1569 // Used as initializer for foreignlanguage entry
1570 actualdeptindex = 1;
1571 depts[1] = openPos+1;
1575 int Intervall::previousNotIgnored(int start) const
1577 int idx = 0; /* int intervalls */
1578 for (idx = ignoreidx; idx >= 0; --idx) {
1579 if (start > borders[idx].upper)
1581 if (start >= borders[idx].low)
1582 start = borders[idx].low-1;
1587 int Intervall::nextNotIgnored(int start) const
1589 int idx = 0; /* int intervalls */
1590 for (idx = 0; idx <= ignoreidx; idx++) {
1591 if (start < borders[idx].low)
1593 if (start < borders[idx].upper)
1594 start = borders[idx].upper;
1599 typedef map<string, KeyInfo> KeysMap;
1600 typedef vector< KeyInfo> Entries;
1601 static KeysMap keys = map<string, KeyInfo>();
1607 Intervall interval_;
1608 void buildKeys(bool);
1609 void buildEntries(bool);
1610 void makeKey(const string &, KeyInfo, bool isPatternString);
1611 void processRegion(int start, int region_end); /* remove {} parts */
1612 void removeHead(KeyInfo const &, int count=0);
1615 LatexInfo(string const & par, bool isPatternString)
1616 : entidx_(-1), interval_(isPatternString, par)
1618 buildKeys(isPatternString);
1619 entries_ = vector<KeyInfo>();
1620 buildEntries(isPatternString);
1624 if (entries_.empty()) {
1627 if (entries_[0].keytype == KeyInfo::isTitle) {
1628 interval_.hasTitle = true;
1629 if (! entries_[0].disabled) {
1630 interval_.titleValue = entries_[0].head;
1633 interval_.titleValue = "";
1635 removeHead(entries_[0]);
1636 if (entries_.size() > 1)
1645 if (int(entries_.size()) > entidx_) {
1652 bool setNextKey(int idx) {
1653 if ((idx == entidx_) && (entidx_ >= 0)) {
1660 int find(int start, KeyInfo::KeyType keytype) const {
1664 while (tmpIdx < int(entries_.size())) {
1665 if (entries_[tmpIdx].keytype == keytype)
1671 int process(ostringstream & os, KeyInfo const & actual);
1672 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1673 // string show(int lastpos) { return interval.show(lastpos);};
1674 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1675 KeyInfo &getKeyInfo(int keyinfo) {
1676 static KeyInfo invalidInfo = KeyInfo();
1677 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1680 return entries_[keyinfo];
1682 void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
1683 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1687 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1691 for (int i = start; i < end; i += 1 + skip) {
1695 if (c == '\\') skip = 1;
1699 else if (c == down) {
1702 if ((repeat <= 0) || (par[i+1] != up))
1720 vector<MathEntry> entries_;
1725 void insert(string const & wait, size_t start, size_t end) {
1726 MathEntry m = MathEntry();
1728 m.mathStart = start;
1730 m.mathSize = end - start;
1731 entries_.push_back(m);
1733 bool empty() const { return entries_.empty(); };
1734 size_t getEndPos() const {
1735 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1738 return entries_[actualIdx_].mathEnd;
1740 size_t getStartPos() const {
1741 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1742 return 100000; /* definitely enough? */
1744 return entries_[actualIdx_].mathStart;
1746 size_t getFirstPos() {
1748 return getStartPos();
1750 size_t getSize() const {
1751 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1754 return entries_[actualIdx_].mathSize;
1756 void incrEntry() { actualIdx_++; };
1759 void LatexInfo::buildEntries(bool isPatternString)
1761 static regex const rmath("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\})");
1762 static regex const rkeys("(\\\\)*(\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?)))");
1763 static bool disableLanguageOverride = false;
1764 smatch sub, submath;
1765 bool evaluatingRegexp = false;
1767 bool evaluatingMath = false;
1768 bool evaluatingCode = false;
1770 bool evaluatingOptional = false;
1771 size_t optionalEnd = 0;
1774 bool math_end_waiting = false;
1775 size_t math_pos = 10000;
1777 static vector<string> usedText = vector<string>();
1779 interval_.removeAccents();
1781 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1783 if ((submath.position(2) - submath.position(0)) %2 == 1) {
1784 // prefixed by odd count of '\\'
1787 if (math_end_waiting) {
1788 size_t pos = submath.position(size_t(2));
1789 if ((math_end == "$") &&
1790 (submath.str(2) == "$")) {
1791 mi.insert("$", math_pos, pos + 1);
1792 math_end_waiting = false;
1794 else if ((math_end == "\\]") &&
1795 (submath.str(2) == "\\]")) {
1796 mi.insert("\\]", math_pos, pos + 2);
1797 math_end_waiting = false;
1799 else if ((submath.str(3).compare("end") == 0) &&
1800 (submath.str(4).compare(math_end) == 0)) {
1801 mi.insert(math_end, math_pos, pos + submath.str(2).length());
1802 math_end_waiting = false;
1808 if (submath.str(3).compare("begin") == 0) {
1809 math_end_waiting = true;
1810 math_end = submath.str(4);
1811 math_pos = submath.position(size_t(2));
1813 else if (submath.str(2).compare("\\[") == 0) {
1814 math_end_waiting = true;
1816 math_pos = submath.position(size_t(2));
1818 else if (submath.str(2) == "$") {
1819 size_t pos = submath.position(size_t(2));
1820 math_end_waiting = true;
1826 // Ignore language if there is math somewhere in pattern-string
1827 if (isPatternString) {
1828 for (auto s: usedText) {
1829 // Remove entries created in previous search runs
1832 usedText = vector<string>();
1835 keys["foreignlanguage"].disabled = true;
1836 disableLanguageOverride = true;
1839 disableLanguageOverride = false;
1842 if (disableLanguageOverride) {
1843 keys["foreignlanguage"].disabled = true;
1846 math_pos = mi.getFirstPos();
1847 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1849 if ((sub.position(2) - sub.position(0)) %2 == 1) {
1850 // prefixed by odd count of '\\'
1853 string key = sub.str(5);
1855 if (sub.str(2)[0] == '\\')
1856 key = sub.str(2)[1];
1861 if (keys.find(key) != keys.end()) {
1862 if (keys[key].keytype == KeyInfo::headRemove) {
1863 KeyInfo found1 = keys[key];
1864 found1.disabled = true;
1865 found1.head = "\\" + key + "{";
1866 found1._tokenstart = sub.position(size_t(2));
1867 found1._tokensize = found1.head.length();
1868 found1._dataStart = found1._tokenstart + found1.head.length();
1869 int endpos = interval_.findclosing(found1._dataStart, interval_.par.length(), '{', '}', 1);
1870 found1._dataEnd = endpos;
1875 if (evaluatingRegexp) {
1876 if (sub.str(3).compare("endregexp") == 0) {
1877 evaluatingRegexp = false;
1878 // found._tokenstart already set
1879 found._dataEnd = sub.position(size_t(2)) + 13;
1880 found._dataStart = found._dataEnd;
1881 found._tokensize = found._dataEnd - found._tokenstart;
1882 found.parenthesiscount = 0;
1883 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1890 if (evaluatingMath) {
1891 if (size_t(sub.position(size_t(2))) < mi.getEndPos())
1893 evaluatingMath = false;
1895 math_pos = mi.getStartPos();
1897 if (keys.find(key) == keys.end()) {
1898 found = KeyInfo(KeyInfo::isStandard, 0, true);
1899 LYXERR(Debug::INFO, "Undefined key " << key << " ==> will be used as text");
1900 found = KeyInfo(KeyInfo::isText, 0, false);
1901 if (isPatternString) {
1902 found.keytype = KeyInfo::isChar;
1903 found.disabled = false;
1907 usedText.push_back(key);
1911 if (key.compare("regexp") == 0) {
1912 evaluatingRegexp = true;
1913 found._tokenstart = sub.position(size_t(2));
1914 found._tokensize = 0;
1918 // Handle the other params of key
1919 if (found.keytype == KeyInfo::isIgnored)
1921 else if (found.keytype == KeyInfo::isMath) {
1922 if (size_t(sub.position(size_t(2))) == math_pos) {
1924 found._tokenstart = sub.position(size_t(2));
1925 found._tokensize = mi.getSize();
1926 found._dataEnd = found._tokenstart + found._tokensize;
1927 found._dataStart = found._dataEnd;
1928 found.parenthesiscount = 0;
1929 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1930 evaluatingMath = true;
1933 // begin|end of unknown env, discard
1934 // First handle tables
1935 // longtable|tabular
1936 bool discardComment;
1938 found.keytype = KeyInfo::doRemove;
1939 if ((sub.str(7).compare("longtable") == 0) ||
1940 (sub.str(7).compare("tabular") == 0)) {
1941 discardComment = true; /* '%' */
1944 discardComment = false;
1945 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1947 string token = sub.str(7);
1948 if (regex_match(token, sub2, removeArgs)) {
1949 found.keytype = KeyInfo::removeWithArg;
1952 // discard spaces before pos(2)
1953 int pos = sub.position(size_t(2));
1955 for (count = 0; pos - count > 0; count++) {
1956 char c = interval_.par[pos-count-1];
1957 if (discardComment) {
1958 if ((c != ' ') && (c != '%'))
1964 found._tokenstart = pos - count;
1965 if (sub.str(3).compare(0, 5, "begin") == 0) {
1966 size_t pos1 = pos + sub.str(2).length();
1967 if (sub.str(7).compare("cjk") == 0) {
1968 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1969 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1971 found.keytype = KeyInfo::isMain;
1972 found._dataStart = pos1;
1973 found._dataEnd = interval_.par.length();
1974 found.disabled = keys["foreignlanguage"].disabled;
1975 found.used = keys["foreignlanguage"].used;
1976 found._tokensize = pos1 - found._tokenstart;
1977 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1980 // Swallow possible optional params
1981 while (interval_.par[pos1] == '[') {
1982 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1984 // Swallow also the eventual parameter
1985 if (interval_.par[pos1] == '{') {
1986 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1989 found._dataEnd = pos1;
1991 found._dataStart = found._dataEnd;
1992 found._tokensize = count + found._dataEnd - pos;
1993 found.parenthesiscount = 0;
1994 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1995 found.disabled = true;
1999 // Handle "\end{...}"
2000 found._dataStart = pos + sub.str(2).length();
2001 found._dataEnd = found._dataStart;
2002 found._tokensize = count + found._dataEnd - pos;
2003 found.parenthesiscount = 0;
2004 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
2005 found.disabled = true;
2009 else if (found.keytype != KeyInfo::isRegex) {
2010 found._tokenstart = sub.position(size_t(2));
2011 if (found.parenthesiscount == 0) {
2012 // Probably to be discarded
2013 size_t following_pos = sub.position(size_t(2)) + sub.str(5).length() + 1;
2014 char following = interval_.par[following_pos];
2015 if (following == ' ')
2016 found.head = "\\" + sub.str(5) + " ";
2017 else if (following == '=') {
2018 // like \uldepth=1000pt
2019 found.head = sub.str(2);
2022 found.head = "\\" + key;
2023 found._tokensize = found.head.length();
2024 found._dataEnd = found._tokenstart + found._tokensize;
2025 found._dataStart = found._dataEnd;
2028 int params = found._tokenstart + key.length() + 1;
2029 if (evaluatingOptional) {
2030 if (size_t(found._tokenstart) > optionalEnd) {
2031 evaluatingOptional = false;
2034 found.disabled = true;
2037 int optend = params;
2038 while (interval_.par[optend] == '[') {
2039 // discard optional parameters
2040 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
2042 if (optend > params) {
2043 key += interval_.par.substr(params, optend-params);
2044 evaluatingOptional = true;
2045 optionalEnd = optend;
2047 string token = sub.str(7);
2049 if (interval_.par[optend] != '{') {
2051 found.parenthesiscount = 0;
2052 found.head = "\\" + key;
2055 closings = found.parenthesiscount;
2056 if (found.parenthesiscount == 1) {
2057 found.head = "\\" + key + "{";
2059 else if (found.parenthesiscount > 1) {
2061 found.head = sub.str(2) + "{";
2062 closings = found.parenthesiscount - 1;
2065 found.head = "\\" + key + "{";
2068 found._tokensize = found.head.length();
2069 found._dataStart = found._tokenstart + found.head.length();
2070 if (found.keytype == KeyInfo::doRemove) {
2072 size_t endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2073 if (endpar >= interval_.par.length())
2074 found._dataStart = interval_.par.length();
2076 found._dataStart = endpar;
2077 found._tokensize = found._dataStart - found._tokenstart;
2080 found._dataStart = found._tokenstart + found._tokensize;
2084 if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
2085 found._dataStart += 15;
2089 endpos = found._dataStart - 1;
2091 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
2092 if (found.keytype == KeyInfo::isList) {
2093 // Check if it really is list env
2094 static regex const listre("^([a-z]+)$");
2096 if (!regex_match(token, sub2, listre)) {
2097 // Change the key of this entry. It is not in a list/item environment
2098 found.keytype = KeyInfo::endArguments;
2101 if (found.keytype == KeyInfo::noMain) {
2102 evaluatingCode = true;
2104 codeStart = found._dataStart;
2106 else if (evaluatingCode) {
2107 if (size_t(found._dataStart) > codeEnd)
2108 evaluatingCode = false;
2109 else if (found.keytype == KeyInfo::isMain) {
2110 // Disable this key, treate it as standard
2111 found.keytype = KeyInfo::isStandard;
2112 found.disabled = true;
2113 if ((codeEnd +1 >= interval_.par.length()) &&
2114 (found._tokenstart == codeStart)) {
2115 // trickery, because the code inset starts
2116 // with \selectlanguage ...
2118 if (entries_.size() > 1) {
2119 entries_[entries_.size()-1]._dataEnd = codeEnd;
2124 if ((endpos == interval_.par.length()) &&
2125 (found.keytype == KeyInfo::doRemove)) {
2126 // Missing closing => error in latex-input?
2127 // therefore do not delete remaining data
2128 found._dataStart -= 1;
2129 found._dataEnd = found._dataStart;
2132 found._dataEnd = endpos;
2134 if (isPatternString) {
2135 keys[key].used = true;
2138 entries_.push_back(found);
2142 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
2144 stringstream s(keysstring);
2146 const char delim = '|';
2147 while (getline(s, key, delim)) {
2148 KeyInfo keyII(keyI);
2149 if (isPatternString) {
2152 else if ( !keys[key].used)
2153 keyII.disabled = true;
2158 void LatexInfo::buildKeys(bool isPatternString)
2161 static bool keysBuilt = false;
2162 if (keysBuilt && !isPatternString) return;
2164 // Keys to ignore in any case
2165 makeKey("text|textcyrillic|lyxmathsym", KeyInfo(KeyInfo::headRemove, 1, true), true);
2166 // Known standard keys with 1 parameter.
2167 // Split is done, if not at start of region
2168 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
2169 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
2170 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
2171 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
2172 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2173 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2175 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2176 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2177 makeKey("section*|subsection*|subsubsection*|paragraph*",
2178 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2179 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2180 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2182 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2184 // Split is done, if not at start of region
2185 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2186 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2188 // Split is done always.
2189 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2193 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2194 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2195 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2196 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2198 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2199 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2200 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2201 makeKey("thickspace|medspace|thinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2203 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2204 // Custom space/skip, remove the content (== length value)
2205 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2206 // Found in fr/UserGuide.lyx
2207 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2209 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2210 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2211 // Known macros to remove (including their parameter)
2213 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2214 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2215 // handle like standard keys with 1 parameter.
2216 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2218 // Ignore deleted text
2219 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2220 // but preserve added text
2221 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2223 // Macros to remove, but let the parameter survive
2225 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2227 // Remove language spec from content of these insets
2228 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2230 // Same effect as previous, parameter will survive (because there is no one anyway)
2232 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2233 // Remove table decorations
2234 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2235 // Discard shape-header.
2236 // For footnote or shortcut too, because of lang settings
2237 // and wrong handling if used 'KeyInfo::noMain'
2238 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2239 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2240 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2241 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2242 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2243 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2244 // like ('tiny{}' or '\tiny ' ... )
2245 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2247 // Survives, like known character
2248 // makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2249 makeKey("tableofcontents", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2250 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2252 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2253 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2254 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2256 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2257 // Remove RTL/LTR marker
2258 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2259 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2260 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2261 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2262 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2263 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2264 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2265 if (isPatternString) {
2266 // Allow the first searched string to rebuild the keys too
2270 // no need to rebuild again
2276 * Keep the list of actual opened parentheses actual
2277 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2279 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2282 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2286 if (c == '\\') skip = 1;
2287 else if (c == '{') {
2290 else if (c == '}') {
2291 handleCloseP(i, closingAllowed);
2297 string Intervall::show(int lastpos)
2299 int idx = 0; /* int intervalls */
2302 for (idx = 0; idx <= ignoreidx; idx++) {
2303 while (i < lastpos) {
2305 if (i <= borders[idx].low) {
2306 if (borders[idx].low > lastpos)
2307 printsize = lastpos - i;
2309 printsize = borders[idx].low - i;
2310 s += par.substr(i, printsize);
2312 if (i >= borders[idx].low)
2313 i = borders[idx].upper;
2316 i = borders[idx].upper;
2322 s += par.substr(i, lastpos-i);
2328 void Intervall::output(ostringstream &os, int lastpos)
2330 // get number of chars to output
2331 int idx = 0; /* int intervalls */
2334 string startTitle = titleValue;
2335 for (idx = 0; idx <= ignoreidx; idx++) {
2337 if (i <= borders[idx].low) {
2339 if (borders[idx].low > lastpos)
2340 printsize = lastpos - i;
2342 printsize = borders[idx].low - i;
2343 if (printsize > 0) {
2344 os << startTitle << par.substr(i, printsize);
2346 printed += printsize;
2349 handleParentheses(i, false);
2350 if (i >= borders[idx].low)
2351 i = borders[idx].upper;
2354 i = borders[idx].upper;
2361 os << startTitle << par.substr(i, lastpos-i);
2362 printed += lastpos-i;
2364 handleParentheses(lastpos, false);
2366 if (keys["foreignlanguage"].disabled)
2367 startindex = actualdeptindex-langcount;
2369 startindex = actualdeptindex;
2370 for (int i = startindex; i > 0; --i) {
2373 if (hasTitle && (printed > 0))
2375 if (! isPatternString_)
2377 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2380 void LatexInfo::processRegion(int start, int region_end)
2382 while (start < region_end) { /* Let {[} and {]} survive */
2383 int cnt = interval_.isOpeningPar(start);
2385 // Closing is allowed past the region
2386 int closing = interval_.findclosing(start+1, interval_.par.length());
2387 interval_.addIntervall(start, start+1);
2388 interval_.addIntervall(closing, closing+1);
2392 start = interval_.nextNotIgnored(start+1);
2396 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2398 if (actual.parenthesiscount == 0) {
2399 // "{\tiny{} ...}" ==> "{{} ...}"
2400 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2403 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2404 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2405 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2409 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2412 switch (actual.keytype)
2414 case KeyInfo::isTitle: {
2416 nextKeyIdx = getNextKey();
2419 case KeyInfo::cleanToStart: {
2420 actual._dataEnd = actual._dataStart;
2421 nextKeyIdx = getNextKey();
2422 // Search for end of arguments
2423 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2425 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2426 entries_[i].disabled = true;
2428 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2430 while (interval_.par[actual._dataEnd] == ' ')
2432 interval_.addIntervall(0, actual._dataEnd+1);
2433 interval_.actualdeptindex = 0;
2434 interval_.depts[0] = actual._dataEnd+1;
2435 interval_.closes[0] = -1;
2438 case KeyInfo::isText:
2439 interval_.par[actual._tokenstart] = '#';
2440 //interval_.addIntervall(actual._tokenstart, actual._tokenstart+1);
2441 nextKeyIdx = getNextKey();
2443 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2444 if (actual.disabled)
2445 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2447 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2450 case KeyInfo::isChar: {
2451 nextKeyIdx = getNextKey();
2454 case KeyInfo::isSize: {
2455 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2456 if (actual.parenthesiscount == 0)
2457 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2459 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2461 nextKeyIdx = getNextKey();
2463 // Here _dataStart points to '{', so correct it
2464 actual._dataStart += 1;
2465 actual._tokensize += 1;
2466 actual.parenthesiscount = 1;
2467 if (interval_.par[actual._dataStart] == '}') {
2468 // Determine the end if used like '{\tiny{}...}'
2469 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2470 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2473 // Determine the end if used like '\tiny{...}'
2474 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2476 // Split on this key if not at start
2477 int start = interval_.nextNotIgnored(previousStart);
2478 if (start < actual._tokenstart) {
2479 interval_.output(os, actual._tokenstart);
2480 interval_.addIntervall(start, actual._tokenstart);
2482 // discard entry if at end of actual
2483 nextKeyIdx = process(os, actual);
2487 case KeyInfo::endArguments: {
2488 // Remove trailing '{}' too
2489 actual._dataStart += 1;
2490 actual._dataEnd += 1;
2491 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2492 nextKeyIdx = getNextKey();
2495 case KeyInfo::noMain:
2497 case KeyInfo::isStandard: {
2498 if (actual.disabled) {
2500 processRegion(actual._dataStart, actual._dataStart+1);
2501 nextKeyIdx = getNextKey();
2503 // Split on this key if not at datastart of calling entry
2504 int start = interval_.nextNotIgnored(previousStart);
2505 if (start < actual._tokenstart) {
2506 interval_.output(os, actual._tokenstart);
2507 interval_.addIntervall(start, actual._tokenstart);
2509 // discard entry if at end of actual
2510 nextKeyIdx = process(os, actual);
2514 case KeyInfo::removeWithArg: {
2515 nextKeyIdx = getNextKey();
2516 // Search for end of arguments
2517 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2519 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2520 entries_[i].disabled = true;
2522 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2524 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2527 case KeyInfo::doRemove: {
2528 // Remove the key with all parameters and following spaces
2530 for (pos = actual._dataEnd+1; pos < interval_.par.length(); pos++) {
2531 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2534 // Remove also enclosing parentheses [] and {}
2537 while (actual._tokenstart > numpars) {
2538 if (pos+numpars >= interval_.par.size())
2540 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2542 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2548 if (interval_.par[pos+numpars] == ' ')
2552 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2553 nextKeyIdx = getNextKey();
2556 case KeyInfo::isList: {
2557 // Discard space before _tokenstart
2559 for (count = 0; count < actual._tokenstart; count++) {
2560 if (interval_.par[actual._tokenstart-count-1] != ' ')
2563 nextKeyIdx = getNextKey();
2564 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2566 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2568 // How else can we catch this one?
2569 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2570 entries_[i].disabled = true;
2572 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2574 else if (nextKeyIdx > 0) {
2575 // Ignore any lang entries inside data region
2576 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2577 if (entries_[i].keytype == KeyInfo::isMain)
2578 entries_[i].disabled = true;
2581 if (actual.disabled) {
2582 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2585 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2587 if (interval_.par[actual._dataEnd+1] == '[') {
2588 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2589 if ((interval_.par[actual._dataEnd+2] == '{') &&
2590 (interval_.par[posdown-1] == '}')) {
2591 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2592 interval_.addIntervall(posdown-1, posdown+1);
2595 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2596 interval_.addIntervall(posdown, posdown+1);
2598 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2599 if (blk > posdown) {
2600 // Discard at most 1 space after empty item
2602 for (count = 0; count < 1; count++) {
2603 if (interval_.par[blk+count] != ' ')
2607 interval_.addIntervall(blk, blk+count);
2612 case KeyInfo::isSectioning: {
2613 // Discard spaces before _tokenstart
2615 int val = actual._tokenstart;
2616 for (count = 0; count < actual._tokenstart;) {
2617 val = interval_.previousNotIgnored(val-1);
2618 if (val < 0 || interval_.par[val] != ' ')
2621 count = actual._tokenstart - val;
2624 if (actual.disabled) {
2625 removeHead(actual, count);
2626 nextKeyIdx = getNextKey();
2628 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2629 nextKeyIdx = process(os, actual);
2633 case KeyInfo::isMath: {
2634 // Same as regex, use the content unchanged
2635 nextKeyIdx = getNextKey();
2638 case KeyInfo::isRegex: {
2639 // DO NOT SPLIT ON REGEX
2641 nextKeyIdx = getNextKey();
2644 case KeyInfo::isIgnored: {
2645 // Treat like a character for now
2646 nextKeyIdx = getNextKey();
2649 case KeyInfo::isMain: {
2650 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2651 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2652 if (actual._tokenstart > 0) {
2653 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2654 if ((prev >= 0) && interval_.par[prev] == '%')
2655 interval_.addIntervall(prev, prev+1);
2657 if (actual.disabled) {
2659 interval_.langcount++;
2660 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2661 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2662 // Discard also the space before math-equation
2663 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2665 nextKeyIdx = getNextKey();
2666 // interval.resetOpenedP(actual._dataStart-1);
2669 if (actual._tokenstart < 26) {
2670 // for the first (and maybe dummy) language
2671 interval_.setForDefaultLang(actual);
2673 interval_.resetOpenedP(actual._dataStart-1);
2677 case KeyInfo::invalid:
2678 case KeyInfo::headRemove:
2679 // These two cases cannot happen, already handled
2682 // LYXERR(Debug::INFO, "Unhandled keytype");
2683 nextKeyIdx = getNextKey();
2690 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2692 int end = interval_.nextNotIgnored(actual._dataEnd);
2693 int oldStart = actual._dataStart;
2694 int nextKeyIdx = getNextKey();
2696 if ((nextKeyIdx < 0) ||
2697 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2698 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2699 if (oldStart <= end) {
2700 processRegion(oldStart, end);
2705 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2707 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2708 (void) dispatch(os, actual._dataStart, nextKey);
2709 end = nextKey._tokenstart;
2712 processRegion(oldStart, nextKey._tokenstart);
2713 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2715 oldStart = nextKey._dataEnd+1;
2717 // now nextKey is either invalid or is outside of actual._dataEnd
2718 // output the remaining and discard myself
2719 if (oldStart <= end) {
2720 processRegion(oldStart, end);
2722 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2724 // This is the normal case.
2725 // But if using the firstlanguage, the closing may be missing
2727 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2729 if (actual._dataEnd < end)
2730 output_end = interval_.nextNotIgnored(actual._dataEnd);
2731 else if (interval_.par.size() > (size_t) end)
2732 output_end = interval_.nextNotIgnored(end);
2734 output_end = interval_.par.size();
2735 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2736 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2738 // Remove possible empty data
2739 int dstart = interval_.nextNotIgnored(actual._dataStart);
2740 while (interval_.isOpeningPar(dstart) == 1) {
2741 interval_.addIntervall(dstart, dstart+1);
2742 int dend = interval_.findclosing(dstart+1, output_end);
2743 interval_.addIntervall(dend, dend+1);
2744 dstart = interval_.nextNotIgnored(dstart+1);
2746 if (dstart < output_end)
2747 interval_.output(os, output_end);
2748 interval_.addIntervall(actual._tokenstart, end);
2752 string splitOnKnownMacros(string par, bool isPatternString)
2755 LatexInfo li(par, isPatternString);
2756 // LYXERR(Debug::INFO, "Berfore split: " << par);
2757 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2759 DummyKey._tokensize = 0;
2760 DummyKey._dataStart = 0;
2761 DummyKey._dataEnd = par.length();
2762 DummyKey.disabled = true;
2763 int firstkeyIdx = li.getFirstKey();
2765 if (firstkeyIdx >= 0) {
2766 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2767 DummyKey._tokenstart = firstKey._tokenstart;
2769 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2770 // Use dummy firstKey
2771 firstKey = DummyKey;
2772 (void) li.setNextKey(firstkeyIdx);
2775 if (par.substr(firstKey._dataStart, 2) == "% ")
2776 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2778 nextkeyIdx = li.process(os, firstKey);
2779 while (nextkeyIdx >= 0) {
2780 // Check for a possible gap between the last
2781 // entry and this one
2782 int datastart = li.nextNotIgnored(firstKey._dataStart);
2783 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2784 if ((nextKey._tokenstart > datastart)) {
2786 firstKey._dataStart = datastart;
2787 firstKey._dataEnd = par.length();
2788 (void) li.setNextKey(nextkeyIdx);
2789 // Fake the last opened parenthesis
2790 li.setForDefaultLang(firstKey);
2791 nextkeyIdx = li.process(os, firstKey);
2794 if (nextKey.keytype != KeyInfo::isMain) {
2795 firstKey._dataStart = datastart;
2796 firstKey._dataEnd = nextKey._dataEnd+1;
2797 (void) li.setNextKey(nextkeyIdx);
2798 li.setForDefaultLang(firstKey);
2799 nextkeyIdx = li.process(os, firstKey);
2802 nextkeyIdx = li.process(os, nextKey);
2806 // Handle the remaining
2807 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2808 firstKey._dataEnd = par.length();
2810 if ((firstKey._dataStart < firstKey._dataEnd) &&
2811 (par[firstKey._dataStart] != '}')) {
2812 li.setForDefaultLang(firstKey);
2813 (void) li.process(os, firstKey);
2817 // return string definitelly impossible to match
2818 s = "\\foreignlanguage{ignore}{ }";
2822 s = par; /* no known macros found */
2823 // LYXERR(Debug::INFO, "After split: " << s);
2828 * Try to unify the language specs in the latexified text.
2829 * Resulting modified string is set to "", if
2830 * the searched tex does not contain all the features in the search pattern
2832 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2834 static Features regex_f;
2835 static int missed = 0;
2836 static bool regex_with_format = false;
2838 int parlen = par.length();
2840 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2843 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2844 // Happens to be there in case of description or labeling environment
2849 // Split the latex input into pieces which
2850 // can be digested by our search engine
2851 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2852 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2853 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2856 result = par.substr(0, parlen);
2857 if (isPatternString) {
2860 regex_f = identifyFeatures(result);
2861 string features = "";
2862 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2863 string a = it->first;
2864 regex_with_format = true;
2865 features += " " + a;
2866 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2868 LYXERR(Debug::FIND, "Identified Features" << features);
2871 } else if (regex_with_format) {
2872 Features info = identifyFeatures(result);
2873 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2874 string a = it->first;
2875 bool b = it->second;
2876 if (b && ! info[a]) {
2878 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2884 // LYXERR(Debug::INFO, "No regex formats");
2890 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2891 static int identifyClosing(string & t)
2893 int open_braces = 0;
2895 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2896 if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
2898 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
2900 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
2902 if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
2911 static int num_replaced = 0;
2912 static bool previous_single_replace = true;
2914 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2915 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2917 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2918 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2919 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2920 if (opt.replace_all && previous_single_replace) {
2921 previous_single_replace = false;
2924 else if (!opt.replace_all) {
2925 num_replaced = 0; // count number of replaced strings
2926 previous_single_replace = true;
2928 // When using regexp, braces are hacked already by escape_for_regex()
2929 par_as_string = normalize(ds, !use_regexp);
2931 close_wildcards = 0;
2933 size_t lead_size = 0;
2934 // correct the language settings
2935 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2936 if (opt.ignoreformat) {
2938 // if par_as_string_nolead were emty,
2939 // the following call to findAux will always *find* the string
2940 // in the checked data, and thus always using the slow
2941 // examining of the current text part.
2942 par_as_string_nolead = par_as_string;
2945 lead_size = identifyLeading(par_as_string);
2946 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2947 lead_as_string = par_as_string.substr(0, lead_size);
2948 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2952 open_braces = identifyClosing(par_as_string);
2953 identifyClosing(par_as_string_nolead);
2954 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2955 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2957 string lead_as_regexp;
2958 if (lead_size > 0) {
2959 // @todo No need to search for \regexp{} insets in leading material
2960 static std::regex specialChars { R"([-[\]{}()*+?.,\^$|#\s\\])" };
2961 lead_as_regexp = std::regex_replace(par_as_string.substr(0, lead_size), specialChars, R"(\$&)" );
2962 // lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2963 par_as_string = par_as_string_nolead;
2964 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2965 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2967 LYXERR(Debug::FIND, "par_as_string before escape_for_regex() is '" << par_as_string << "'");
2968 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2969 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2970 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2972 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2973 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2974 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2975 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2976 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2977 || regex_replace(par_as_string, par_as_string,
2978 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2979 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2980 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2984 if (!opt.ignoreformat) {
2985 // Remove extra '\}' at end if not part of \{\.\}
2986 size_t lng = par_as_string.size();
2988 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
2990 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
2999 if (lng < par_as_string.size())
3000 par_as_string = par_as_string.substr(0,lng);
3003 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
3004 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
3005 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
3006 // replace '[^...]' with '[^...\}\{\\]'
3007 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
3008 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
3009 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
3011 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
3014 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
3015 LYXERR(Debug::FIND, "Open braces: " << open_braces);
3016 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
3017 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
3019 // If entered regexp must match at begin of searched string buffer
3020 // Kornel: Added parentheses to use $1 for size of the leading string
3024 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
3025 // Unfortunately is '\1', '\2', etc not working for strings with extra format
3026 // so the convert has no effect in that case
3027 for (int i = 7; i > 0; --i) {
3028 string orig = "\\\\" + std::to_string(i);
3029 string dest = "\\" + std::to_string(i+2);
3030 while (regex_replace(par_as_string, par_as_string, orig, dest));
3032 regexp_str = "(" + lead_as_regexp + ")()" + par_as_string;
3033 regexp2_str = "(" + lead_as_regexp + ")(.*?)" + par_as_string;
3035 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
3036 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
3038 // Handle \w properly
3039 QRegularExpression::PatternOptions popts = QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption;
3040 if (! opt.casesensitive) {
3041 popts |= QRegularExpression::CaseInsensitiveOption;
3043 regexp = QRegularExpression(QString::fromStdString(regexp_str), popts);
3044 regexp2 = QRegularExpression(QString::fromStdString(regexp2_str), popts);
3046 if (regexp.isValid() && regexp2.isValid()) {
3047 regexIsValid = true;
3048 // Check '{', '}' pairs inside the regex
3051 for (unsigned i = 0; i < par_as_string.size(); i+= skip) {
3052 char c = par_as_string[i];
3059 else if (c == '}') {
3066 if (balanced != 0) {
3067 regexIsValid = false;
3068 regexError = "Unbalanced curly brackets in regexp \"" + regexp_str + "\"";
3072 regexIsValid = false;
3073 if (!regexp.isValid())
3074 regexError += "Invalid regexp \"" + regexp_str + "\", error = " + regexp.errorString().toStdString();
3075 if (!regexp2.isValid())
3076 regexError += "Invalid regexp2 \"" + regexp2_str + "\", error = " + regexp2.errorString().toStdString();
3079 if (opt.casesensitive) {
3080 regexp = regex(regexp_str);
3081 regexp2 = regex(regexp2_str);
3084 regexp = regex(regexp_str, std::regex_constants::icase);
3085 regexp2 = regex(regexp2_str, std::regex_constants::icase);
3092 // Count number of characters in string
3096 // \\[a-zA-Z]+ ==> 1
3098 static int computeSize(QStringRef s, int len)
3099 #define isLyxAlpha(arg) arg.isLetter()
3101 static int computeSize(string s, int len)
3102 #define isLyxAlpha(arg) isalpha(arg)
3109 for (int i = 0; i < len; i += skip, count++) {
3110 if (s.at(i) == '\\') {
3112 if (i + 1 < len && isLyxAlpha(s.at(i+1))) {
3113 for (int j = 2; i+j < len; j++) {
3114 if (! isLyxAlpha(s.at(i+j))) {
3115 if (s.at(i+j) == ' ')
3117 else if (s.at(i+j) == '{') {
3118 if (i+j+1 < len && s.at(i+j+1) == '}')
3120 else if (i + j + 1 >= len)
3129 else if (s.at(i) == '{') {
3130 if (i + 1 < len && s.at(i+1) == '}')
3135 else if (s.at(i) == '-') {
3136 if (i+1 < len && s.at(i+1) == '-') {
3137 if (i + 2 < len && s.at(i+2) == '-')
3153 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
3158 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
3161 docstring docstr = stringifyFromForSearch(opt, cur, len);
3163 if (use_regexp || opt.casesensitive)
3164 str = normalize(docstr, true);
3166 str = normalize(lowercase(docstr), true);
3167 if (!opt.ignoreformat) {
3168 str = correctlanguagesetting(str, false, !opt.ignoreformat);
3171 mres.match_len = -1;
3174 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
3175 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
3178 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
3180 QString qstr = QString::fromStdString(str);
3181 QRegularExpression const *p_regexp;
3182 QRegularExpression::MatchType flags = QRegularExpression::NormalMatch;
3186 p_regexp = ®exp2;
3188 QRegularExpressionMatch match = p_regexp->match(qstr, 0, flags);
3189 if (!match.hasMatch())
3192 regex const *p_regexp;
3193 regex_constants::match_flag_type flags;
3195 flags = regex_constants::match_continuous;
3198 flags = regex_constants::match_default;
3199 p_regexp = ®exp2;
3201 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
3202 if (re_it == sregex_iterator())
3204 match_results<string::const_iterator> const & m = *re_it;
3206 // Whole found string, including the leading
3207 // std: m[0].second - m[0].first
3208 // Qt: match.capturedEnd(0) - match.capturedStart(0)
3210 // Size of the leading string
3211 // std: m[1].second - m[1].first
3212 // Qt: match.capturedEnd(1) - match.capturedStart(1)
3213 int leadingsize = 0;
3215 if (match.lastCapturedIndex() > 0) {
3216 leadingsize = match.capturedEnd(1) - match.capturedStart(1);
3221 leadingsize = m[1].second - m[1].first;
3225 mres.match_prefix = match.capturedEnd(2) - match.capturedStart(2);
3226 mres.match_len = match.capturedEnd(0) - match.capturedEnd(2);
3227 // because of different number of closing at end of string
3228 // we have to 'unify' the length of the post-match.
3229 // Done by ignoring closing parenthesis and linefeeds at string end
3230 int matchend = match.capturedEnd(0);
3231 while (mres.match_len > 0) {
3232 QChar c = qstr.at(matchend - 1);
3233 if ((c == '\n') || (c == '}') || (c == '{')) {
3240 size_t strsize = qstr.size();
3241 while (strsize > (size_t) match.capturedEnd(0)) {
3242 QChar c = qstr.at(strsize-1);
3243 if ((c == '\n') || (c == '}')) {
3249 // LYXERR0(qstr.toStdString());
3250 mres.match2end = strsize - matchend;
3251 mres.pos = match.capturedStart(2);
3253 mres.match_prefix = m[2].second - m[2].first;
3254 mres.match_len = m[0].second - m[2].second;
3255 // ignore closing parenthesis and linefeeds at string end
3256 size_t strend = m[0].second - m[0].first;
3257 int matchend = strend;
3258 while (mres.match_len > 0) {
3259 char c = str.at(matchend - 1);
3260 if ((c == '\n') || (c == '}') || (c == '{')) {
3267 size_t strsize = str.size();
3268 while (strsize > strend) {
3269 if ((str.at(strsize-1) == '}') || (str.at(strsize-1) == '\n')) {
3276 mres.match2end = strsize - matchend;
3277 mres.pos = m[2].first - m[0].first;;
3279 if (mres.match2end < 0)
3281 mres.leadsize = leadingsize;
3283 if (mres.match_len > 0) {
3284 string a0 = match.captured(0).mid(mres.pos + mres.match_prefix, mres.match_len).toStdString();
3285 mres.result.push_back(a0);
3286 for (int i = 3; i <= match.lastCapturedIndex(); i++) {
3287 mres.result.push_back(match.captured(i).toStdString());
3291 if (mres.match_len > 0) {
3292 string a0 = m[0].str().substr(mres.pos + mres.match_prefix, mres.match_len);
3293 mres.result.push_back(a0);
3294 for (size_t i = 3; i < m.size(); i++) {
3295 mres.result.push_back(m[i]);
3302 // else !use_regexp: but all code paths above return
3303 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
3304 << par_as_string << "', str='" << str << "'");
3305 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
3306 << lead_as_string << "', par_as_string_nolead='"
3307 << par_as_string_nolead << "'");
3310 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3311 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3312 if (str.substr(0, par_as_string.size()) == par_as_string) {
3313 mres.match_len = par_as_string.size();
3314 mres.match2end = str.size();
3319 // Start the search _after_ the leading part
3320 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3321 if (pos != string::npos) {
3322 mres.match_len = par_as_string.size();
3323 mres.match2end = str.size() - pos;
3332 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3334 MatchResult mres = findAux(cur, len, at_begin);
3335 int res = mres.match_len;
3337 "res=" << res << ", at_begin=" << at_begin
3338 << ", matchword=" << opt.matchword
3339 << ", inTexted=" << cur.inTexted());
3340 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
3342 if ((len > 0) && (res < len)) {
3346 Paragraph const & par = cur.paragraph();
3347 bool ws_left = (cur.pos() > 0)
3348 ? par.isWordSeparator(cur.pos() - 1)
3354 ws_right = (cur.pos() + len < par.size())
3355 ? par.isWordSeparator(cur.pos() + len)
3359 "cur.pos()=" << cur.pos() << ", res=" << res
3360 << ", separ: " << ws_left << ", " << ws_right
3363 if (ws_left && ws_right) {
3364 // Check for word separators inside the found 'word'
3365 for (int i = 0; i < len; i++) {
3366 if (par.isWordSeparator(cur.pos() + i)) {
3377 static bool simple_replace(string &t, string from, string to)
3379 regex repl("(\\\\)*(" + from + ")");
3383 for (sregex_iterator it(t.begin(), t.end(), repl), end; it != end; ++it) {
3385 if ((sub.position(2) - sub.position(0)) % 2 == 1)
3387 if (lastpos < (size_t) sub.position(2))
3388 s += t.substr(lastpos, sub.position(2) - lastpos);
3390 lastpos = sub.position(2) + sub.length(2);
3394 else if (lastpos < t.length())
3395 s += t.substr(lastpos, t.length() - lastpos);
3400 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
3403 t = lyx::to_utf8(s);
3404 // Remove \n at begin
3405 while (!t.empty() && t[0] == '\n')
3408 while (!t.empty() && t[t.size() - 1] == '\n')
3409 t = t.substr(0, t.size() - 1);
3411 // Handle all other '\n'
3412 while ((pos = t.find("\n")) != string::npos) {
3413 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3415 if (isAlnumASCII(t[pos+1])) {
3416 t.replace(pos-2, 3, " ");
3419 t.replace(pos-2, 3, "");
3422 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3423 // '\n' adjacent to non-alpha-numerics, discard
3424 t.replace(pos, 1, "");
3427 // Replace all other \n with spaces
3428 t.replace(pos, 1, " ");
3431 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3432 // Kornel: Added textsl, textsf, textit, texttt and noun
3433 // + allow to seach for colored text too
3434 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3435 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3436 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3437 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3438 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3439 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3440 // FIXME - check what preceeds the brace
3442 if (opt.ignoreformat)
3443 while (regex_replace(t, t, "\\{", "_x_<")
3444 || regex_replace(t, t, "\\}", "_x_>"))
3445 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3447 simple_replace(t, "\\\\\\{", "_x_<");
3448 simple_replace(t, "\\\\\\}", "_x_>");
3449 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3457 docstring stringifyFromCursor(DocIterator const & cur, int len)
3459 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3460 if (cur.inTexted()) {
3461 Paragraph const & par = cur.paragraph();
3462 // TODO what about searching beyond/across paragraph breaks ?
3463 // TODO Try adding a AS_STR_INSERTS as last arg
3464 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3465 int(par.size()) : cur.pos() + len;
3466 // OutputParams runparams(&cur.buffer()->params().encoding());
3467 OutputParams runparams(encodings.fromLyXName("utf8"));
3468 runparams.nice = true;
3469 runparams.flavor = Flavor::XeTeX;
3470 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3471 // No side effect of file copying and image conversion
3472 runparams.dryrun = true;
3473 runparams.for_search = true;
3474 LYXERR(Debug::FIND, "Stringifying with cur: "
3475 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3476 return par.asString(cur.pos(), end,
3477 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3479 } else if (cur.inMathed()) {
3480 CursorSlice cs = cur.top();
3481 MathData md = cs.cell();
3482 MathData::const_iterator it_end =
3483 (( len == -1 || cs.pos() + len > int(md.size()))
3485 : md.begin() + cs.pos() + len );
3487 for (MathData::const_iterator it = md.begin() + cs.pos();
3490 docstring s = asString(md2);
3491 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3494 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3499 /** Computes the LaTeX export of buf starting from cur and ending len positions
3500 * after cur, if len is positive, or at the paragraph or innermost inset end
3503 docstring latexifyFromCursor(DocIterator const & cur, int len)
3505 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3506 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3507 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3508 Buffer const & buf = *cur.buffer();
3510 odocstringstream ods;
3512 //OutputParams runparams(&buf.params().encoding());
3513 OutputParams runparams(encodings.fromLyXName("utf8"));
3514 runparams.nice = false;
3515 runparams.flavor = Flavor::XeTeX;
3516 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3517 // No side effect of file copying and image conversion
3518 runparams.dryrun = true;
3519 runparams.for_search = true;
3521 if (cur.inTexted()) {
3522 // @TODO what about searching beyond/across paragraph breaks ?
3523 pos_type endpos = cur.paragraph().size();
3524 if (len != -1 && endpos > cur.pos() + len)
3525 endpos = cur.pos() + len;
3526 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3527 string(), cur.pos(), endpos);
3528 string s = lyx::to_utf8(ods.str());
3529 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3530 return(lyx::from_utf8(s));
3531 } else if (cur.inMathed()) {
3532 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3533 for (int s = cur.depth() - 1; s >= 0; --s) {
3534 CursorSlice const & cs = cur[s];
3535 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3536 TeXMathStream ws(os);
3537 cs.asInsetMath()->asHullInset()->header_write(ws);
3542 CursorSlice const & cs = cur.top();
3543 MathData md = cs.cell();
3544 MathData::const_iterator it_end =
3545 ((len == -1 || cs.pos() + len > int(md.size()))
3547 : md.begin() + cs.pos() + len);
3549 for (MathData::const_iterator it = md.begin() + cs.pos();
3553 ods << asString(md2);
3554 // Retrieve the math environment type, and add '$' or '$]'
3555 // or others (\end{equation}) accordingly
3556 for (int s = cur.depth() - 1; s >= 0; --s) {
3557 CursorSlice const & cs2 = cur[s];
3558 InsetMath * inset = cs2.asInsetMath();
3559 if (inset && inset->asHullInset()) {
3560 TeXMathStream ws(os);
3561 inset->asHullInset()->footer_write(ws);
3565 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3567 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3572 #if defined(ResultsDebug)
3574 static void displayMResult(MatchResult &mres, int increment)
3576 LYXERR0( "pos: " << mres.pos << " increment " << increment);
3577 LYXERR0( "leadsize: " << mres.leadsize);
3578 LYXERR0( "match_len: " << mres.match_len);
3579 LYXERR0( "match_prefix: " << mres.match_prefix);
3580 LYXERR0( "match2end: " << mres.match2end);
3581 for (size_t i = 0; i < mres.result.size(); i++)
3582 LYXERR0( "Match " << i << " = \"" << mres.result[i] << "\"");
3584 #define displayMres(s,i) displayMResult(s,i);
3586 #define displayMres(s,i)
3589 static bool findAdvForwardInnermost(DocIterator & cur)
3592 DocIterator old_cur(cur.buffer());
3593 int forwardCount = 0;
3601 if (cur.depth() > d) {
3605 if (cur.depth() == d)
3609 if (forwardCount > 0) {
3610 LYXERR(Debug::FIND, "Forwarded " << forwardCount << " step(s) (searching for innermost match)");
3617 /** Finalize an advanced find operation, advancing the cursor to the innermost
3618 ** position that matches, plus computing the length of the matching text to
3621 MatchResult &findAdvFinalize(DocIterator & cur, MatchStringAdv const & match, MatchResult const & expected = MatchResult(-1))
3623 // Search the foremost position that matches (avoids find of entire math
3624 // inset when match at start of it)
3625 DocIterator old_cur(cur.buffer());
3627 static MatchResult fail = MatchResult();
3628 static MatchResult max_match;
3629 // If (prefix_len > 0) means that forwarding 1 position will remove the complete entry
3630 // Happens with e.g. hyperlinks
3631 // either one sees "http://www.bla.bla" or nothing
3632 // so the search for "www" gives prefix_len = 7 (== sizeof("http://")
3633 // and although we search for only 3 chars, we find the whole hyperlink inset
3634 bool at_begin = (expected.match_prefix == 0);
3635 if (findAdvForwardInnermost(cur)) {
3636 mres = match(cur, -1, at_begin);
3637 displayMres(mres, 0);
3638 if (expected.match_len > 0) {
3639 if (mres.match_len < expected.match_len)
3643 if (mres.match_len <= 0)
3646 max_match = mres.match_len;
3648 else if (expected.match_len < 0) {
3649 mres = match(cur); /* match valid only if not searching whole words */
3650 displayMres(mres, 0);
3654 max_match = expected;
3656 if (max_match.match_len <= 0) return fail;
3657 LYXERR(Debug::FIND, "Ok");
3659 // Compute the match length
3661 if (cur.pos() + len > cur.lastpos())
3663 // regexp should use \w+, \S+, or \b(some string)\b
3664 // to search for whole words
3665 if (match.opt.matchword && !match.use_regexp) {
3666 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3667 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3669 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3671 // Length of matched text (different from len param)
3672 static MatchResult old_match = match(cur, len, at_begin);
3673 if (old_match.match_len < 0)
3675 MatchResult new_match;
3676 // Greedy behaviour while matching regexps
3677 while ((new_match = match(cur, len + 1, at_begin)).match_len > old_match.match_len) {
3679 old_match = new_match;
3680 LYXERR(Debug::FIND, "verifying match with len = " << len);
3686 int maxl = cur.lastpos() - cur.pos();
3687 // Greedy behaviour while matching regexps
3688 while (maxl > minl) {
3690 mres2 = match(cur, len, at_begin);
3691 displayMres(mres2, len);
3692 int actual_match = mres2.match_len;
3693 if (actual_match >= max_match.match_len) {
3694 // actual_match > max_match _can_ happen,
3695 // if the search area splits
3696 // some following word so that the regex
3697 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3699 // This means, the len value is too big
3701 if (maxl - minl < 4)
3702 len = (int)((maxl + minl)/2);
3704 len = (int)(minl + (maxl - minl + 3)/4);
3707 // (actual_match < max_match)
3709 len = (int)((maxl + minl)/2);
3713 // Search for real start of matched characters
3715 MatchResult actual_match;
3718 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3719 if (cur.depth() < old_cur.depth()) {
3721 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3724 if (cur.pos() != old_cur.pos()) {
3725 // OK, forwarded 1 pos in actual inset
3726 actual_match = match(cur, len-1, at_begin);
3727 if (actual_match.match_len == max_match.match_len) {
3728 // Ha, got it! The shorter selection has the same match length
3733 // OK, the shorter selection matches less chars, revert to previous value
3739 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3740 actual_match = match(cur, len, at_begin);
3741 if (actual_match.match_len == max_match.match_len) {
3743 max_match = actual_match;
3755 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
3759 while (!theApp()->longOperationCancelled() && cur) {
3760 (void) findAdvForwardInnermost(cur);
3761 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3762 MatchResult mres = match(cur, -1, false);
3763 displayMres(mres,-1)
3764 int match_len = mres.match_len;
3765 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3766 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3769 if (match_len > 0) {
3770 // Try to find the begin of searched string
3772 int firstInvalid = 100000;
3773 if (mres.match_prefix + mres.pos - mres.leadsize > 1)
3774 increment = (mres.match_prefix + mres.pos - mres.leadsize + 1)*3/4;
3777 LYXERR(Debug::FIND, "Set increment to " << increment);
3778 while (increment > 0) {
3779 DocIterator old_cur = cur;
3780 for (int i = 0; i < increment && cur; cur.forwardPos(), i++) {
3782 if (! cur || (cur.pit() > old_cur.pit())) {
3783 // Are we outside of the paragraph?
3784 // This can happen if moving past some UTF8-encoded chars
3789 MatchResult mres2 = match(cur, -1, false);
3790 displayMres(mres2,increment)
3791 switch (interpretMatch(mres, mres2)) {
3792 case MatchResult::newIsTooFar:
3793 // behind the expected match
3794 firstInvalid = increment;
3798 case MatchResult::newIsBetter:
3799 // not reached ye, but cur.pos()+increment is bettert
3801 firstInvalid -= increment;
3802 if (increment > firstInvalid*3/4)
3803 increment = firstInvalid*3/4;
3804 if ((mres2.pos == mres2.leadsize) && (increment >= mres2.match_prefix)) {
3805 if (increment >= mres2.match_prefix)
3806 increment = (mres2.match_prefix+1)*3/4;
3811 // Handle not like MatchResult::newIsTooFar
3812 // LYXERR0( "Something is wrong: Increment = " << increment << " match_prefix = " << mres.match_prefix);
3814 increment = increment*3/4;
3820 // LYXERR0("Leaving first loop");
3822 LYXERR(Debug::FIND, "Finalizing 1");
3823 MatchResult found_match = findAdvFinalize(cur, match, mres);
3824 if (found_match.match_len > 0) {
3825 match.FillResults(found_match);
3826 return found_match.match_len;
3829 // try next possible match
3834 // The following code is newer reached
3835 // but parts of it may be needed in future
3836 int match_len_zero_count = 0;
3838 for (int i = 0; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
3840 mres3 = match(cur, -1, false);
3841 displayMres(mres3, 1)
3842 int remaining_len = mres3.match_len;
3843 if (remaining_len <= 0) {
3844 // Apparently the searched string is not in the remaining part
3851 LYXERR(Debug::FIND, "Advancing cur: " << cur);
3852 mres3 = match(cur, 1);
3853 displayMres(mres3, 1)
3854 int match_len3 = mres3.match_len;
3858 displayMres(mres3, 1)
3859 int match_len2 = mres3.match_len;
3860 LYXERR(Debug::FIND, "match_len2: " << match_len2);
3861 if (match_len2 > 0) {
3862 // Sometimes in finalize we understand it wasn't a match
3863 // and we need to continue the outest loop
3864 LYXERR(Debug::FIND, "Finalizing 2");
3865 MatchResult mres4 = findAdvFinalize(cur, match, mres.match_len);
3866 if (mres4.match_len > 0) {
3867 match.FillResults(mres4);
3868 return mres4.match_len;
3872 match_len_zero_count = 0;
3873 else if (match_len2 == 0)
3874 match_len_zero_count++;
3875 if (match_len2 < 0) {
3876 if (++match_len_zero_count > 3) {
3877 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
3885 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
3886 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
3889 // This should exit nested insets, if any, or otherwise undefine the currsor.
3890 cur.pos() = cur.lastpos();
3891 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3899 /// Find the most backward consecutive match within same paragraph while searching backwards.
3900 MatchResult &findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3902 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3903 DocIterator tmp_cur = cur;
3904 static MatchResult mr = findAdvFinalize(tmp_cur, match, MatchResult(-1));
3905 Inset & inset = cur.inset();
3906 for (; cur != cur_begin; cur.backwardPos()) {
3907 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3908 DocIterator new_cur = cur;
3909 new_cur.backwardPos();
3910 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3912 MatchResult new_mr = findAdvFinalize(new_cur, match, MatchResult(-1));
3913 if (new_mr.match_len == mr.match_len)
3917 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3923 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3927 // Backup of original position
3928 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3929 if (cur == cur_begin)
3932 DocIterator cur_orig(cur);
3933 bool pit_changed = false;
3936 bool found_match = (match(cur, -1, false).match_len > 0);
3940 cur.pos() = cur.lastpos();
3942 cur.pos() = cur_orig.pos();
3943 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3944 DocIterator cur_prev_iter;
3946 found_match = (match(cur).match_len > 0);
3947 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3948 << found_match << ", cur: " << cur);
3950 MatchResult found_mr = findMostBackwards(cur, match);
3951 match.FillResults(found_mr);
3952 return found_mr.match_len;
3955 // Stop if begin of document reached
3956 if (cur == cur_begin)
3958 cur_prev_iter = cur;
3962 if (cur == cur_begin)
3969 } while (!theApp()->longOperationCancelled());
3977 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3978 DocIterator const & cur, int len)
3980 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3982 if (!opt.ignoreformat)
3983 return latexifyFromCursor(cur, len);
3985 return stringifyFromCursor(cur, len);
3989 FindAndReplaceOptions::FindAndReplaceOptions(
3990 docstring const & _find_buf_name, bool _casesensitive,
3991 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3992 docstring const & _repl_buf_name, bool _keep_case,
3993 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3994 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3995 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3996 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
4004 /** Check if 'len' letters following cursor are all non-lowercase */
4005 static bool allNonLowercase(Cursor const & cur, int len)
4007 pos_type beg_pos = cur.selectionBegin().pos();
4008 pos_type end_pos = cur.selectionBegin().pos() + len;
4009 if (len > cur.lastpos() + 1 - beg_pos) {
4010 LYXERR(Debug::FIND, "This should not happen, more debug needed");
4011 len = cur.lastpos() + 1 - beg_pos;
4012 end_pos = beg_pos + len;
4014 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
4015 if (isLowerCase(cur.paragraph().getChar(pos)))
4021 /** Check if first letter is upper case and second one is lower case */
4022 static bool firstUppercase(Cursor const & cur)
4025 pos_type pos = cur.selectionBegin().pos();
4026 if (pos >= cur.lastpos() - 1) {
4027 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
4030 ch1 = cur.paragraph().getChar(pos);
4031 ch2 = cur.paragraph().getChar(pos + 1);
4032 bool result = isUpperCase(ch1) && isLowerCase(ch2);
4033 LYXERR(Debug::FIND, "firstUppercase(): "
4034 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
4035 << ch2 << "(" << char(ch2) << ")"
4036 << ", result=" << result << ", cur=" << cur);
4041 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
4043 ** \fixme What to do with possible further paragraphs in replace buffer ?
4045 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
4047 ParagraphList::iterator pit = buffer.paragraphs().begin();
4048 LASSERT(!pit->empty(), /**/);
4049 pos_type right = pos_type(1);
4050 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
4051 right = pit->size();
4052 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
4058 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
4060 Cursor & cur = bv->cursor();
4061 if (opt.repl_buf_name.empty()
4062 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
4063 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4066 DocIterator sel_beg = cur.selectionBegin();
4067 DocIterator sel_end = cur.selectionEnd();
4068 if (&sel_beg.inset() != &sel_end.inset()
4069 || sel_beg.pit() != sel_end.pit()
4070 || sel_beg.idx() != sel_end.idx())
4072 int sel_len = sel_end.pos() - sel_beg.pos();
4073 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
4074 << ", sel_len: " << sel_len << endl);
4077 LASSERT(sel_len > 0, return 0);
4079 if (!matchAdv(sel_beg, sel_len).match_len)
4082 // Build a copy of the replace buffer, adapted to the KeepCase option
4083 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
4085 repl_buffer_orig.write(oss);
4086 string lyx = oss.str();
4087 Buffer repl_buffer("", false);
4088 repl_buffer.setUnnamed(true);
4089 LASSERT(repl_buffer.readString(lyx), return 0);
4090 if (opt.keep_case && sel_len >= 2) {
4091 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
4092 if (cur.inTexted()) {
4093 if (firstUppercase(cur))
4094 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
4095 else if (allNonLowercase(cur, sel_len))
4096 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
4099 cap::cutSelection(cur, false);
4100 if (cur.inTexted()) {
4101 repl_buffer.changeLanguage(
4102 repl_buffer.language(),
4103 cur.getFont().language());
4104 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
4105 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
4106 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
4107 repl_buffer.params().documentClassPtr(),
4108 bv->buffer().errorList("Paste"));
4109 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
4110 sel_len = repl_buffer.paragraphs().begin()->size();
4111 } else if (cur.inMathed()) {
4112 odocstringstream ods;
4114 // OutputParams runparams(&repl_buffer.params().encoding());
4115 OutputParams runparams(encodings.fromLyXName("utf8"));
4116 runparams.nice = false;
4117 runparams.flavor = Flavor::XeTeX;
4118 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
4119 runparams.dryrun = true;
4120 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
4121 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
4122 docstring repl_latex = ods.str();
4123 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
4125 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
4126 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
4127 repl_latex = from_utf8(s);
4128 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
4129 MathData ar(cur.buffer());
4130 asArray(repl_latex, ar, Parse::NORMAL);
4132 sel_len = ar.size();
4133 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4135 if (cur.pos() >= sel_len)
4136 cur.pos() -= sel_len;
4139 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
4140 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
4141 bv->processUpdateFlags(Update::Force);
4146 /// Perform a FindAdv operation.
4147 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
4152 // e.g., when invoking word-findadv from mini-buffer wither with
4153 // wrong options syntax or before ever opening advanced F&R pane
4154 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
4158 MatchStringAdv matchAdv(bv->buffer(), opt);
4160 if (!matchAdv.regexIsValid) {
4161 bv->message(lyx::from_utf8(matchAdv.regexError));
4165 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
4167 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
4168 num_replaced += findAdvReplace(bv, opt, matchAdv);
4171 match_len = findForwardAdv(cur, matchAdv);
4173 match_len = findBackwardsAdv(cur, matchAdv);
4174 } catch (exception & ex) {
4175 bv->message(from_utf8(ex.what()));
4179 if (match_len == 0) {
4180 if (num_replaced > 0) {
4181 switch (num_replaced)
4184 bv->message(_("One match has been replaced."));
4187 bv->message(_("Two matches have been replaced."));
4190 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
4196 bv->message(_("Match not found."));
4201 if (num_replaced > 0)
4202 bv->message(_("Match has been replaced."));
4204 bv->message(_("Match found."));
4206 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
4207 bv->putSelectionAt(cur, match_len, !opt.forward);
4213 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
4215 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
4216 << opt.casesensitive << ' '
4217 << opt.matchword << ' '
4218 << opt.forward << ' '
4219 << opt.expandmacros << ' '
4220 << opt.ignoreformat << ' '
4221 << opt.replace_all << ' '
4222 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
4223 << opt.keep_case << ' '
4224 << int(opt.scope) << ' '
4227 LYXERR(Debug::FIND, "built: " << os.str());
4233 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
4235 LYXERR(Debug::FIND, "parsing");
4239 while (line != "EOSS") {
4243 if (is.eof()) // Tolerate malformed request
4247 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
4248 opt.find_buf_name = from_utf8(s);
4249 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
4250 is.get(); // Waste space before replace string
4253 while (line != "EOSS") {
4257 if (is.eof()) // Tolerate malformed request
4261 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
4262 opt.repl_buf_name = from_utf8(s);
4263 is >> opt.keep_case;
4266 opt.scope = FindAndReplaceOptions::SearchScope(i);
4268 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
4270 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
4271 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
4272 << opt.scope << ' ' << opt.restr);