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("%", "\\\\\\%"));
604 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
605 ** the found occurrence were escaped.
607 string apply_escapes(string s, Escapes const & escape_map)
609 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
610 Escapes::const_iterator it;
611 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
612 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
613 unsigned int pos = 0;
614 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
615 s.replace(pos, it->first.length(), it->second);
616 LYXERR(Debug::FIND, "After escape: " << s);
617 pos += it->second.length();
618 // LYXERR(Debug::FIND, "pos: " << pos);
621 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
626 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
627 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
628 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
629 string escape_for_regex(string s, bool match_latex)
632 while (pos < s.size()) {
633 size_t new_pos = s.find("\\regexp{", pos);
634 if (new_pos == string::npos)
636 LYXERR(Debug::FIND, "new_pos: " << new_pos);
637 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
638 LYXERR(Debug::FIND, "t [lyx]: " << t);
639 t = apply_escapes(t, get_regexp_escapes());
640 LYXERR(Debug::FIND, "t [rxp]: " << t);
641 s.replace(pos, new_pos - pos, t);
642 new_pos = pos + t.size();
643 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
644 LYXERR(Debug::FIND, "new_pos: " << new_pos);
645 if (new_pos == s.size())
647 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
648 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
649 LYXERR(Debug::FIND, "end_pos: " << end_pos);
650 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
651 LYXERR(Debug::FIND, "t in regexp : " << t);
652 t = apply_escapes(t, get_lyx_unescapes());
653 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
655 t = apply_escapes(t, get_regexp_latex_escapes());
656 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
658 if (end_pos == s.size()) {
659 s.replace(new_pos, end_pos - new_pos, t);
660 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
663 s.replace(new_pos, end_pos + 13 - new_pos, t);
664 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
665 pos = new_pos + t.size();
666 LYXERR(Debug::FIND, "pos: " << pos);
672 /// Wrapper for lyx::regex_replace with simpler interface
673 bool regex_replace(string const & s, string & t, string const & searchstr,
674 string const & replacestr)
676 lyx::regex e(searchstr, regex_constants::ECMAScript);
678 ostream_iterator<char, char> it(oss);
679 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
680 // tolerate t and s be references to the same variable
681 bool rv = (s != oss.str());
687 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
689 ** Verify that closed braces exactly match open braces. This avoids that, for example,
690 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
693 ** Number of open braces that must remain open at the end for the verification to succeed.
695 bool braces_match(string::const_iterator const & beg,
696 string::const_iterator const & end,
700 string::const_iterator it = beg;
701 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
702 for (; it != end; ++it) {
703 // Skip escaped braces in the count
708 } else if (*it == '{') {
710 } else if (*it == '}') {
711 if (open_pars == 0) {
712 LYXERR(Debug::FIND, "Found unmatched closed brace");
718 if (open_pars != unmatched) {
719 LYXERR(Debug::FIND, "Found " << open_pars
720 << " instead of " << unmatched
721 << " unmatched open braces at the end of count");
724 LYXERR(Debug::FIND, "Braces match as expected");
729 /** The class performing a match between a position in the document and the FindAdvOptions.
731 class MatchStringAdv {
733 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
735 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
736 ** constructor as opt.search, under the opt.* options settings.
739 ** If set, then match is searched only against beginning of text starting at cur.
740 ** If unset, then match is searched anywhere in text starting at cur.
743 ** The length of the matching text, or zero if no match was found.
745 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
750 /// first buffer on which search was started
751 lyx::Buffer * const p_first_buf;
753 FindAndReplaceOptions const & opt;
756 /// Auxiliary find method (does not account for opt.matchword)
757 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
759 /** Normalize a stringified or latexified LyX paragraph.
763 ** <li>if search is not casesensitive, then lowercase the string;
764 ** <li>remove any newline at begin or end of the string;
765 ** <li>replace any newline in the middle of the string with a simple space;
766 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
769 ** @todo Normalization should also expand macros, if the corresponding
770 ** search option was checked.
772 string normalize(docstring const & s, bool hack_braces) const;
773 // normalized string to search
774 string par_as_string;
775 // regular expression to use for searching
777 // same as regexp, but prefixed with a ".*"
779 // leading format material as string
780 string lead_as_string;
781 // par_as_string after removal of lead_as_string
782 string par_as_string_nolead;
783 // unmatched open braces in the search string/regexp
785 // number of (.*?) subexpressions added at end of search regexp for closing
786 // environments, math mode, styles, etc...
788 // Are we searching with regular expressions ?
793 static docstring buffer_to_latex(Buffer & buffer)
795 OutputParams runparams(&buffer.params().encoding());
796 odocstringstream ods;
798 runparams.nice = true;
799 runparams.flavor = OutputParams::LATEX;
800 runparams.linelen = 80; //lyxrc.plaintext_linelen;
801 // No side effect of file copying and image conversion
802 runparams.dryrun = true;
803 runparams.for_search = true;
804 pit_type const endpit = buffer.paragraphs().size();
805 for (pit_type pit = 0; pit != endpit; ++pit) {
806 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
807 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
813 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
816 if (!opt.ignoreformat) {
817 str = buffer_to_latex(buffer);
819 OutputParams runparams(&buffer.params().encoding());
820 runparams.nice = true;
821 runparams.flavor = OutputParams::LATEX;
822 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
823 runparams.dryrun = true;
824 runparams.for_search = true;
825 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
826 Paragraph const & par = buffer.paragraphs().at(pit);
827 LYXERR(Debug::FIND, "Adding to search string: '"
828 << par.asString(pos_type(0), par.size(),
829 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
832 str += par.asString(pos_type(0), par.size(),
833 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
841 /// Return separation pos between the leading material and the rest
842 static size_t identifyLeading(string const & s)
845 // @TODO Support \item[text]
846 // Kornel: Added textsl, textsf, textit, texttt and noun
847 // + allow to seach for colored text too
848 while (regex_replace(t, t, REGEX_BOS "\\\\(((emph|noun|text(bf|sl|sf|it|tt))|((textcolor|foreignlanguage)\\{[a-z]+\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part)\\*?)\\{", "")
849 || regex_replace(t, t, REGEX_BOS "\\$", "")
850 || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
851 || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
852 || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
854 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
859 * Given a latexified string, retrieve some handled features
860 * The features of the regex will later be compared with the features
861 * of the searched text. If the regex features are not a
862 * subset of the analized, then, in not format ignoring search
863 * we can early stop the search in the relevant inset.
865 typedef map<string, bool> Features;
867 static Features identifyFeatures(string const & s)
869 static regex const feature("\\\\(([a-z]+(\\{([a-z]+)\\}|\\*)?))\\{");
870 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)\\*?)$");
875 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
878 if (sub.str(1).compare("regexp") == 0) {
882 string token = sub.str(1);
884 if (regex_match(token, sub2, valid)) {
892 if (sub.str(1).compare("endregexp") == 0) {
902 * Faster search for the related closing parenthesis
904 static int findclosing(string p, int start, int end)
908 int lastunclosed = start-1;
909 for (int i = start; i < end; i += 1 + skip) {
913 if (c == '\\') skip = 1;
919 if (depth == 0) return(i);
923 return(0 - lastunclosed);
927 * defines values features of a key "\\[a-z]+{"
934 isMain, /* for \\foreignlanguage */
941 isIgnored /* to be ignored by creating infos */
949 KeyInfo(KeyType type, int parcount, bool disable)
951 parenthesiscount(parcount),
952 disabled(disable) {};
959 int parenthesiscount;
965 Border(int l=0, int u=0) : low(l), upper(u) {};
973 Intervall() : ignoreidx(-1), actualdeptindex(0) {};
976 int depts[MAXOPENED];
977 int closes[MAXOPENED];
979 Border borders[2*MAXOPENED];
980 // int previousNotIgnored(int);
981 int nextNotIgnored(int);
982 void handleOpenP(int i);
983 void handleCloseP(int i, bool closingAllowed);
984 void resetOpenedP(int openPos);
985 void addIntervall(int upper);
986 void addIntervall(int low, int upper); /* if explicit */
987 void setForDefaultLang(int upTo);
988 int findclosing(int start, int end);
989 void handleParentheses(int lastpos, bool closingAllowed);
990 void output(ostringstream &os, int lastpos);
991 // string show(int lastpos);
994 void Intervall::setForDefaultLang(int upTo)
996 // Enable the use of first token again
997 if (ignoreidx >= 0) {
998 if (borders[0].low < upTo)
999 borders[0].low = upTo;
1000 if (borders[0].upper < upTo)
1001 borders[0].upper = upTo;
1005 static void checkDepthIndex(int val)
1007 static int maxdepthidx = MAXOPENED-2;
1008 if (val > maxdepthidx) {
1010 LYXERR0("maxdepthidx now " << val);
1014 static void checkIgnoreIdx(int val)
1016 static int maxignoreidx = 2*MAXOPENED - 4;
1017 if (val > maxignoreidx) {
1019 LYXERR0("maxignoreidx now " << val);
1024 * Expand the region of ignored parts of the input latex string
1025 * The region is only relevant in output()
1027 void Intervall::addIntervall(int low, int upper)
1030 if (low == upper) return;
1031 for (idx = ignoreidx+1; idx > 0; --idx) {
1032 if (low > borders[idx-1].upper) {
1036 Border br(low, upper);
1037 if (idx > ignoreidx) {
1040 checkIgnoreIdx(ignoreidx);
1044 // Expand only if one of the new bound is inside the interwall
1045 // We know here that br.low > borders[idx-1].upper
1046 if (br.upper < borders[idx].low) {
1047 // We have to insert at this pos
1048 for (int i = ignoreidx+1; i > idx; --i) {
1049 borders[i] = borders[i-1];
1053 checkIgnoreIdx(ignoreidx);
1056 // Here we know, that we are overlapping
1057 if (br.low > borders[idx].low)
1058 br.low = borders[idx].low;
1059 // check what has to be concatenated
1061 for (int i = idx; i <= ignoreidx; i++) {
1062 if (br.upper >= borders[i].low) {
1064 if (br.upper < borders[i].upper)
1065 br.upper = borders[i].upper;
1071 // count should be >= 1 here
1074 for (int i = idx + count; i <= ignoreidx; i++) {
1075 borders[i-count+1] = borders[i];
1077 ignoreidx -= count - 1;
1083 void Intervall::handleOpenP(int i)
1086 depts[actualdeptindex] = i+1;
1087 closes[actualdeptindex] = -1;
1088 checkDepthIndex(actualdeptindex);
1091 void Intervall::handleCloseP(int i, bool closingAllowed)
1093 if (actualdeptindex <= 0) {
1094 if (! closingAllowed)
1095 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1096 // if we are at the very end
1097 addIntervall(i, i+1);
1100 closes[actualdeptindex] = i+1;
1105 void Intervall::resetOpenedP(int openPos)
1107 // Used as initializer for foreignlanguage entry
1108 actualdeptindex = 1;
1109 depts[1] = openPos+1;
1114 int Intervall::previousNotIgnored(int start)
1116 int idx = 0; /* int intervalls */
1117 for (idx = ignoreidx; idx >= 0; --idx) {
1118 if (start > borders[idx].upper)
1120 if (start >= borders[idx].low)
1121 start = borders[idx].low-1;
1127 int Intervall::nextNotIgnored(int start)
1129 int idx = 0; /* int intervalls */
1130 for (idx = 0; idx <= ignoreidx; idx++) {
1131 if (start < borders[idx].low)
1133 if (start < borders[idx].upper)
1134 start = borders[idx].upper;
1139 typedef map<string, KeyInfo> KeysMap;
1140 typedef vector< KeyInfo> Entries;
1141 static KeysMap keys = map<string, KeyInfo>();
1147 KeyInfo analyze(string key);
1150 void buildEntries();
1151 void makeKey(const string &, KeyInfo);
1152 void processRegion(int start, int region_end); /* remove {} parts */
1153 void removeHead(KeyInfo&, int count=0);
1155 LatexInfo(string par) {
1158 entries = vector<KeyInfo>();
1163 if (entries.empty()) {
1170 if (int(entries.size()) > entidx) {
1177 bool setNextKey(int idx) {
1178 if ((idx == entidx) && (entidx >= 0)) {
1185 int process(ostringstream &os, KeyInfo &actual);
1186 int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
1187 // string show(int lastpos) { return interval.show(lastpos);};
1188 int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1189 KeyInfo &getKeyInfo(int keyinfo) {
1190 static KeyInfo invalidInfo = KeyInfo();
1191 if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1194 return entries[keyinfo];
1196 void setForDefaultLang(int upTo) {interval.setForDefaultLang(upTo);};
1201 int Intervall::findclosing(int start, int end)
1205 for (int i = start; i < end; i += 1 + skip) {
1209 if (c == '\\') skip = 1;
1210 else if (c == '{') {
1213 else if (c == '}') {
1214 if (depth == 0) return(i);
1221 void LatexInfo::buildEntries()
1223 static regex const rmath("\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multiline|align)\\*?)\\}");
1224 static regex const rkeys("\\\\((([a-z]+\\*?)(\\{([a-z]+\\*?)\\})?))");
1225 smatch sub, submath;
1226 bool evaluatingRegexp = false;
1228 bool math_end_waiting = false;
1229 size_t math_pos = 10000;
1231 int math_end_pos = -1;
1234 for (sregex_iterator itmath(interval.par.begin(), interval.par.end(), rmath), end; itmath != end; ++itmath) {
1236 if (math_end_waiting) {
1237 if ((submath.str(1).compare("end") == 0) &&
1238 (submath.str(2).compare(math_end) == 0)) {
1239 math_size = submath.position(0) + submath.str(0).length() - math_pos;
1240 math_end_waiting = false;
1244 if (submath.str(1).compare("begin") == 0) {
1245 math_end_waiting = true;
1246 math_end = submath.str(2);
1247 math_pos = submath.position(0);
1251 for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1253 if (evaluatingRegexp) {
1254 if (sub.str(1).compare("endregexp") == 0) {
1255 evaluatingRegexp = false;
1256 // found._tokenstart already set
1257 found._dataEnd = sub.position(0) + 13;
1258 found._dataStart = found._dataEnd;
1259 found._tokensize = found._dataEnd - found._tokenstart;
1260 found.parenthesiscount = 0;
1264 if (keys.find(sub.str(3)) == keys.end()) {
1265 LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1268 found = keys[sub.str(3)];
1269 if (sub.str(3).compare("regexp") == 0) {
1270 evaluatingRegexp = true;
1271 found._tokenstart = sub.position(0);
1272 found._tokensize = 0;
1276 // Handle the other params of key
1277 if (found.keytype == KeyInfo::isIgnored)
1279 else if (found.keytype == KeyInfo::isMath) {
1280 if (size_t(sub.position(0)) == math_pos) {
1281 found = keys[sub.str(3)];
1282 found._tokenstart = sub.position(0);
1283 found._tokensize = math_size;
1284 found._dataEnd = found._tokenstart + found._tokensize;
1285 found._dataStart = found._dataEnd;
1286 found.parenthesiscount = 0;
1287 math_end_pos = found._dataEnd;
1292 else if (found.keytype != KeyInfo::isRegex) {
1293 found._tokenstart = sub.position(0);
1294 if (found._tokenstart < math_end_pos) {
1295 // Ignore if we are inside math equation
1298 if (found.parenthesiscount == 0) {
1299 // Probably to be discarded
1300 if (interval.par[sub.position(0) + sub.str(3).length() + 1] == ' ')
1301 found.head = "\\" + sub.str(3) + " ";
1303 found.head = "\\" + sub.str(3);
1304 found._tokensize = found.head.length();
1305 found._dataEnd = found._tokenstart + found._tokensize;
1306 found._dataStart = found._dataEnd;
1309 if (found.parenthesiscount == 1) {
1310 found.head = "\\" + sub.str(3) + "{";
1312 else if (found.parenthesiscount == 2) {
1313 found.head = sub.str(0) + "{";
1314 found._tokensize = found.head.length();
1316 found._tokensize = found.head.length();
1317 found._dataStart = found._tokenstart + found.head.length();
1318 found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1321 entries.push_back(found);
1325 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI)
1327 stringstream s(keysstring);
1329 KeyInfo keyII(keyI);
1330 const char delim = '|';
1331 while (getline(s, key, delim)) {
1336 void LatexInfo::buildKeys()
1338 static bool keysBuilt = false;
1339 static bool ignoreFamily = false;
1340 static bool ignoreSeries = false;
1341 static bool ignoreShape = false;
1342 static bool ignoreUnderline = false;
1343 static bool ignoreMarkUp = false;
1344 static bool ignoreStrikeOut = false;
1345 static bool ignoreSectioning = false;
1346 static bool ignoreColor = false;
1347 static bool ignoreLanguage = false;
1349 if (keysBuilt) return;
1351 // Know statdard keys with 1 parameter.
1352 // Split is done, if not at start of region
1353 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFamily));
1354 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreSeries));
1355 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreShape));
1356 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreUnderline));
1357 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreMarkUp));
1358 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreStrikeOut));
1361 makeKey("section|subsection|subsubsection|paragraph|subparagraph",
1362 KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1363 makeKey("section*|subsection*|subsubsection*",
1364 KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1365 makeKey("title|part|part*", KeyInfo(KeyInfo::isSectioning, 1, ignoreSectioning));
1368 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false));
1370 // Split is done, if not at start of region
1371 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreColor));
1373 // Split is done always.
1374 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreLanguage));
1378 makeKey("backslash|textbackslash", KeyInfo(KeyInfo::isChar, 1, false));
1380 // Known macros to remove (including their parameter)
1382 makeKey("inputencoding|shortcut", KeyInfo(KeyInfo::doRemove, 1, false));
1384 // Macros to remove, but let the parameter survive
1386 makeKey("url|href|menuitem|footnote|code", KeyInfo(KeyInfo::isStandard, 1, true));
1388 // Same effect as previous, parameter will survive (because there is no one anyway)
1390 makeKey("noindent", KeyInfo(KeyInfo::isStandard, 0, true));
1391 // like ('tiny{}' or '\tiny ' ... }
1392 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, true));
1394 // Survives, like known character
1395 makeKey("lyx", KeyInfo(KeyInfo::isIgnored, 0, false));
1397 makeKey("begin", KeyInfo(KeyInfo::isMath, 1, false));
1398 makeKey("end", KeyInfo(KeyInfo::isMath, 1, false));
1400 makeKey("par", KeyInfo(KeyInfo::doRemove, 0, true));
1406 * Keep the list of actual opened parentheses actual
1407 * (e.g. depth == 4 means there are 4 '{' not processed yet)
1409 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1412 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1416 if (c == '\\') skip = 1;
1417 else if (c == '{') {
1420 else if (c == '}') {
1421 handleCloseP(i, closingAllowed);
1427 string Intervall::show(int lastpos)
1429 int idx = 0; /* int intervalls */
1433 for (idx = 0; idx <= ignoreidx; idx++) {
1434 while (i < lastpos) {
1436 if (i <= borders[idx].low) {
1437 if (borders[idx].low > lastpos)
1438 printsize = lastpos - i;
1440 printsize = borders[idx].low - i;
1441 s += par.substr(i, printsize);
1443 if (i >= borders[idx].low)
1444 i = borders[idx].upper;
1447 i = borders[idx].upper;
1453 s += par.substr(i, lastpos-i);
1459 void Intervall::output(ostringstream &os, int lastpos)
1461 // get number of chars to output
1462 int idx = 0; /* int intervalls */
1464 for (idx = 0; idx <= ignoreidx; idx++) {
1467 if (i <= borders[idx].low) {
1468 if (borders[idx].low > lastpos)
1469 printsize = lastpos - i;
1471 printsize = borders[idx].low - i;
1472 os << par.substr(i, printsize);
1474 handleParentheses(i, false);
1475 if (i >= borders[idx].low)
1476 i = borders[idx].upper;
1479 i = borders[idx].upper;
1486 os << par.substr(i, lastpos-i);
1488 handleParentheses(lastpos, false);
1489 for (int i = actualdeptindex; i > 0; --i) {
1492 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1495 void LatexInfo::processRegion(int start, int region_end)
1497 while (start < region_end) {
1498 if (interval.par[start] == '{') {
1499 // Closing is allowed past the region
1500 int closing = interval.findclosing(start+1, interval.par.length());
1501 interval.addIntervall(start, start+1);
1502 interval.addIntervall(closing, closing+1);
1504 start = interval.nextNotIgnored(start+1);
1508 void LatexInfo::removeHead(KeyInfo &actual, int count)
1510 if (actual.parenthesiscount == 0) {
1511 // "{\tiny{} ...}" ==> "{{} ...}"
1512 interval.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
1515 // Remove header hull, that is "\url{abcd}" ==> "abcd"
1516 interval.addIntervall(actual._tokenstart, actual._dataStart);
1517 interval.addIntervall(actual._dataEnd, actual._dataEnd+1);
1521 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
1524 switch (actual.keytype)
1526 case KeyInfo::isChar: {
1527 nextKeyIdx = getNextKey();
1530 case KeyInfo::isSize: {
1531 if (actual.disabled) {
1533 processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
1534 interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1535 nextKeyIdx = getNextKey();
1537 // Split on this key if not at start
1538 int start = interval.nextNotIgnored(previousStart);
1539 if (start < actual._tokenstart) {
1540 interval.output(os, actual._tokenstart);
1541 interval.addIntervall(start, actual._tokenstart);
1543 // discard entry if at end of actual
1544 nextKeyIdx = process(os, actual);
1548 case KeyInfo::isStandard: {
1549 if (actual.disabled) {
1551 processRegion(actual._dataStart, actual._dataStart+1);
1552 nextKeyIdx = getNextKey();
1554 // Split on this key if not at start
1555 int start = interval.nextNotIgnored(previousStart);
1556 if (start < actual._tokenstart) {
1557 interval.output(os, actual._tokenstart);
1558 interval.addIntervall(start, actual._tokenstart);
1560 // discard entry if at end of actual
1561 nextKeyIdx = process(os, actual);
1565 case KeyInfo::doRemove: {
1566 // Remove the key with all parameters
1567 interval.addIntervall(actual._tokenstart, actual._dataEnd+1);
1568 nextKeyIdx = getNextKey();
1571 case KeyInfo::isSectioning: {
1572 // Discard space before _tokenstart
1574 for (count = 0; count < actual._tokenstart; count++) {
1575 if (interval.par[actual._tokenstart-count-1] != ' ')
1578 if (actual.disabled) {
1579 removeHead(actual, count);
1580 nextKeyIdx = getNextKey();
1582 interval.addIntervall(actual._tokenstart-count, actual._tokenstart);
1583 nextKeyIdx = process(os, actual);
1587 case KeyInfo::isMath: {
1588 // Same as regex, use the content unchanged
1589 nextKeyIdx = getNextKey();
1592 case KeyInfo::isRegex: {
1593 // DO NOT SPLIT ON REGEX
1595 nextKeyIdx = getNextKey();
1598 case KeyInfo::isIgnored: {
1599 // Treat like a character for now
1600 nextKeyIdx = getNextKey();
1603 case KeyInfo::isMain: {
1604 if (actual.disabled) {
1606 interval.resetOpenedP(actual._dataStart-1);
1609 if (actual._tokenstart == 0) {
1610 // for the first (and maybe dummy) language
1611 interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1613 interval.resetOpenedP(actual._dataStart-1);
1617 case KeyInfo::invalid:
1618 // This cannot happen, already handled
1621 // LYXERR0("Unhandled keytype");
1622 nextKeyIdx = getNextKey();
1629 int LatexInfo::process(ostringstream &os, KeyInfo &actual )
1631 int end = interval.nextNotIgnored(actual._dataEnd);
1632 int oldStart = actual._dataStart;
1633 int nextKeyIdx = getNextKey();
1635 if ((nextKeyIdx < 0) ||
1636 (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1637 (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1638 if (oldStart <= end) {
1639 processRegion(oldStart, end);
1644 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1646 if (nextKey.keytype == KeyInfo::isMain) {
1647 (void) dispatch(os, actual._dataStart, nextKey);
1648 end = nextKey._tokenstart;
1651 processRegion(oldStart, nextKey._tokenstart);
1652 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
1654 oldStart = nextKey._dataEnd+1;
1656 // now nextKey is either invalid or is outside of actual._dataEnd
1657 // output the remaining and discard myself
1658 if (oldStart <= end) {
1659 processRegion(oldStart, end);
1661 if (interval.par[end] == '}') {
1663 // This is the normal case.
1664 // But if using the firstlanguage, the closing may be missing
1666 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
1668 if (actual._dataEnd < end)
1669 output_end = interval.nextNotIgnored(actual._dataEnd);
1671 output_end = interval.nextNotIgnored(end);
1672 if (interval.nextNotIgnored(actual._dataStart) < output_end)
1673 interval.output(os, output_end);
1674 interval.addIntervall(actual._tokenstart, end);
1678 string splitOnKnownMacros(string par) {
1681 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
1683 DummyKey._tokensize = 0;
1684 DummyKey._tokenstart = 0;
1685 DummyKey._dataStart = 0;
1686 DummyKey._dataEnd = par.length();
1687 DummyKey.disabled = true;
1688 int firstkeyIdx = li.getFirstKey();
1690 if (firstkeyIdx >= 0) {
1691 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
1693 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
1694 // Create dummy firstKey
1695 firstKey = DummyKey;
1696 (void) li.setNextKey(firstkeyIdx);
1698 nextkeyIdx = li.process(os, firstKey);
1699 while (nextkeyIdx >= 0) {
1700 // Check for a possible gap between the last
1701 // entry and this one
1702 int datastart = li.nextNotIgnored(firstKey._dataStart);
1703 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1704 if ((nextKey._tokenstart > datastart)) {
1706 firstKey._dataStart = datastart;
1707 firstKey._dataEnd = par.length();
1708 (void) li.setNextKey(nextkeyIdx);
1709 if (firstKey._tokensize > 0)
1710 li.setForDefaultLang(firstKey._tokensize);
1711 // Fake the last opened parenthesis
1712 nextkeyIdx = li.process(os, firstKey);
1715 if (nextKey.keytype != KeyInfo::isMain) {
1716 firstKey._dataStart = datastart;
1717 firstKey._dataEnd = nextKey._dataEnd+1;
1718 (void) li.setNextKey(nextkeyIdx);
1719 if (firstKey._tokensize > 0)
1720 li.setForDefaultLang(firstKey._tokensize);
1721 nextkeyIdx = li.process(os, firstKey);
1724 nextkeyIdx = li.process(os, nextKey);
1728 // Handle the remaining
1729 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1730 firstKey._dataEnd = par.length();
1731 if (firstKey._dataStart < firstKey._dataEnd)
1732 (void) li.process(os, firstKey);
1736 s = ""; /* found end */
1741 * Try to unify the language specs in the latexified text.
1742 * Resulting modified string is set to "", if
1743 * the searched tex does not contain all the features in the search pattern
1745 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1747 static Features regex_f;
1748 static int missed = 0;
1749 static bool regex_with_format = false;
1751 int parlen = par.length();
1753 while ((parlen > 0) && (par[parlen-1] == '\n')) {
1758 // Split the latex input into pieces which
1759 // can be digested by our search engine
1760 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1761 result = splitOnKnownMacros(par);
1762 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1765 result = par.substr(0, parlen);
1766 bool handle_colors = false;
1770 regex_f = identifyFeatures(result);
1771 string features = "";
1772 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1773 string a = it->first;
1774 regex_with_format = true;
1775 if (a.compare(0,10,"textcolor{") == 0)
1776 handle_colors = true;
1777 features += " " + a;
1778 // LYXERR0("Identified regex format:" << a);
1780 LYXERR(Debug::FIND, "Identified Features" << features);
1783 } else if (regex_with_format) {
1784 Features info = identifyFeatures(result);
1785 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1786 string a = it->first;
1787 bool b = it->second;
1788 if (b && ! info[a]) {
1790 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1793 else if (a.compare(0,10,"textcolor{") == 0)
1794 handle_colors = true;
1798 // LYXERR0("No regex formats");
1800 // remove possible disturbing macros
1801 while (regex_replace(result, result, "\\\\(noindent )", ""))
1803 // Either not found language spec,or is single and closed spec or empty
1806 static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1810 for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1812 string token = sub.str(1);
1813 pars.push_back(token);
1815 for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1817 int ti = result.find(token);
1818 int tokensize = token.size() + 1;
1820 int tc = findclosing(result, ti + tokensize, result.size());
1822 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1826 if (handle_colors) {
1827 while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1828 while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1834 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1835 static int identifyClosing(string & t)
1837 int open_braces = 0;
1839 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1840 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1842 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1844 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1846 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1856 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1857 : p_buf(&buf), p_first_buf(&buf), opt(opt)
1859 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1860 docstring const & ds = stringifySearchBuffer(find_buf, opt);
1861 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1862 // When using regexp, braces are hacked already by escape_for_regex()
1863 par_as_string = normalize(ds, !use_regexp);
1865 close_wildcards = 0;
1867 size_t lead_size = 0;
1868 // correct the language settings
1869 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1870 if (opt.ignoreformat) {
1872 // if par_as_string_nolead were emty,
1873 // the following call to findAux will always *find* the string
1874 // in the checked data, and thus always using the slow
1875 // examining of the current text part.
1876 par_as_string_nolead = par_as_string;
1879 lead_size = identifyLeading(par_as_string);
1880 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1881 lead_as_string = par_as_string.substr(0, lead_size);
1882 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1886 open_braces = identifyClosing(par_as_string);
1887 identifyClosing(par_as_string_nolead);
1888 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1889 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1891 string lead_as_regexp;
1892 if (lead_size > 0) {
1893 // @todo No need to search for \regexp{} insets in leading material
1894 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1895 par_as_string = par_as_string_nolead;
1896 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1897 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1899 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1900 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1901 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1903 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1904 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1905 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1906 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1907 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1908 || regex_replace(par_as_string, par_as_string,
1909 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1910 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1911 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1915 if (!opt.ignoreformat) {
1916 // Remove extra '\}' at end
1917 while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1921 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1922 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1923 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1924 // replace '[^...]' with '[^...\}\{\\]'
1925 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1926 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1927 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1929 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1931 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1932 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1933 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
1934 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1936 // If entered regexp must match at begin of searched string buffer
1937 // Kornel: Added parentheses to use $1 for size of the leading string
1941 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1942 // Unfortunately is '\1', '\2', etc not working for strings with extra format
1943 // so the convert has no effect in that case
1944 for (int i = 8; i > 0; --i) {
1945 string orig = "\\\\" + std::to_string(i);
1946 string dest = "\\" + std::to_string(i+1);
1947 while (regex_replace(par_as_string, par_as_string, orig, dest));
1949 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1950 regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1952 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1953 regexp = lyx::regex(regexp_str);
1955 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1956 regexp2 = lyx::regex(regexp2_str);
1961 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1964 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1967 docstring docstr = stringifyFromForSearch(opt, cur, len);
1968 string str = normalize(docstr, true);
1969 if (!opt.ignoreformat) {
1970 str = correctlanguagesetting(str, false, !opt.ignoreformat);
1972 if (str.empty()) return(-1);
1973 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
1974 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1977 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1978 regex const *p_regexp;
1979 regex_constants::match_flag_type flags;
1981 flags = regex_constants::match_continuous;
1984 flags = regex_constants::match_default;
1985 p_regexp = ®exp2;
1987 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1988 if (re_it == sregex_iterator())
1990 match_results<string::const_iterator> const & m = *re_it;
1992 if (0) { // Kornel Benko: DO NOT CHECKK
1993 // Check braces on the segment that matched the entire regexp expression,
1994 // plus the last subexpression, if a (.*?) was inserted in the constructor.
1995 if (!braces_match(m[0].first, m[0].second, open_braces))
1999 // Check braces on segments that matched all (.*?) subexpressions,
2000 // except the last "padding" one inserted by lyx.
2001 for (size_t i = 1; i < m.size() - 1; ++i)
2002 if (!braces_match(m[i].first, m[i].second, open_braces))
2005 // Exclude from the returned match length any length
2006 // due to close wildcards added at end of regexp
2007 // and also the length of the leading (e.g. '\emph{')
2009 // Whole found string, including the leading: m[0].second - m[0].first
2010 // Size of the leading string: m[1].second - m[1].first
2011 int leadingsize = 0;
2013 leadingsize = m[1].second - m[1].first;
2015 for (size_t i = 0; i < m.size(); i++) {
2016 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2018 if (close_wildcards == 0)
2019 result = m[0].second - m[0].first;
2022 result = m[m.size() - close_wildcards].first - m[0].first;
2024 if (result > leadingsize)
2025 result -= leadingsize;
2031 // else !use_regexp: but all code paths above return
2032 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2033 << par_as_string << "', str='" << str << "'");
2034 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2035 << lead_as_string << "', par_as_string_nolead='"
2036 << par_as_string_nolead << "'");
2039 LYXERR(Debug::FIND, "size=" << par_as_string.size()
2040 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
2041 if (str.substr(0, par_as_string.size()) == par_as_string)
2042 return par_as_string.size();
2044 size_t pos = str.find(par_as_string_nolead);
2045 if (pos != string::npos)
2046 return par_as_string.size();
2052 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
2054 int res = findAux(cur, len, at_begin);
2056 "res=" << res << ", at_begin=" << at_begin
2057 << ", matchword=" << opt.matchword
2058 << ", inTexted=" << cur.inTexted());
2059 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
2061 Paragraph const & par = cur.paragraph();
2062 bool ws_left = (cur.pos() > 0)
2063 ? par.isWordSeparator(cur.pos() - 1)
2065 bool ws_right = (cur.pos() + res < par.size())
2066 ? par.isWordSeparator(cur.pos() + res)
2069 "cur.pos()=" << cur.pos() << ", res=" << res
2070 << ", separ: " << ws_left << ", " << ws_right
2072 if (ws_left && ws_right)
2078 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
2081 if (! opt.casesensitive)
2082 t = lyx::to_utf8(lowercase(s));
2084 t = lyx::to_utf8(s);
2085 // Remove \n at begin
2086 while (!t.empty() && t[0] == '\n')
2089 while (!t.empty() && t[t.size() - 1] == '\n')
2090 t = t.substr(0, t.size() - 1);
2092 // Replace all other \n with spaces
2093 while ((pos = t.find("\n")) != string::npos)
2094 t.replace(pos, 1, " ");
2095 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
2096 // Kornel: Added textsl, textsf, textit, texttt and noun
2097 // + allow to seach for colored text too
2098 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
2099 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
2100 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2101 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
2102 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
2104 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
2105 // FIXME - check what preceeds the brace
2107 if (opt.ignoreformat)
2108 while (regex_replace(t, t, "\\{", "_x_<")
2109 || regex_replace(t, t, "\\}", "_x_>"))
2110 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2112 while (regex_replace(t, t, "\\\\\\{", "_x_<")
2113 || regex_replace(t, t, "\\\\\\}", "_x_>"))
2114 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2121 docstring stringifyFromCursor(DocIterator const & cur, int len)
2123 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2124 if (cur.inTexted()) {
2125 Paragraph const & par = cur.paragraph();
2126 // TODO what about searching beyond/across paragraph breaks ?
2127 // TODO Try adding a AS_STR_INSERTS as last arg
2128 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2129 int(par.size()) : cur.pos() + len;
2130 OutputParams runparams(&cur.buffer()->params().encoding());
2131 runparams.nice = true;
2132 runparams.flavor = OutputParams::LATEX;
2133 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2134 // No side effect of file copying and image conversion
2135 runparams.dryrun = true;
2136 LYXERR(Debug::FIND, "Stringifying with cur: "
2137 << cur << ", from pos: " << cur.pos() << ", end: " << end);
2138 return par.asString(cur.pos(), end,
2139 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2141 } else if (cur.inMathed()) {
2143 CursorSlice cs = cur.top();
2144 MathData md = cs.cell();
2145 MathData::const_iterator it_end =
2146 (( len == -1 || cs.pos() + len > int(md.size()))
2148 : md.begin() + cs.pos() + len );
2149 for (MathData::const_iterator it = md.begin() + cs.pos();
2151 s = s + asString(*it);
2152 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2155 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2160 /** Computes the LaTeX export of buf starting from cur and ending len positions
2161 * after cur, if len is positive, or at the paragraph or innermost inset end
2164 docstring latexifyFromCursor(DocIterator const & cur, int len)
2166 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2167 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2168 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2169 Buffer const & buf = *cur.buffer();
2171 odocstringstream ods;
2173 OutputParams runparams(&buf.params().encoding());
2174 runparams.nice = false;
2175 runparams.flavor = OutputParams::LATEX;
2176 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2177 // No side effect of file copying and image conversion
2178 runparams.dryrun = true;
2179 runparams.for_search = true;
2181 if (cur.inTexted()) {
2182 // @TODO what about searching beyond/across paragraph breaks ?
2183 pos_type endpos = cur.paragraph().size();
2184 if (len != -1 && endpos > cur.pos() + len)
2185 endpos = cur.pos() + len;
2186 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2187 string(), cur.pos(), endpos);
2188 string s = lyx::to_utf8(ods.str());
2189 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2190 return(lyx::from_utf8(s));
2191 } else if (cur.inMathed()) {
2192 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2193 for (int s = cur.depth() - 1; s >= 0; --s) {
2194 CursorSlice const & cs = cur[s];
2195 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2197 cs.asInsetMath()->asHullInset()->header_write(ws);
2202 CursorSlice const & cs = cur.top();
2203 MathData md = cs.cell();
2204 MathData::const_iterator it_end =
2205 ((len == -1 || cs.pos() + len > int(md.size()))
2207 : md.begin() + cs.pos() + len);
2208 for (MathData::const_iterator it = md.begin() + cs.pos();
2210 ods << asString(*it);
2212 // Retrieve the math environment type, and add '$' or '$]'
2213 // or others (\end{equation}) accordingly
2214 for (int s = cur.depth() - 1; s >= 0; --s) {
2215 CursorSlice const & cs2 = cur[s];
2216 InsetMath * inset = cs2.asInsetMath();
2217 if (inset && inset->asHullInset()) {
2219 inset->asHullInset()->footer_write(ws);
2223 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2225 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2231 /** Finalize an advanced find operation, advancing the cursor to the innermost
2232 ** position that matches, plus computing the length of the matching text to
2235 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2237 // Search the foremost position that matches (avoids find of entire math
2238 // inset when match at start of it)
2240 DocIterator old_cur(cur.buffer());
2242 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2246 } while (cur && cur.depth() > d && match(cur) > 0);
2248 if (match(cur) <= 0) return 0;
2249 LYXERR(Debug::FIND, "Ok");
2251 // Compute the match length
2253 if (cur.pos() + len > cur.lastpos())
2255 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2256 while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2258 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2260 // Length of matched text (different from len param)
2261 int old_len = match(cur, len);
2262 if (old_len < 0) old_len = 0;
2264 // Greedy behaviour while matching regexps
2265 while ((new_len = match(cur, len + 1)) > old_len) {
2268 LYXERR(Debug::FIND, "verifying match with len = " << len);
2275 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2279 while (!theApp()->longOperationCancelled() && cur) {
2280 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2281 int match_len = match(cur, -1, false);
2282 LYXERR(Debug::FIND, "match_len: " << match_len);
2283 if (match_len > 0) {
2284 int match_len_zero_count = 0;
2285 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2286 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2287 int match_len2 = match(cur);
2288 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2289 if (match_len2 > 0) {
2290 // Sometimes in finalize we understand it wasn't a match
2291 // and we need to continue the outest loop
2292 int len = findAdvFinalize(cur, match);
2297 if (match_len2 >= 0) {
2298 if (match_len2 == 0)
2299 match_len_zero_count++;
2301 match_len_zero_count = 0;
2304 if (++match_len_zero_count > 3) {
2305 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2306 match_len_zero_count = 0;
2314 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2315 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2318 // This should exit nested insets, if any, or otherwise undefine the currsor.
2319 cur.pos() = cur.lastpos();
2320 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2328 /// Find the most backward consecutive match within same paragraph while searching backwards.
2329 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2331 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2332 DocIterator tmp_cur = cur;
2333 int len = findAdvFinalize(tmp_cur, match);
2334 Inset & inset = cur.inset();
2335 for (; cur != cur_begin; cur.backwardPos()) {
2336 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2337 DocIterator new_cur = cur;
2338 new_cur.backwardPos();
2339 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2341 int new_len = findAdvFinalize(new_cur, match);
2346 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2352 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2356 // Backup of original position
2357 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2358 if (cur == cur_begin)
2361 DocIterator cur_orig(cur);
2362 bool pit_changed = false;
2365 bool found_match = match(cur, -1, false);
2369 cur.pos() = cur.lastpos();
2371 cur.pos() = cur_orig.pos();
2372 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2373 DocIterator cur_prev_iter;
2375 found_match = match(cur);
2376 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2377 << found_match << ", cur: " << cur);
2379 return findMostBackwards(cur, match);
2381 // Stop if begin of document reached
2382 if (cur == cur_begin)
2384 cur_prev_iter = cur;
2388 if (cur == cur_begin)
2395 } while (!theApp()->longOperationCancelled());
2403 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2404 DocIterator const & cur, int len)
2406 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2408 if (!opt.ignoreformat)
2409 return latexifyFromCursor(cur, len);
2411 return stringifyFromCursor(cur, len);
2415 FindAndReplaceOptions::FindAndReplaceOptions(
2416 docstring const & find_buf_name, bool casesensitive,
2417 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2418 docstring const & repl_buf_name, bool keep_case,
2419 SearchScope scope, SearchRestriction restr)
2420 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2421 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2422 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2430 /** Check if 'len' letters following cursor are all non-lowercase */
2431 static bool allNonLowercase(Cursor const & cur, int len)
2433 pos_type beg_pos = cur.selectionBegin().pos();
2434 pos_type end_pos = cur.selectionBegin().pos() + len;
2435 if (len > cur.lastpos() + 1 - beg_pos) {
2436 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2437 len = cur.lastpos() + 1 - beg_pos;
2438 end_pos = beg_pos + len;
2440 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2441 if (isLowerCase(cur.paragraph().getChar(pos)))
2447 /** Check if first letter is upper case and second one is lower case */
2448 static bool firstUppercase(Cursor const & cur)
2451 pos_type pos = cur.selectionBegin().pos();
2452 if (pos >= cur.lastpos() - 1) {
2453 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2456 ch1 = cur.paragraph().getChar(pos);
2457 ch2 = cur.paragraph().getChar(pos + 1);
2458 bool result = isUpperCase(ch1) && isLowerCase(ch2);
2459 LYXERR(Debug::FIND, "firstUppercase(): "
2460 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2461 << ch2 << "(" << char(ch2) << ")"
2462 << ", result=" << result << ", cur=" << cur);
2467 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2469 ** \fixme What to do with possible further paragraphs in replace buffer ?
2471 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2473 ParagraphList::iterator pit = buffer.paragraphs().begin();
2474 LASSERT(pit->size() >= 1, /**/);
2475 pos_type right = pos_type(1);
2476 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2477 right = pit->size();
2478 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2484 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2486 Cursor & cur = bv->cursor();
2487 if (opt.repl_buf_name == docstring()
2488 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2489 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2492 DocIterator sel_beg = cur.selectionBegin();
2493 DocIterator sel_end = cur.selectionEnd();
2494 if (&sel_beg.inset() != &sel_end.inset()
2495 || sel_beg.pit() != sel_end.pit()
2496 || sel_beg.idx() != sel_end.idx())
2498 int sel_len = sel_end.pos() - sel_beg.pos();
2499 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2500 << ", sel_len: " << sel_len << endl);
2503 LASSERT(sel_len > 0, return);
2505 if (!matchAdv(sel_beg, sel_len))
2508 // Build a copy of the replace buffer, adapted to the KeepCase option
2509 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2511 repl_buffer_orig.write(oss);
2512 string lyx = oss.str();
2513 Buffer repl_buffer("", false);
2514 repl_buffer.setUnnamed(true);
2515 LASSERT(repl_buffer.readString(lyx), return);
2516 if (opt.keep_case && sel_len >= 2) {
2517 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2518 if (cur.inTexted()) {
2519 if (firstUppercase(cur))
2520 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2521 else if (allNonLowercase(cur, sel_len))
2522 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2525 cap::cutSelection(cur, false);
2526 if (cur.inTexted()) {
2527 repl_buffer.changeLanguage(
2528 repl_buffer.language(),
2529 cur.getFont().language());
2530 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2531 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2532 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2533 repl_buffer.params().documentClassPtr(),
2534 bv->buffer().errorList("Paste"));
2535 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2536 sel_len = repl_buffer.paragraphs().begin()->size();
2537 } else if (cur.inMathed()) {
2538 odocstringstream ods;
2540 OutputParams runparams(&repl_buffer.params().encoding());
2541 runparams.nice = false;
2542 runparams.flavor = OutputParams::LATEX;
2543 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2544 runparams.dryrun = true;
2545 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2546 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2547 docstring repl_latex = ods.str();
2548 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2550 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2551 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2552 repl_latex = from_utf8(s);
2553 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2554 MathData ar(cur.buffer());
2555 asArray(repl_latex, ar, Parse::NORMAL);
2557 sel_len = ar.size();
2558 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2560 if (cur.pos() >= sel_len)
2561 cur.pos() -= sel_len;
2564 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2565 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2566 bv->processUpdateFlags(Update::Force);
2570 /// Perform a FindAdv operation.
2571 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2576 // e.g., when invoking word-findadv from mini-buffer wither with
2577 // wrong options syntax or before ever opening advanced F&R pane
2578 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2582 MatchStringAdv matchAdv(bv->buffer(), opt);
2583 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2585 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2586 findAdvReplace(bv, opt, matchAdv);
2589 match_len = findForwardAdv(cur, matchAdv);
2591 match_len = findBackwardsAdv(cur, matchAdv);
2593 // This may only be raised by lyx::regex()
2594 bv->message(_("Invalid regular expression!"));
2598 if (match_len == 0) {
2599 bv->message(_("Match not found!"));
2603 bv->message(_("Match found!"));
2605 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2606 bv->putSelectionAt(cur, match_len, !opt.forward);
2612 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2614 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2615 << opt.casesensitive << ' '
2616 << opt.matchword << ' '
2617 << opt.forward << ' '
2618 << opt.expandmacros << ' '
2619 << opt.ignoreformat << ' '
2620 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2621 << opt.keep_case << ' '
2622 << int(opt.scope) << ' '
2625 LYXERR(Debug::FIND, "built: " << os.str());
2631 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2633 LYXERR(Debug::FIND, "parsing");
2637 while (line != "EOSS") {
2641 if (is.eof()) // Tolerate malformed request
2645 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2646 opt.find_buf_name = from_utf8(s);
2647 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2648 is.get(); // Waste space before replace string
2651 while (line != "EOSS") {
2655 if (is.eof()) // Tolerate malformed request
2659 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2660 opt.repl_buf_name = from_utf8(s);
2661 is >> opt.keep_case;
2664 opt.scope = FindAndReplaceOptions::SearchScope(i);
2666 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2668 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2669 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2670 << opt.scope << ' ' << opt.restr);