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
12 * Full author contact details are available in file CREDITS.
20 #include "buffer_funcs.h"
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"
32 #include "ParIterator.h"
36 #include "frontends/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
46 #include "support/convert.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/FileName.h"
50 #include "support/gettext.h"
51 #include "support/lassert.h"
52 #include "support/lstrings.h"
54 #include "support/regex.h"
58 using namespace lyx::support;
64 bool parse_bool(docstring & howto)
69 howto = split(howto, var, ' ');
74 class MatchString : public binary_function<Paragraph, pos_type, int>
77 MatchString(docstring const & str, bool cs, bool mw)
78 : str(str), case_sens(cs), whole_words(mw)
81 // returns true if the specified string is at the specified position
82 // del specifies whether deleted strings in ct mode will be considered
83 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
85 return par.find(str, case_sens, whole_words, pos, del);
93 // match whole words only
98 int findForward(DocIterator & cur, MatchString const & match,
101 for (; cur; cur.forwardChar())
102 if (cur.inTexted()) {
103 int len = match(cur.paragraph(), cur.pos(), find_del);
111 int findBackwards(DocIterator & cur, MatchString const & match,
112 bool find_del = true)
116 if (cur.inTexted()) {
117 int len = match(cur.paragraph(), cur.pos(), find_del);
126 bool searchAllowed(docstring const & str)
129 frontend::Alert::error(_("Search error"), _("Search string is empty"));
136 bool findOne(BufferView * bv, docstring const & searchstr,
137 bool case_sens, bool whole, bool forward,
138 bool find_del = true, bool check_wrap = false)
140 if (!searchAllowed(searchstr))
143 DocIterator cur = forward
144 ? bv->cursor().selectionEnd()
145 : bv->cursor().selectionBegin();
147 MatchString const match(searchstr, case_sens, whole);
149 int match_len = forward
150 ? findForward(cur, match, find_del)
151 : findBackwards(cur, match, find_del);
154 bv->putSelectionAt(cur, match_len, !forward);
155 else if (check_wrap) {
156 DocIterator cur_orig(bv->cursor());
159 q = _("End of file reached while searching forward.\n"
160 "Continue searching from the beginning?");
162 q = _("Beginning of file reached while searching backward.\n"
163 "Continue searching from the end?");
164 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
165 q, 0, 1, _("&Yes"), _("&No"));
166 if (wrap_answer == 0) {
168 bv->cursor().clear();
169 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
171 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
172 bv->cursor().backwardPos();
174 bv->clearSelection();
175 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
178 bv->cursor().setCursor(cur_orig);
182 return match_len > 0;
186 int replaceAll(BufferView * bv,
187 docstring const & searchstr, docstring const & replacestr,
188 bool case_sens, bool whole)
190 Buffer & buf = bv->buffer();
192 if (!searchAllowed(searchstr) || buf.isReadonly())
195 DocIterator cur_orig(bv->cursor());
197 MatchString const match(searchstr, case_sens, whole);
200 int const rsize = replacestr.size();
201 int const ssize = searchstr.size();
204 cur.setCursor(doc_iterator_begin(&buf));
205 int match_len = findForward(cur, match, false);
206 while (match_len > 0) {
207 // Backup current cursor position and font.
208 pos_type const pos = cur.pos();
209 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
211 int striked = ssize -
212 cur.paragraph().eraseChars(pos, pos + match_len,
213 buf.params().track_changes);
214 cur.paragraph().insert(pos, replacestr, font,
215 Change(buf.params().track_changes
217 : Change::UNCHANGED));
218 for (int i = 0; i < rsize + striked; ++i)
221 match_len = findForward(cur, match, false);
224 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
226 cur_orig.fixIfBroken();
227 bv->setCursor(cur_orig);
233 // the idea here is that we are going to replace the string that
234 // is selected IF it is the search string.
235 // if there is a selection, but it is not the search string, then
236 // we basically ignore it. (FIXME We ought to replace only within
238 // if there is no selection, then:
239 // (i) if some search string has been provided, then we find it.
240 // (think of how the dialog works when you hit "replace" the
242 // (ii) if no search string has been provided, then we treat the
243 // word the cursor is in as the search string. (why? i have no
244 // idea.) but this only works in text?
246 // returns the number of replacements made (one, if any) and
247 // whether anything at all was done.
248 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
249 docstring const & replacestr, bool case_sens,
250 bool whole, bool forward, bool findnext)
252 Cursor & cur = bv->cursor();
254 if (!cur.selection()) {
255 // no selection, non-empty search string: find it
256 if (!searchstr.empty()) {
257 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
258 return make_pair(found, 0);
260 // empty search string
263 return make_pair(false, 0);
264 // select current word and treat it as the search string.
265 // This causes a minor bug as undo will restore this selection,
266 // which the user did not create (#8986).
267 cur.innerText()->selectWord(cur, WHOLE_WORD);
268 searchstr = cur.selectionAsString(false);
271 // if we still don't have a search string, report the error
273 if (!searchAllowed(searchstr))
274 return make_pair(false, 0);
276 bool have_selection = cur.selection();
277 docstring const selected = cur.selectionAsString(false);
280 ? searchstr == selected
281 : compare_no_case(searchstr, selected) == 0;
283 // no selection or current selection is not search word:
284 // just find the search word
285 if (!have_selection || !match) {
286 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
287 return make_pair(found, 0);
290 // we're now actually ready to replace. if the buffer is
291 // read-only, we can't, though.
292 if (bv->buffer().isReadonly())
293 return make_pair(false, 0);
295 cap::replaceSelectionWithString(cur, replacestr);
297 cur.pos() += replacestr.length();
298 LASSERT(cur.pos() <= cur.lastpos(),
299 cur.pos() = cur.lastpos());
302 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
304 return make_pair(true, 1);
310 docstring const find2string(docstring const & search,
311 bool casesensitive, bool matchword, bool forward)
315 << int(casesensitive) << ' '
316 << int(matchword) << ' '
322 docstring const replace2string(docstring const & replace,
323 docstring const & search,
324 bool casesensitive, bool matchword,
325 bool all, bool forward, bool findnext)
328 ss << replace << '\n'
330 << int(casesensitive) << ' '
331 << int(matchword) << ' '
333 << int(forward) << ' '
339 bool lyxfind(BufferView * bv, FuncRequest const & ev)
341 if (!bv || ev.action() != LFUN_WORD_FIND)
344 //lyxerr << "find called, cmd: " << ev << endl;
346 // data is of the form
348 // <casesensitive> <matchword> <forward>"
350 docstring howto = split(ev.argument(), search, '\n');
352 bool casesensitive = parse_bool(howto);
353 bool matchword = parse_bool(howto);
354 bool forward = parse_bool(howto);
356 return findOne(bv, search, casesensitive, matchword, forward, true, true);
360 bool lyxreplace(BufferView * bv,
361 FuncRequest const & ev, bool has_deleted)
363 if (!bv || ev.action() != LFUN_WORD_REPLACE)
366 // data is of the form
369 // <casesensitive> <matchword> <all> <forward> <findnext>"
372 docstring howto = split(ev.argument(), rplc, '\n');
373 howto = split(howto, search, '\n');
375 bool casesensitive = parse_bool(howto);
376 bool matchword = parse_bool(howto);
377 bool all = parse_bool(howto);
378 bool forward = parse_bool(howto);
379 bool findnext = howto.empty() ? true : parse_bool(howto);
384 int replace_count = 0;
386 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
387 update = replace_count > 0;
390 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
392 replace_count = rv.second;
395 Buffer const & buf = bv->buffer();
397 // emit message signal.
398 buf.message(_("String not found."));
400 if (replace_count == 0) {
401 buf.message(_("String found."));
402 } else if (replace_count == 1) {
403 buf.message(_("String has been replaced."));
405 docstring const str =
406 bformat(_("%1$d strings have been replaced."), replace_count);
410 } else if (findnext) {
411 // if we have deleted characters, we do not replace at all, but
412 // rather search for the next occurence
413 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
416 bv->message(_("String not found."));
422 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
424 for (; cur; cur.forwardPos())
425 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
429 DocIterator cur_orig(bv->cursor());
430 docstring q = _("End of file reached while searching forward.\n"
431 "Continue searching from the beginning?");
432 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
433 q, 0, 1, _("&Yes"), _("&No"));
434 if (wrap_answer == 0) {
435 bv->cursor().clear();
436 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
437 bv->clearSelection();
438 cur.setCursor(bv->cursor().selectionBegin());
439 if (findNextChange(bv, cur, false))
442 bv->cursor().setCursor(cur_orig);
449 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
451 for (cur.backwardPos(); cur; cur.backwardPos()) {
452 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
457 DocIterator cur_orig(bv->cursor());
458 docstring q = _("Beginning of file reached while searching backward.\n"
459 "Continue searching from the end?");
460 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
461 q, 0, 1, _("&Yes"), _("&No"));
462 if (wrap_answer == 0) {
463 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
464 bv->cursor().backwardPos();
465 bv->clearSelection();
466 cur.setCursor(bv->cursor().selectionBegin());
467 if (findPreviousChange(bv, cur, false))
470 bv->cursor().setCursor(cur_orig);
477 bool selectChange(Cursor & cur, bool forward)
479 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
481 Change ch = cur.paragraph().lookupChange(cur.pos());
483 CursorSlice tip1 = cur.top();
484 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
485 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
486 if (!ch2.isSimilarTo(ch))
489 CursorSlice tip2 = cur.top();
490 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
492 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
493 if (!ch2.isSimilarTo(ch)) {
494 // take a step forward to correctly set the selection
502 cur.bv().mouseSetCursor(cur, false);
504 cur.bv().mouseSetCursor(cur, true);
512 bool findChange(BufferView * bv, bool forward)
515 cur.setCursor(forward ? bv->cursor().selectionEnd()
516 : bv->cursor().selectionBegin());
517 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
518 return selectChange(cur, forward);
523 bool findNextChange(BufferView * bv)
525 return findChange(bv, true);
529 bool findPreviousChange(BufferView * bv)
531 return findChange(bv, false);
538 typedef vector<pair<string, string> > Escapes;
540 /// A map of symbols and their escaped equivalent needed within a regex.
541 /// @note Beware of order
542 Escapes const & get_regexp_escapes()
544 typedef std::pair<std::string, std::string> P;
546 static Escapes escape_map;
547 if (escape_map.empty()) {
548 escape_map.push_back(P("$", "_x_$"));
549 escape_map.push_back(P("{", "_x_{"));
550 escape_map.push_back(P("}", "_x_}"));
551 escape_map.push_back(P("[", "_x_["));
552 escape_map.push_back(P("]", "_x_]"));
553 escape_map.push_back(P("(", "_x_("));
554 escape_map.push_back(P(")", "_x_)"));
555 escape_map.push_back(P("+", "_x_+"));
556 escape_map.push_back(P("*", "_x_*"));
557 escape_map.push_back(P(".", "_x_."));
558 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
559 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
560 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
561 escape_map.push_back(P("_x_", "\\"));
566 /// A map of lyx escaped strings and their unescaped equivalent.
567 Escapes const & get_lyx_unescapes()
569 typedef std::pair<std::string, std::string> P;
571 static Escapes escape_map;
572 if (escape_map.empty()) {
573 escape_map.push_back(P("\\%", "%"));
574 escape_map.push_back(P("\\mathcircumflex ", "^"));
575 escape_map.push_back(P("\\mathcircumflex", "^"));
576 escape_map.push_back(P("\\backslash ", "\\"));
577 escape_map.push_back(P("\\backslash", "\\"));
578 escape_map.push_back(P("\\\\{", "_x_<"));
579 escape_map.push_back(P("\\\\}", "_x_>"));
580 escape_map.push_back(P("\\sim ", "~"));
581 escape_map.push_back(P("\\sim", "~"));
586 /// A map of escapes turning a regexp matching text to one matching latex.
587 Escapes const & get_regexp_latex_escapes()
589 typedef std::pair<std::string, std::string> P;
591 static Escapes escape_map;
592 if (escape_map.empty()) {
593 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
594 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
595 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
596 escape_map.push_back(P("\\[", "\\{\\[\\}"));
597 escape_map.push_back(P("\\]", "\\{\\]\\}"));
598 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
599 escape_map.push_back(P("%", "\\\\\\%"));
600 escape_map.push_back(P("#", "\\\\#"));
605 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
606 ** the found occurrence were escaped.
608 string apply_escapes(string s, Escapes const & escape_map)
610 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
611 Escapes::const_iterator it;
612 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
613 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
614 unsigned int pos = 0;
615 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
616 s.replace(pos, it->first.length(), it->second);
617 LYXERR(Debug::FIND, "After escape: " << s);
618 pos += it->second.length();
619 // LYXERR(Debug::FIND, "pos: " << pos);
622 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
627 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
628 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
629 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
630 string escape_for_regex(string s, bool match_latex)
633 while (pos < s.size()) {
634 size_t new_pos = s.find("\\regexp{", pos);
635 if (new_pos == string::npos)
637 LYXERR(Debug::FIND, "new_pos: " << new_pos);
638 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
639 LYXERR(Debug::FIND, "t [lyx]: " << t);
640 t = apply_escapes(t, get_regexp_escapes());
641 LYXERR(Debug::FIND, "t [rxp]: " << t);
642 s.replace(pos, new_pos - pos, t);
643 new_pos = pos + t.size();
644 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
645 LYXERR(Debug::FIND, "new_pos: " << new_pos);
646 if (new_pos == s.size())
648 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
649 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
650 LYXERR(Debug::FIND, "end_pos: " << end_pos);
651 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
652 LYXERR(Debug::FIND, "t in regexp : " << t);
653 t = apply_escapes(t, get_lyx_unescapes());
654 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
656 t = apply_escapes(t, get_regexp_latex_escapes());
657 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
659 if (end_pos == s.size()) {
660 s.replace(new_pos, end_pos - new_pos, t);
661 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
664 s.replace(new_pos, end_pos + 13 - new_pos, t);
665 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
666 pos = new_pos + t.size();
667 LYXERR(Debug::FIND, "pos: " << pos);
673 /// Wrapper for lyx::regex_replace with simpler interface
674 bool regex_replace(string const & s, string & t, string const & searchstr,
675 string const & replacestr)
677 lyx::regex e(searchstr, regex_constants::ECMAScript);
679 ostream_iterator<char, char> it(oss);
680 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
681 // tolerate t and s be references to the same variable
682 bool rv = (s != oss.str());
688 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
690 ** Verify that closed braces exactly match open braces. This avoids that, for example,
691 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
694 ** Number of open braces that must remain open at the end for the verification to succeed.
696 bool braces_match(string::const_iterator const & beg,
697 string::const_iterator const & end,
701 string::const_iterator it = beg;
702 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
703 for (; it != end; ++it) {
704 // Skip escaped braces in the count
709 } else if (*it == '{') {
711 } else if (*it == '}') {
712 if (open_pars == 0) {
713 LYXERR(Debug::FIND, "Found unmatched closed brace");
719 if (open_pars != unmatched) {
720 LYXERR(Debug::FIND, "Found " << open_pars
721 << " instead of " << unmatched
722 << " unmatched open braces at the end of count");
725 LYXERR(Debug::FIND, "Braces match as expected");
730 /** The class performing a match between a position in the document and the FindAdvOptions.
732 class MatchStringAdv {
734 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
736 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
737 ** constructor as opt.search, under the opt.* options settings.
740 ** If set, then match is searched only against beginning of text starting at cur.
741 ** If unset, then match is searched anywhere in text starting at cur.
744 ** The length of the matching text, or zero if no match was found.
746 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
751 /// first buffer on which search was started
752 lyx::Buffer * const p_first_buf;
754 FindAndReplaceOptions const & opt;
757 /// Auxiliary find method (does not account for opt.matchword)
758 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
760 /** Normalize a stringified or latexified LyX paragraph.
764 ** <li>if search is not casesensitive, then lowercase the string;
765 ** <li>remove any newline at begin or end of the string;
766 ** <li>replace any newline in the middle of the string with a simple space;
767 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
770 ** @todo Normalization should also expand macros, if the corresponding
771 ** search option was checked.
773 string normalize(docstring const & s, bool hack_braces) const;
774 // normalized string to search
775 string par_as_string;
776 // regular expression to use for searching
778 // same as regexp, but prefixed with a ".*"
780 // leading format material as string
781 string lead_as_string;
782 // par_as_string after removal of lead_as_string
783 string par_as_string_nolead;
784 // unmatched open braces in the search string/regexp
786 // number of (.*?) subexpressions added at end of search regexp for closing
787 // environments, math mode, styles, etc...
789 // Are we searching with regular expressions ?
794 static docstring buffer_to_latex(Buffer & buffer)
796 OutputParams runparams(&buffer.params().encoding());
797 odocstringstream ods;
799 runparams.nice = true;
800 runparams.flavor = OutputParams::LATEX;
801 runparams.linelen = 80; //lyxrc.plaintext_linelen;
802 // No side effect of file copying and image conversion
803 runparams.dryrun = true;
804 runparams.for_search = true;
805 pit_type const endpit = buffer.paragraphs().size();
806 for (pit_type pit = 0; pit != endpit; ++pit) {
807 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
808 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
814 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
817 if (!opt.ignoreformat) {
818 str = buffer_to_latex(buffer);
820 OutputParams runparams(&buffer.params().encoding());
821 runparams.nice = true;
822 runparams.flavor = OutputParams::LATEX;
823 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
824 runparams.dryrun = true;
825 runparams.for_search = true;
826 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
827 Paragraph const & par = buffer.paragraphs().at(pit);
828 LYXERR(Debug::FIND, "Adding to search string: '"
829 << par.asString(pos_type(0), par.size(),
830 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
833 str += par.asString(pos_type(0), par.size(),
834 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
842 /// Return separation pos between the leading material and the rest
843 static size_t identifyLeading(string const & s)
846 // @TODO Support \item[text]
847 // Kornel: Added textsl, textsf, textit, texttt and noun
848 // + allow to search for colored text too
849 while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|minisec|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
850 || regex_replace(t, t, REGEX_BOS "\\$", "")
851 || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
852 || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
853 || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
855 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
860 * Given a latexified string, retrieve some handled features
861 * The features of the regex will later be compared with the features
862 * of the searched text. If the regex features are not a
863 * subset of the analized, then, in not format ignoring search
864 * we can early stop the search in the relevant inset.
866 typedef map<string, bool> Features;
868 static Features identifyFeatures(string const & s)
870 static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
871 static regex const valid("^(((emph|noun|text(bf|sl|sf|it|tt)|(textcolor|foreignlanguage)\\{[a-z]+\\})|item |(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)$");
876 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
879 if (sub.str(1).compare("regexp") == 0) {
883 string token = sub.str(1);
885 if (regex_match(token, sub2, valid)) {
893 if (sub.str(1).compare("endregexp") == 0) {
903 * defines values features of a key "\\[a-z]+{"
910 isMain, /* for \\foreignlanguage */
917 isIgnored /* to be ignored by creating infos */
926 KeyInfo(KeyType type, int parcount, bool disable)
928 parenthesiscount(parcount),
937 int parenthesiscount;
939 bool used; /* by pattern */
944 Border(int l=0, int u=0) : low(l), upper(u) {};
951 bool isPatternString;
953 Intervall(bool isPattern) : isPatternString(isPattern), ignoreidx(-1), actualdeptindex(0) {};
956 int depts[MAXOPENED];
957 int closes[MAXOPENED];
959 Border borders[2*MAXOPENED];
960 // int previousNotIgnored(int);
961 int nextNotIgnored(int);
962 void handleOpenP(int i);
963 void handleCloseP(int i, bool closingAllowed);
964 void resetOpenedP(int openPos);
965 void addIntervall(int upper);
966 void addIntervall(int low, int upper); /* if explicit */
967 void setForDefaultLang(int upTo);
968 int findclosing(int start, int end);
969 void handleParentheses(int lastpos, bool closingAllowed);
970 void output(ostringstream &os, int lastpos);
971 // string show(int lastpos);
974 void Intervall::setForDefaultLang(int upTo)
976 // Enable the use of first token again
977 if (ignoreidx >= 0) {
978 if (borders[0].low < upTo)
979 borders[0].low = upTo;
980 if (borders[0].upper < upTo)
981 borders[0].upper = upTo;
985 static void checkDepthIndex(int val)
987 static int maxdepthidx = MAXOPENED-2;
988 if (val > maxdepthidx) {
990 LYXERR0("maxdepthidx now " << val);
994 static void checkIgnoreIdx(int val)
996 static int maxignoreidx = 2*MAXOPENED - 4;
997 if (val > maxignoreidx) {
999 LYXERR0("maxignoreidx now " << val);
1004 * Expand the region of ignored parts of the input latex string
1005 * The region is only relevant in output()
1007 void Intervall::addIntervall(int low, int upper)
1010 if (low == upper) return;
1011 for (idx = ignoreidx+1; idx > 0; --idx) {
1012 if (low > borders[idx-1].upper) {
1016 Border br(low, upper);
1017 if (idx > ignoreidx) {
1020 checkIgnoreIdx(ignoreidx);
1024 // Expand only if one of the new bound is inside the interwall
1025 // We know here that br.low > borders[idx-1].upper
1026 if (br.upper < borders[idx].low) {
1027 // We have to insert at this pos
1028 for (int i = ignoreidx+1; i > idx; --i) {
1029 borders[i] = borders[i-1];
1033 checkIgnoreIdx(ignoreidx);
1036 // Here we know, that we are overlapping
1037 if (br.low > borders[idx].low)
1038 br.low = borders[idx].low;
1039 // check what has to be concatenated
1041 for (int i = idx; i <= ignoreidx; i++) {
1042 if (br.upper >= borders[i].low) {
1044 if (br.upper < borders[i].upper)
1045 br.upper = borders[i].upper;
1051 // count should be >= 1 here
1054 for (int i = idx + count; i <= ignoreidx; i++) {
1055 borders[i-count+1] = borders[i];
1057 ignoreidx -= count - 1;
1063 void Intervall::handleOpenP(int i)
1066 depts[actualdeptindex] = i+1;
1067 closes[actualdeptindex] = -1;
1068 checkDepthIndex(actualdeptindex);
1071 void Intervall::handleCloseP(int i, bool closingAllowed)
1073 if (actualdeptindex <= 0) {
1074 if (! closingAllowed)
1075 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1076 // if we are at the very end
1077 addIntervall(i, i+1);
1080 closes[actualdeptindex] = i+1;
1085 void Intervall::resetOpenedP(int openPos)
1087 // Used as initializer for foreignlanguage entry
1088 actualdeptindex = 1;
1089 depts[1] = openPos+1;
1094 int Intervall::previousNotIgnored(int start)
1096 int idx = 0; /* int intervalls */
1097 for (idx = ignoreidx; idx >= 0; --idx) {
1098 if (start > borders[idx].upper)
1100 if (start >= borders[idx].low)
1101 start = borders[idx].low-1;
1107 int Intervall::nextNotIgnored(int start)
1109 int idx = 0; /* int intervalls */
1110 for (idx = 0; idx <= ignoreidx; idx++) {
1111 if (start < borders[idx].low)
1113 if (start < borders[idx].upper)
1114 start = borders[idx].upper;
1119 typedef map<string, KeyInfo> KeysMap;
1120 typedef vector< KeyInfo> Entries;
1121 static KeysMap keys = map<string, KeyInfo>();
1123 class IgnoreFormats {
1124 static bool ignoreFamily;
1125 static bool ignoreSeries;
1126 static bool ignoreShape;
1127 static bool ignoreUnderline;
1128 static bool ignoreMarkUp;
1129 static bool ignoreStrikeOut;
1130 static bool ignoreSectioning;
1131 static bool ignoreFrontMatter;
1132 static bool ignoreColor;
1133 static bool ignoreLanguage;
1135 bool getFamily() { return ignoreFamily; };
1136 bool getSeries() { return ignoreSeries; };
1137 bool getShape() { return ignoreShape; };
1138 bool getUnderline() { return ignoreUnderline; };
1139 bool getMarkUp() { return ignoreMarkUp; };
1140 bool getStrikeOut() { return ignoreStrikeOut; };
1141 bool getSectioning() { return ignoreSectioning; };
1142 bool getFrontMatter() { return ignoreFrontMatter; };
1143 bool getColor() { return ignoreColor; };
1144 bool getLanguage() { return ignoreLanguage; };
1146 void setIgnoreFormat(string type, bool value);
1149 bool IgnoreFormats::ignoreFamily = false;
1150 bool IgnoreFormats::ignoreSeries = false;
1151 bool IgnoreFormats::ignoreShape = false;
1152 bool IgnoreFormats::ignoreUnderline = false;
1153 bool IgnoreFormats::ignoreMarkUp = false;
1154 bool IgnoreFormats::ignoreStrikeOut = false;
1155 bool IgnoreFormats::ignoreSectioning = false;
1156 bool IgnoreFormats::ignoreFrontMatter= true;
1157 bool IgnoreFormats::ignoreColor = false;
1158 bool IgnoreFormats::ignoreLanguage = false;
1160 void IgnoreFormats::setIgnoreFormat(string type, bool value)
1162 if (type == "color") {
1163 ignoreColor = value;
1165 else if (type == "language") {
1166 ignoreLanguage = value;
1168 else if (type == "sectioning") {
1169 ignoreSectioning = value;
1170 ignoreFrontMatter = value;
1172 else if (type == "font") {
1173 ignoreSeries = value;
1174 ignoreShape = value;
1175 ignoreFamily = value;
1177 else if (type == "series") {
1178 ignoreSeries = value;
1180 else if (type == "shape") {
1181 ignoreShape = value;
1183 else if (type == "family") {
1184 ignoreFamily = value;
1186 else if (type == "markup") {
1187 ignoreMarkUp = value;
1189 else if (type == "underline") {
1190 ignoreUnderline = value;
1192 else if (type == "strike") {
1193 ignoreStrikeOut = value;
1196 #pragma GCC diagnostic push
1197 #pragma GCC diagnostic ignored "-Wpragmas"
1198 #pragma GCC diagnostic ignored "-Wunused"
1199 #pragma GCC diagnostic ignored "-Wunused-function"
1202 #define SUPPRESS_NOT_USED_WARN __attribute__ ((unused))
1204 #define SUPPRESS_NOT_USED_WARN
1207 void SUPPRESS_NOT_USED_WARN setIgnoreFormat(string type, bool value)
1209 IgnoreFormats().setIgnoreFormat(type, value);
1211 #pragma GCC diagnostic pop
1218 void buildKeys(bool);
1219 void buildEntries(bool);
1220 void makeKey(const string &, KeyInfo, bool isPatternString);
1221 void processRegion(int start, int region_end); /* remove {} parts */
1222 void removeHead(KeyInfo&, int count=0);
1226 LatexInfo(string par, bool isPatternString) : interval(isPatternString) {
1228 buildKeys(isPatternString);
1229 entries = vector<KeyInfo>();
1230 buildEntries(isPatternString);
1234 if (entries.empty()) {
1241 if (int(entries.size()) > entidx) {
1248 bool setNextKey(int idx) {
1249 if ((idx == entidx) && (entidx >= 0)) {
1256 int process(ostringstream &os, KeyInfo &actual);
1257 int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
1258 // string show(int lastpos) { return interval.show(lastpos);};
1259 int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1260 KeyInfo &getKeyInfo(int keyinfo) {
1261 static KeyInfo invalidInfo = KeyInfo();
1262 if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1265 return entries[keyinfo];
1267 void setForDefaultLang(int upTo) {interval.setForDefaultLang(upTo);};
1272 int Intervall::findclosing(int start, int end)
1276 for (int i = start; i < end; i += 1 + skip) {
1280 if (c == '\\') skip = 1;
1281 else if (c == '{') {
1284 else if (c == '}') {
1285 if (depth == 0) return(i);
1301 vector<MathEntry> entries;
1306 void insert(string wait, size_t start, size_t end) {
1307 MathEntry m = MathEntry();
1309 m.mathStart = start;
1311 m.mathSize = end - start;
1312 entries.push_back(m);
1314 bool evaluating(size_t pos) {
1315 while (actualIdx < entries.size()) {
1316 if (pos < entries[actualIdx].mathStart)
1318 if (pos < entries[actualIdx].mathEnd)
1324 bool empty() { return(entries.empty()); };
1325 size_t getEndPos() {
1326 if (entries.empty() || (actualIdx >= entries.size())) {
1329 return entries[actualIdx].mathEnd;
1331 size_t getStartPos() {
1332 if (entries.empty() || (actualIdx >= entries.size())) {
1333 return 100000; /* definitely enough? */
1335 return entries[actualIdx].mathStart;
1337 size_t getFirstPos() {
1339 return getStartPos();
1342 if (entries.empty() || (actualIdx >= entries.size())) {
1345 return entries[actualIdx].mathSize;
1347 void incrEntry() { actualIdx++; };
1350 void LatexInfo::buildEntries(bool isPatternString)
1352 static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multiline|align)\\*?)\\}");
1353 static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1354 static bool disableLanguageOverride = false;
1355 smatch sub, submath;
1356 bool evaluatingRegexp = false;
1358 bool evaluatingMath = false;
1360 bool math_end_waiting = false;
1361 size_t math_pos = 10000;
1364 for (sregex_iterator itmath(interval.par.begin(), interval.par.end(), rmath), end; itmath != end; ++itmath) {
1366 if (math_end_waiting) {
1367 size_t pos = submath.position(size_t(0));
1368 if (math_end == "$") {
1369 if ((submath.str(0) == "$") && (interval.par[pos-1] != '\\')) {
1370 mi.insert("$", math_pos, pos + 1);
1371 math_end_waiting = false;
1374 else if (math_end == "\\]") {
1375 if (submath.str(0) == "\\]") {
1376 mi.insert("\\]", math_pos, pos + 2);
1377 math_end_waiting = false;
1380 else if ((submath.str(1).compare("end") == 0) &&
1381 (submath.str(2).compare(math_end) == 0)) {
1382 mi.insert(math_end, math_pos, pos + submath.str(0).length());
1383 math_end_waiting = false;
1387 if (submath.str(1).compare("begin") == 0) {
1388 math_end_waiting = true;
1389 math_end = submath.str(2);
1390 math_pos = submath.position(size_t(0));
1392 else if (submath.str(0).compare("\\[") == 0) {
1393 math_end_waiting = true;
1395 math_pos = submath.position(size_t(0));
1397 else if (submath.str(0) == "$") {
1398 size_t pos = submath.position(size_t(0));
1399 if ((pos == 0) || (interval.par[pos-1] != '\\')) {
1400 math_end_waiting = true;
1407 // Ignore language if there is math somewhere in pattern-string
1408 if (isPatternString) {
1411 keys["foreignlanguage"].disabled = true;
1412 disableLanguageOverride = true;
1415 disableLanguageOverride = false;
1418 if (disableLanguageOverride) {
1419 keys["foreignlanguage"].disabled = true;
1422 math_pos = mi.getFirstPos();
1423 for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1425 string key = sub.str(3);
1427 if (sub.str(0)[0] == '\\')
1428 key = sub.str(0)[1];
1432 if (evaluatingRegexp) {
1433 if (sub.str(1).compare("endregexp") == 0) {
1434 evaluatingRegexp = false;
1435 // found._tokenstart already set
1436 found._dataEnd = sub.position(size_t(0)) + 13;
1437 found._dataStart = found._dataEnd;
1438 found._tokensize = found._dataEnd - found._tokenstart;
1439 found.parenthesiscount = 0;
1443 if (evaluatingMath) {
1444 if (size_t(sub.position(size_t(0))) < mi.getEndPos())
1446 evaluatingMath = false;
1448 math_pos = mi.getStartPos();
1450 if (keys.find(key) == keys.end()) {
1451 LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1455 if (key.compare("regexp") == 0) {
1456 evaluatingRegexp = true;
1457 found._tokenstart = sub.position(size_t(0));
1458 found._tokensize = 0;
1462 // Handle the other params of key
1463 if (found.keytype == KeyInfo::isIgnored)
1465 else if (found.keytype == KeyInfo::isMath) {
1466 if (size_t(sub.position(size_t(0))) == math_pos) {
1468 found._tokenstart = sub.position(size_t(0));
1469 found._tokensize = mi.getSize();
1470 found._dataEnd = found._tokenstart + found._tokensize;
1471 found._dataStart = found._dataEnd;
1472 found.parenthesiscount = 0;
1473 evaluatingMath = true;
1478 else if (found.keytype != KeyInfo::isRegex) {
1479 found._tokenstart = sub.position(size_t(0));
1480 if (found.parenthesiscount == 0) {
1481 // Probably to be discarded
1482 char following = interval.par[sub.position(size_t(0)) + sub.str(3).length() + 1];
1483 if (following == ' ')
1484 found.head = "\\" + sub.str(3) + " ";
1485 else if (following == '=') {
1486 // like \uldepth=1000pt
1487 found.head = sub.str(0);
1490 found.head = "\\" + key;
1491 found._tokensize = found.head.length();
1492 found._dataEnd = found._tokenstart + found._tokensize;
1493 found._dataStart = found._dataEnd;
1496 if (found.parenthesiscount == 1) {
1497 found.head = "\\" + key + "{";
1499 else if (found.parenthesiscount == 2) {
1500 found.head = sub.str(0) + "{";
1502 found._tokensize = found.head.length();
1503 found._dataStart = found._tokenstart + found.head.length();
1504 found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1505 if (isPatternString) {
1506 keys[key].used = true;
1510 entries.push_back(found);
1514 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
1516 stringstream s(keysstring);
1518 const char delim = '|';
1519 while (getline(s, key, delim)) {
1520 KeyInfo keyII(keyI);
1521 if (isPatternString) {
1524 else if ( !keys[key].used)
1525 keyII.disabled = true;
1530 void LatexInfo::buildKeys(bool isPatternString)
1533 static bool keysBuilt = false;
1534 if (keysBuilt && !isPatternString) return;
1536 // Know standard keys with 1 parameter.
1537 // Split is done, if not at start of region
1538 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, f.getFamily()), isPatternString);
1539 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, f.getSeries()), isPatternString);
1540 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, f.getShape()), isPatternString);
1541 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, f.getUnderline()), isPatternString);
1542 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, f.getMarkUp()), isPatternString);
1543 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, f.getStrikeOut()), isPatternString);
1545 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
1546 KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1547 makeKey("section*|subsection*|subsubsection*|paragraph*",
1548 KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1549 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, f.getSectioning()), isPatternString);
1550 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isSectioning, 1, f.getFrontMatter()), isPatternString);
1552 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
1554 // Split is done, if not at start of region
1555 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, f.getColor()), isPatternString);
1557 // Split is done always.
1558 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, f.getLanguage()), isPatternString);
1562 makeKey("backslash|textbackslash|textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 1, false), isPatternString);
1564 // Known macros to remove (including their parameter)
1566 makeKey("inputencoding|shortcut|label|ref", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
1568 // Macros to remove, but let the parameter survive
1570 makeKey("url|href|menuitem|footnote|code", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
1572 // Same effect as previous, parameter will survive (because there is no one anyway)
1574 makeKey("noindent", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
1575 // like ('tiny{}' or '\tiny ' ... }
1576 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, true), isPatternString);
1578 // Survives, like known character
1579 makeKey("lyx|latex|tex", KeyInfo(KeyInfo::isIgnored, 0, false), isPatternString);
1580 makeKey("item", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
1582 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1583 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1584 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
1586 makeKey("par|uldepth|ULdepth|protect", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
1588 if (isPatternString) {
1589 // Allow the first searched string to rebuild the keys too
1593 // no need to rebuild again
1599 * Keep the list of actual opened parentheses actual
1600 * (e.g. depth == 4 means there are 4 '{' not processed yet)
1602 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1605 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1609 if (c == '\\') skip = 1;
1610 else if (c == '{') {
1613 else if (c == '}') {
1614 handleCloseP(i, closingAllowed);
1620 string Intervall::show(int lastpos)
1622 int idx = 0; /* int intervalls */
1626 for (idx = 0; idx <= ignoreidx; idx++) {
1627 while (i < lastpos) {
1629 if (i <= borders[idx].low) {
1630 if (borders[idx].low > lastpos)
1631 printsize = lastpos - i;
1633 printsize = borders[idx].low - i;
1634 s += par.substr(i, printsize);
1636 if (i >= borders[idx].low)
1637 i = borders[idx].upper;
1640 i = borders[idx].upper;
1646 s += par.substr(i, lastpos-i);
1652 void Intervall::output(ostringstream &os, int lastpos)
1654 // get number of chars to output
1655 int idx = 0; /* int intervalls */
1657 for (idx = 0; idx <= ignoreidx; idx++) {
1660 if (i <= borders[idx].low) {
1661 if (borders[idx].low > lastpos)
1662 printsize = lastpos - i;
1664 printsize = borders[idx].low - i;
1665 os << par.substr(i, printsize);
1667 handleParentheses(i, false);
1668 if (i >= borders[idx].low)
1669 i = borders[idx].upper;
1672 i = borders[idx].upper;
1679 os << par.substr(i, lastpos-i);
1681 handleParentheses(lastpos, false);
1682 for (int i = actualdeptindex; i > 0; --i) {
1685 if (! isPatternString)
1687 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1690 void LatexInfo::processRegion(int start, int region_end)
1692 while (start < region_end) { /* Let {[} and {]} survive */
1693 if ((interval.par[start] == '{') &&
1694 (interval.par[start+1] != ']') &&
1695 (interval.par[start+1] != '[')) {
1696 // Closing is allowed past the region
1697 int closing = interval.findclosing(start+1, interval.par.length());
1698 interval.addIntervall(start, start+1);
1699 interval.addIntervall(closing, closing+1);
1701 start = interval.nextNotIgnored(start+1);
1705 void LatexInfo::removeHead(KeyInfo &actual, int count)
1707 if (actual.parenthesiscount == 0) {
1708 // "{\tiny{} ...}" ==> "{{} ...}"
1709 interval.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
1712 // Remove header hull, that is "\url{abcd}" ==> "abcd"
1713 interval.addIntervall(actual._tokenstart, actual._dataStart);
1714 interval.addIntervall(actual._dataEnd, actual._dataEnd+1);
1718 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
1721 switch (actual.keytype)
1723 case KeyInfo::isChar: {
1724 nextKeyIdx = getNextKey();
1727 case KeyInfo::isSize: {
1728 if (actual.disabled) {
1730 processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
1731 interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1732 nextKeyIdx = getNextKey();
1734 // Split on this key if not at start
1735 int start = interval.nextNotIgnored(previousStart);
1736 if (start < actual._tokenstart) {
1737 interval.output(os, actual._tokenstart);
1738 interval.addIntervall(start, actual._tokenstart);
1740 // discard entry if at end of actual
1741 nextKeyIdx = process(os, actual);
1745 case KeyInfo::isStandard: {
1746 if (actual.disabled) {
1748 processRegion(actual._dataStart, actual._dataStart+1);
1749 nextKeyIdx = getNextKey();
1751 // Split on this key if not at start
1752 int start = interval.nextNotIgnored(previousStart);
1753 if (start < actual._tokenstart) {
1754 interval.output(os, actual._tokenstart);
1755 interval.addIntervall(start, actual._tokenstart);
1757 // discard entry if at end of actual
1758 nextKeyIdx = process(os, actual);
1762 case KeyInfo::doRemove: {
1763 // Remove the key with all parameters
1764 interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1765 nextKeyIdx = getNextKey();
1768 case KeyInfo::isSectioning: {
1769 // Discard space before _tokenstart
1771 for (count = 0; count < actual._tokenstart; count++) {
1772 if (interval.par[actual._tokenstart-count-1] != ' ')
1775 if (actual.disabled) {
1776 removeHead(actual, count);
1777 nextKeyIdx = getNextKey();
1779 interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1780 nextKeyIdx = process(os, actual);
1784 case KeyInfo::isMath: {
1785 // Same as regex, use the content unchanged
1786 nextKeyIdx = getNextKey();
1789 case KeyInfo::isRegex: {
1790 // DO NOT SPLIT ON REGEX
1792 nextKeyIdx = getNextKey();
1795 case KeyInfo::isIgnored: {
1796 // Treat like a character for now
1797 nextKeyIdx = getNextKey();
1800 case KeyInfo::isMain: {
1801 if (actual.disabled) {
1803 if ((interval.par.substr(actual._dataStart, 3) == " \\[") ||
1804 (interval.par.substr(actual._dataStart, 8) == " \\begin{")) {
1805 // Discard also the space before math-equation
1806 interval.addIntervall(actual._dataStart, actual._dataStart+1);
1808 interval.resetOpenedP(actual._dataStart-1);
1811 if (actual._tokenstart == 0) {
1812 // for the first (and maybe dummy) language
1813 interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1815 interval.resetOpenedP(actual._dataStart-1);
1819 case KeyInfo::invalid:
1820 // This cannot happen, already handled
1823 // LYXERR0("Unhandled keytype");
1824 nextKeyIdx = getNextKey();
1831 int LatexInfo::process(ostringstream &os, KeyInfo &actual )
1833 int end = interval.nextNotIgnored(actual._dataEnd);
1834 int oldStart = actual._dataStart;
1835 int nextKeyIdx = getNextKey();
1837 if ((nextKeyIdx < 0) ||
1838 (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1839 (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1840 if (oldStart <= end) {
1841 processRegion(oldStart, end);
1846 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1848 if (nextKey.keytype == KeyInfo::isMain) {
1849 (void) dispatch(os, actual._dataStart, nextKey);
1850 end = nextKey._tokenstart;
1853 processRegion(oldStart, nextKey._tokenstart);
1854 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
1856 oldStart = nextKey._dataEnd+1;
1858 // now nextKey is either invalid or is outside of actual._dataEnd
1859 // output the remaining and discard myself
1860 if (oldStart <= end) {
1861 processRegion(oldStart, end);
1863 if (interval.par[end] == '}') {
1865 // This is the normal case.
1866 // But if using the firstlanguage, the closing may be missing
1868 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
1870 if (actual._dataEnd < end)
1871 output_end = interval.nextNotIgnored(actual._dataEnd);
1873 output_end = interval.nextNotIgnored(end);
1874 if (interval.nextNotIgnored(actual._dataStart) < output_end)
1875 interval.output(os, output_end);
1876 interval.addIntervall(actual._tokenstart, end);
1880 string splitOnKnownMacros(string par, bool isPatternString) {
1882 LatexInfo li(par, isPatternString);
1883 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
1885 DummyKey._tokensize = 0;
1886 DummyKey._tokenstart = 0;
1887 DummyKey._dataStart = 0;
1888 DummyKey._dataEnd = par.length();
1889 DummyKey.disabled = true;
1890 int firstkeyIdx = li.getFirstKey();
1892 if (firstkeyIdx >= 0) {
1893 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
1895 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
1896 // Use dummy firstKey
1897 firstKey = DummyKey;
1898 (void) li.setNextKey(firstkeyIdx);
1900 nextkeyIdx = li.process(os, firstKey);
1901 while (nextkeyIdx >= 0) {
1902 // Check for a possible gap between the last
1903 // entry and this one
1904 int datastart = li.nextNotIgnored(firstKey._dataStart);
1905 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1906 if ((nextKey._tokenstart > datastart)) {
1908 firstKey._dataStart = datastart;
1909 firstKey._dataEnd = par.length();
1910 (void) li.setNextKey(nextkeyIdx);
1911 if (firstKey._tokensize > 0) {
1912 // Fake the last opened parenthesis
1913 li.setForDefaultLang(firstKey._tokensize);
1915 nextkeyIdx = li.process(os, firstKey);
1918 if (nextKey.keytype != KeyInfo::isMain) {
1919 firstKey._dataStart = datastart;
1920 firstKey._dataEnd = nextKey._dataEnd+1;
1921 (void) li.setNextKey(nextkeyIdx);
1922 if (firstKey._tokensize > 0)
1923 li.setForDefaultLang(firstKey._tokensize);
1924 nextkeyIdx = li.process(os, firstKey);
1927 nextkeyIdx = li.process(os, nextKey);
1931 // Handle the remaining
1932 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1933 firstKey._dataEnd = par.length();
1934 if (firstKey._dataStart < firstKey._dataEnd)
1935 (void) li.process(os, firstKey);
1939 s = par; /* no known macros found */
1944 * Try to unify the language specs in the latexified text.
1945 * Resulting modified string is set to "", if
1946 * the searched tex does not contain all the features in the search pattern
1948 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
1950 static Features regex_f;
1951 static int missed = 0;
1952 static bool regex_with_format = false;
1954 int parlen = par.length();
1956 while ((parlen > 0) && (par[parlen-1] == '\n')) {
1961 // Split the latex input into pieces which
1962 // can be digested by our search engine
1963 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1964 result = splitOnKnownMacros(par, isPatternString);
1965 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1968 result = par.substr(0, parlen);
1969 if (isPatternString) {
1972 regex_f = identifyFeatures(result);
1973 string features = "";
1974 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1975 string a = it->first;
1976 regex_with_format = true;
1977 features += " " + a;
1978 // LYXERR0("Identified regex format:" << a);
1980 LYXERR(Debug::FIND, "Identified Features" << features);
1983 } else if (regex_with_format) {
1984 Features info = identifyFeatures(result);
1985 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1986 string a = it->first;
1987 bool b = it->second;
1988 if (b && ! info[a]) {
1990 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1996 // LYXERR0("No regex formats");
2002 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2003 static int identifyClosing(string & t)
2005 int open_braces = 0;
2007 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2008 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
2010 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
2012 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
2014 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
2024 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2025 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2027 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2028 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2029 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2030 // When using regexp, braces are hacked already by escape_for_regex()
2031 par_as_string = normalize(ds, !use_regexp);
2033 close_wildcards = 0;
2035 size_t lead_size = 0;
2036 // correct the language settings
2037 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2038 if (opt.ignoreformat) {
2040 // if par_as_string_nolead were emty,
2041 // the following call to findAux will always *find* the string
2042 // in the checked data, and thus always using the slow
2043 // examining of the current text part.
2044 par_as_string_nolead = par_as_string;
2047 lead_size = identifyLeading(par_as_string);
2048 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2049 lead_as_string = par_as_string.substr(0, lead_size);
2050 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2054 open_braces = identifyClosing(par_as_string);
2055 identifyClosing(par_as_string_nolead);
2056 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2057 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2059 string lead_as_regexp;
2060 if (lead_size > 0) {
2061 // @todo No need to search for \regexp{} insets in leading material
2062 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2063 par_as_string = par_as_string_nolead;
2064 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2065 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2067 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2068 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2069 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2071 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2072 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2073 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2074 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2075 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2076 || regex_replace(par_as_string, par_as_string,
2077 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2078 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2079 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2083 if (!opt.ignoreformat) {
2084 // Remove extra '\}' at end
2085 while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
2090 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2091 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2092 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2093 // replace '[^...]' with '[^...\}\{\\]'
2094 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2095 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2096 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2098 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2101 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2102 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2103 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
2104 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2106 // If entered regexp must match at begin of searched string buffer
2107 // Kornel: Added parentheses to use $1 for size of the leading string
2111 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2112 // Unfortunately is '\1', '\2', etc not working for strings with extra format
2113 // so the convert has no effect in that case
2114 for (int i = 8; i > 0; --i) {
2115 string orig = "\\\\" + std::to_string(i);
2116 string dest = "\\" + std::to_string(i+1);
2117 while (regex_replace(par_as_string, par_as_string, orig, dest));
2119 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2120 regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
2122 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2123 regexp = lyx::regex(regexp_str);
2125 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2126 regexp2 = lyx::regex(regexp2_str);
2131 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2134 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2137 docstring docstr = stringifyFromForSearch(opt, cur, len);
2138 string str = normalize(docstr, true);
2139 if (!opt.ignoreformat) {
2140 str = correctlanguagesetting(str, false, !opt.ignoreformat);
2142 if (str.empty()) return(-1);
2143 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
2144 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
2147 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
2148 regex const *p_regexp;
2149 regex_constants::match_flag_type flags;
2151 flags = regex_constants::match_continuous;
2154 flags = regex_constants::match_default;
2155 p_regexp = ®exp2;
2157 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
2158 if (re_it == sregex_iterator())
2160 match_results<string::const_iterator> const & m = *re_it;
2162 if (0) { // Kornel Benko: DO NOT CHECKK
2163 // Check braces on the segment that matched the entire regexp expression,
2164 // plus the last subexpression, if a (.*?) was inserted in the constructor.
2165 if (!braces_match(m[0].first, m[0].second, open_braces))
2169 // Check braces on segments that matched all (.*?) subexpressions,
2170 // except the last "padding" one inserted by lyx.
2171 for (size_t i = 1; i < m.size() - 1; ++i)
2172 if (!braces_match(m[i].first, m[i].second, open_braces))
2175 // Exclude from the returned match length any length
2176 // due to close wildcards added at end of regexp
2177 // and also the length of the leading (e.g. '\emph{')
2179 // Whole found string, including the leading: m[0].second - m[0].first
2180 // Size of the leading string: m[1].second - m[1].first
2181 int leadingsize = 0;
2183 leadingsize = m[1].second - m[1].first;
2185 for (size_t i = 0; i < m.size(); i++) {
2186 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2188 if (close_wildcards == 0)
2189 result = m[0].second - m[0].first;
2192 result = m[m.size() - close_wildcards].first - m[0].first;
2194 if (result > leadingsize)
2195 result -= leadingsize;
2201 // else !use_regexp: but all code paths above return
2202 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2203 << par_as_string << "', str='" << str << "'");
2204 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2205 << lead_as_string << "', par_as_string_nolead='"
2206 << par_as_string_nolead << "'");
2209 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2210 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2211 if (str.substr(0, par_as_string.size()) == par_as_string)
2212 return par_as_string.size();
2214 size_t pos = str.find(par_as_string_nolead);
2215 if (pos != string::npos)
2216 return par_as_string.size();
2222 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
2224 int res = findAux(cur, len, at_begin);
2226 "res=" << res << ", at_begin=" << at_begin
2227 << ", matchword=" << opt.matchword
2228 << ", inTexted=" << cur.inTexted());
2229 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
2231 Paragraph const & par = cur.paragraph();
2232 bool ws_left = (cur.pos() > 0)
2233 ? par.isWordSeparator(cur.pos() - 1)
2235 bool ws_right = (cur.pos() + res < par.size())
2236 ? par.isWordSeparator(cur.pos() + res)
2239 "cur.pos()=" << cur.pos() << ", res=" << res
2240 << ", separ: " << ws_left << ", " << ws_right
2242 if (ws_left && ws_right)
2248 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
2251 if (! opt.casesensitive)
2252 t = lyx::to_utf8(lowercase(s));
2254 t = lyx::to_utf8(s);
2255 // Remove \n at begin
2256 while (!t.empty() && t[0] == '\n')
2259 while (!t.empty() && t[t.size() - 1] == '\n')
2260 t = t.substr(0, t.size() - 1);
2262 // Replace all other \n with spaces
2263 while ((pos = t.find("\n")) != string::npos)
2264 t.replace(pos, 1, " ");
2265 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
2266 // Kornel: Added textsl, textsf, textit, texttt and noun
2267 // + allow to seach for colored text too
2268 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
2269 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
2270 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2271 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
2272 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2274 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
2275 // FIXME - check what preceeds the brace
2277 if (opt.ignoreformat)
2278 while (regex_replace(t, t, "\\{", "_x_<")
2279 || regex_replace(t, t, "\\}", "_x_>"))
2280 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2282 while (regex_replace(t, t, "\\\\\\{", "_x_<")
2283 || regex_replace(t, t, "\\\\\\}", "_x_>"))
2284 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2291 docstring stringifyFromCursor(DocIterator const & cur, int len)
2293 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2294 if (cur.inTexted()) {
2295 Paragraph const & par = cur.paragraph();
2296 // TODO what about searching beyond/across paragraph breaks ?
2297 // TODO Try adding a AS_STR_INSERTS as last arg
2298 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2299 int(par.size()) : cur.pos() + len;
2300 OutputParams runparams(&cur.buffer()->params().encoding());
2301 runparams.nice = true;
2302 runparams.flavor = OutputParams::LATEX;
2303 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2304 // No side effect of file copying and image conversion
2305 runparams.dryrun = true;
2306 LYXERR(Debug::FIND, "Stringifying with cur: "
2307 << cur << ", from pos: " << cur.pos() << ", end: " << end);
2308 return par.asString(cur.pos(), end,
2309 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2311 } else if (cur.inMathed()) {
2312 CursorSlice cs = cur.top();
2313 MathData md = cs.cell();
2314 MathData::const_iterator it_end =
2315 (( len == -1 || cs.pos() + len > int(md.size()))
2317 : md.begin() + cs.pos() + len );
2319 for (MathData::const_iterator it = md.begin() + cs.pos();
2322 docstring s = asString(md2);
2323 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2326 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2331 /** Computes the LaTeX export of buf starting from cur and ending len positions
2332 * after cur, if len is positive, or at the paragraph or innermost inset end
2335 docstring latexifyFromCursor(DocIterator const & cur, int len)
2337 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2338 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2339 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2340 Buffer const & buf = *cur.buffer();
2342 odocstringstream ods;
2344 OutputParams runparams(&buf.params().encoding());
2345 runparams.nice = false;
2346 runparams.flavor = OutputParams::LATEX;
2347 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2348 // No side effect of file copying and image conversion
2349 runparams.dryrun = true;
2350 runparams.for_search = true;
2352 if (cur.inTexted()) {
2353 // @TODO what about searching beyond/across paragraph breaks ?
2354 pos_type endpos = cur.paragraph().size();
2355 if (len != -1 && endpos > cur.pos() + len)
2356 endpos = cur.pos() + len;
2357 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2358 string(), cur.pos(), endpos);
2359 string s = lyx::to_utf8(ods.str());
2360 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2361 return(lyx::from_utf8(s));
2362 } else if (cur.inMathed()) {
2363 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2364 for (int s = cur.depth() - 1; s >= 0; --s) {
2365 CursorSlice const & cs = cur[s];
2366 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2368 cs.asInsetMath()->asHullInset()->header_write(ws);
2373 CursorSlice const & cs = cur.top();
2374 MathData md = cs.cell();
2375 MathData::const_iterator it_end =
2376 ((len == -1 || cs.pos() + len > int(md.size()))
2378 : md.begin() + cs.pos() + len);
2380 for (MathData::const_iterator it = md.begin() + cs.pos();
2384 ods << asString(md2);
2385 // Retrieve the math environment type, and add '$' or '$]'
2386 // or others (\end{equation}) accordingly
2387 for (int s = cur.depth() - 1; s >= 0; --s) {
2388 CursorSlice const & cs2 = cur[s];
2389 InsetMath * inset = cs2.asInsetMath();
2390 if (inset && inset->asHullInset()) {
2392 inset->asHullInset()->footer_write(ws);
2396 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2398 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2404 /** Finalize an advanced find operation, advancing the cursor to the innermost
2405 ** position that matches, plus computing the length of the matching text to
2408 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2410 // Search the foremost position that matches (avoids find of entire math
2411 // inset when match at start of it)
2413 DocIterator old_cur(cur.buffer());
2415 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2419 } while (cur && cur.depth() > d && match(cur) > 0);
2421 if (match(cur) <= 0) return 0;
2422 LYXERR(Debug::FIND, "Ok");
2424 // Compute the match length
2426 if (cur.pos() + len > cur.lastpos())
2428 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2429 while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2431 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2433 // Length of matched text (different from len param)
2434 int old_len = match(cur, len);
2435 if (old_len < 0) old_len = 0;
2437 // Greedy behaviour while matching regexps
2438 while ((new_len = match(cur, len + 1)) > old_len) {
2441 LYXERR(Debug::FIND, "verifying match with len = " << len);
2448 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2452 while (!theApp()->longOperationCancelled() && cur) {
2453 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2454 int match_len = match(cur, -1, false);
2455 LYXERR(Debug::FIND, "match_len: " << match_len);
2456 if (match_len > 0) {
2457 int match_len_zero_count = 0;
2458 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2459 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2460 int match_len2 = match(cur);
2461 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2462 if (match_len2 > 0) {
2463 // Sometimes in finalize we understand it wasn't a match
2464 // and we need to continue the outest loop
2465 int len = findAdvFinalize(cur, match);
2470 if (match_len2 >= 0) {
2471 if (match_len2 == 0)
2472 match_len_zero_count++;
2474 match_len_zero_count = 0;
2477 if (++match_len_zero_count > 3) {
2478 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2479 match_len_zero_count = 0;
2487 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2488 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2491 // This should exit nested insets, if any, or otherwise undefine the currsor.
2492 cur.pos() = cur.lastpos();
2493 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2501 /// Find the most backward consecutive match within same paragraph while searching backwards.
2502 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2504 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2505 DocIterator tmp_cur = cur;
2506 int len = findAdvFinalize(tmp_cur, match);
2507 Inset & inset = cur.inset();
2508 for (; cur != cur_begin; cur.backwardPos()) {
2509 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2510 DocIterator new_cur = cur;
2511 new_cur.backwardPos();
2512 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2514 int new_len = findAdvFinalize(new_cur, match);
2519 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2525 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2529 // Backup of original position
2530 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2531 if (cur == cur_begin)
2534 DocIterator cur_orig(cur);
2535 bool pit_changed = false;
2538 bool found_match = match(cur, -1, false);
2542 cur.pos() = cur.lastpos();
2544 cur.pos() = cur_orig.pos();
2545 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2546 DocIterator cur_prev_iter;
2548 found_match = match(cur);
2549 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2550 << found_match << ", cur: " << cur);
2552 return findMostBackwards(cur, match);
2554 // Stop if begin of document reached
2555 if (cur == cur_begin)
2557 cur_prev_iter = cur;
2561 if (cur == cur_begin)
2568 } while (!theApp()->longOperationCancelled());
2576 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2577 DocIterator const & cur, int len)
2579 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2581 if (!opt.ignoreformat)
2582 return latexifyFromCursor(cur, len);
2584 return stringifyFromCursor(cur, len);
2588 FindAndReplaceOptions::FindAndReplaceOptions(
2589 docstring const & find_buf_name, bool casesensitive,
2590 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2591 docstring const & repl_buf_name, bool keep_case,
2592 SearchScope scope, SearchRestriction restr)
2593 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2594 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2595 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2603 /** Check if 'len' letters following cursor are all non-lowercase */
2604 static bool allNonLowercase(Cursor const & cur, int len)
2606 pos_type beg_pos = cur.selectionBegin().pos();
2607 pos_type end_pos = cur.selectionBegin().pos() + len;
2608 if (len > cur.lastpos() + 1 - beg_pos) {
2609 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2610 len = cur.lastpos() + 1 - beg_pos;
2611 end_pos = beg_pos + len;
2613 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2614 if (isLowerCase(cur.paragraph().getChar(pos)))
2620 /** Check if first letter is upper case and second one is lower case */
2621 static bool firstUppercase(Cursor const & cur)
2624 pos_type pos = cur.selectionBegin().pos();
2625 if (pos >= cur.lastpos() - 1) {
2626 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2629 ch1 = cur.paragraph().getChar(pos);
2630 ch2 = cur.paragraph().getChar(pos + 1);
2631 bool result = isUpperCase(ch1) && isLowerCase(ch2);
2632 LYXERR(Debug::FIND, "firstUppercase(): "
2633 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2634 << ch2 << "(" << char(ch2) << ")"
2635 << ", result=" << result << ", cur=" << cur);
2640 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2642 ** \fixme What to do with possible further paragraphs in replace buffer ?
2644 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2646 ParagraphList::iterator pit = buffer.paragraphs().begin();
2647 LASSERT(pit->size() >= 1, /**/);
2648 pos_type right = pos_type(1);
2649 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2650 right = pit->size();
2651 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2657 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2659 Cursor & cur = bv->cursor();
2660 if (opt.repl_buf_name == docstring()
2661 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2662 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2665 DocIterator sel_beg = cur.selectionBegin();
2666 DocIterator sel_end = cur.selectionEnd();
2667 if (&sel_beg.inset() != &sel_end.inset()
2668 || sel_beg.pit() != sel_end.pit()
2669 || sel_beg.idx() != sel_end.idx())
2671 int sel_len = sel_end.pos() - sel_beg.pos();
2672 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2673 << ", sel_len: " << sel_len << endl);
2676 LASSERT(sel_len > 0, return);
2678 if (!matchAdv(sel_beg, sel_len))
2681 // Build a copy of the replace buffer, adapted to the KeepCase option
2682 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2684 repl_buffer_orig.write(oss);
2685 string lyx = oss.str();
2686 Buffer repl_buffer("", false);
2687 repl_buffer.setUnnamed(true);
2688 LASSERT(repl_buffer.readString(lyx), return);
2689 if (opt.keep_case && sel_len >= 2) {
2690 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2691 if (cur.inTexted()) {
2692 if (firstUppercase(cur))
2693 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2694 else if (allNonLowercase(cur, sel_len))
2695 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2698 cap::cutSelection(cur, false);
2699 if (cur.inTexted()) {
2700 repl_buffer.changeLanguage(
2701 repl_buffer.language(),
2702 cur.getFont().language());
2703 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2704 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2705 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2706 repl_buffer.params().documentClassPtr(),
2707 bv->buffer().errorList("Paste"));
2708 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2709 sel_len = repl_buffer.paragraphs().begin()->size();
2710 } else if (cur.inMathed()) {
2711 odocstringstream ods;
2713 OutputParams runparams(&repl_buffer.params().encoding());
2714 runparams.nice = false;
2715 runparams.flavor = OutputParams::LATEX;
2716 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2717 runparams.dryrun = true;
2718 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2719 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2720 docstring repl_latex = ods.str();
2721 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2723 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2724 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2725 repl_latex = from_utf8(s);
2726 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2727 MathData ar(cur.buffer());
2728 asArray(repl_latex, ar, Parse::NORMAL);
2730 sel_len = ar.size();
2731 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2733 if (cur.pos() >= sel_len)
2734 cur.pos() -= sel_len;
2737 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2738 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2739 bv->processUpdateFlags(Update::Force);
2743 /// Perform a FindAdv operation.
2744 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2749 // e.g., when invoking word-findadv from mini-buffer wither with
2750 // wrong options syntax or before ever opening advanced F&R pane
2751 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2755 MatchStringAdv matchAdv(bv->buffer(), opt);
2756 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2758 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2759 findAdvReplace(bv, opt, matchAdv);
2762 match_len = findForwardAdv(cur, matchAdv);
2764 match_len = findBackwardsAdv(cur, matchAdv);
2766 // This may only be raised by lyx::regex()
2767 bv->message(_("Invalid regular expression!"));
2771 if (match_len == 0) {
2772 bv->message(_("Match not found!"));
2776 bv->message(_("Match found!"));
2778 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2779 bv->putSelectionAt(cur, match_len, !opt.forward);
2785 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2787 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2788 << opt.casesensitive << ' '
2789 << opt.matchword << ' '
2790 << opt.forward << ' '
2791 << opt.expandmacros << ' '
2792 << opt.ignoreformat << ' '
2793 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2794 << opt.keep_case << ' '
2795 << int(opt.scope) << ' '
2798 LYXERR(Debug::FIND, "built: " << os.str());
2804 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2806 LYXERR(Debug::FIND, "parsing");
2810 while (line != "EOSS") {
2814 if (is.eof()) // Tolerate malformed request
2818 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2819 opt.find_buf_name = from_utf8(s);
2820 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2821 is.get(); // Waste space before replace string
2824 while (line != "EOSS") {
2828 if (is.eof()) // Tolerate malformed request
2832 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2833 opt.repl_buf_name = from_utf8(s);
2834 is >> opt.keep_case;
2837 opt.scope = FindAndReplaceOptions::SearchScope(i);
2839 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2841 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2842 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2843 << opt.scope << ' ' << opt.restr);