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 */
940 isIgnored /* to be ignored by creating infos */
942 KeyInfo(string key) : head(key) {};
948 KeyInfo(KeyType type, int parcount)
950 parenthesiscount(parcount) {};
957 int parenthesiscount;
962 Border(int l=0, int u=0) : low(l), upper(u) {};
970 Intervall() : ignoreidx(-1), actualdeptindex(0) {};
973 int depts[MAXOPENED];
974 int closes[MAXOPENED];
976 Border borders[2*MAXOPENED];
977 // int previousNotIgnored(int);
978 int nextNotIgnored(int);
979 void handleOpenP(int i);
980 void handleCloseP(int i, bool closingAllowed);
981 void resetOpenedP(int openPos);
982 void addIntervall(int upper);
983 void addIntervall(int low, int upper); /* if explicit */
984 void setForDefaultLang(int upTo);
985 int findclosing(int start, int end);
986 void handleParentheses(int lastpos, bool closingAllowed);
987 void output(ostringstream &os, int lastpos);
988 // string show(int lastpos);
991 void Intervall::setForDefaultLang(int upTo)
993 // Enable the use of first token again
994 if (ignoreidx >= 0) {
995 if (borders[0].low < upTo)
996 borders[0].low = upTo;
997 if (borders[0].upper < upTo)
998 borders[0].upper = upTo;
1002 static void checkDepthIndex(int val)
1004 static int maxdepthidx = MAXOPENED-2;
1005 if (val > maxdepthidx) {
1007 LYXERR0("maxdepthidx now " << val);
1011 static void checkIgnoreIdx(int val)
1013 static int maxignoreidx = 2*MAXOPENED - 4;
1014 if (val > maxignoreidx) {
1016 LYXERR0("maxignoreidx now " << val);
1021 * Expand the region of ignored parts of the input latex string
1022 * The region is only relevant in output()
1024 void Intervall::addIntervall(int low, int upper)
1027 if (low == upper) return;
1028 for (idx = ignoreidx+1; idx > 0; --idx) {
1029 if (low > borders[idx-1].upper) {
1033 Border br(low, upper);
1034 if (idx > ignoreidx) {
1037 checkIgnoreIdx(ignoreidx);
1041 // Expand only if one of the new bound is inside the interwall
1042 // We know here that br.low > borders[idx-1].upper
1043 if (br.upper < borders[idx].low) {
1044 // We have to insert at this pos
1045 for (int i = ignoreidx+1; i > idx; --i) {
1046 borders[i] = borders[i-1];
1050 checkIgnoreIdx(ignoreidx);
1053 // Here we know, that we are overlapping
1054 if (br.low > borders[idx].low)
1055 br.low = borders[idx].low;
1056 // check what has to be concatenated
1058 for (int i = idx; i <= ignoreidx; i++) {
1059 if (br.upper >= borders[i].low) {
1061 if (br.upper < borders[i].upper)
1062 br.upper = borders[i].upper;
1068 // count should be >= 1 here
1071 for (int i = idx + count; i <= ignoreidx; i++) {
1072 borders[i-count+1] = borders[i];
1074 ignoreidx -= count - 1;
1080 void Intervall::handleOpenP(int i)
1083 depts[actualdeptindex] = i+1;
1084 closes[actualdeptindex] = -1;
1085 checkDepthIndex(actualdeptindex);
1088 void Intervall::handleCloseP(int i, bool closingAllowed)
1090 if (actualdeptindex <= 0) {
1091 if (closingAllowed) {
1092 // if we are at the very end
1093 addIntervall(i, i+1);
1096 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should never happen! */
1100 closes[actualdeptindex] = i+1;
1105 void Intervall::resetOpenedP(int openPos)
1107 actualdeptindex = 1;
1108 depts[1] = openPos+1;
1113 int Intervall::previousNotIgnored(int start)
1115 int idx = 0; /* int intervalls */
1116 for (idx = ignoreidx; idx >= 0; --idx) {
1117 if (start > borders[idx].upper)
1119 if (start >= borders[idx].low)
1120 start = borders[idx].low-1;
1126 int Intervall::nextNotIgnored(int start)
1128 int idx = 0; /* int intervalls */
1129 for (idx = 0; idx <= ignoreidx; idx++) {
1130 if (start < borders[idx].low)
1132 if (start < borders[idx].upper)
1133 start = borders[idx].upper;
1138 typedef map<string, KeyInfo> KeysMap;
1139 typedef vector< KeyInfo> Entries;
1140 static KeysMap keys = map<string, KeyInfo>();
1146 KeyInfo analyze(string key);
1149 void buildEntries();
1150 void makeKey(const string &, KeyInfo);
1151 void processRegion(ostringstream &os, int start, int region_end);
1153 LatexInfo(string par) {
1156 entries = vector<KeyInfo>();
1161 if (entries.empty()) {
1168 if (int(entries.size()) > entidx) {
1175 bool setNextKey(int idx) {
1176 if ((idx == entidx) && (entidx > 0)) {
1183 int process(ostringstream &os, int actual, bool faking);
1184 // string show(int lastpos) { return interval.show(lastpos);};
1185 int nextNotIgnored(int start) { return interval.nextNotIgnored(start);};
1186 KeyInfo &getKeyInfo(int keyinfo) {
1187 static KeyInfo invalidInfo = KeyInfo();
1188 if ((keyinfo < 0) || ( keyinfo >= int(entries.size())))
1191 return entries[keyinfo];
1196 int Intervall::findclosing(int start, int end)
1200 for (int i = start; i < end; i += 1 + skip) {
1204 if (c == '\\') skip = 1;
1205 else if (c == '{') {
1208 else if (c == '}') {
1209 if (depth == 0) return(i);
1216 void LatexInfo::buildEntries()
1218 static regex const rkeys("\\\\((([a-z]+\\*?)(\\{([a-z]+)\\})?))([\\{ ])");
1220 bool evaluatingRegexp = false;
1222 for (sregex_iterator it(interval.par.begin(), interval.par.end(), rkeys), end; it != end; ++it) {
1224 if (evaluatingRegexp) {
1225 if (sub.str(1).compare("endregexp") == 0) {
1226 evaluatingRegexp = false;
1227 // found._tokenstart already set
1228 found._dataEnd = sub.position(0) + 12;
1229 found._dataStart = found._tokenstart;
1233 if (keys.find(sub.str(3)) == keys.end()) {
1234 LYXERR(Debug::FIND, "Found unknown key " << sub.str(0));
1237 found = keys[sub.str(3)];
1238 if (sub.str(3).compare("regexp") == 0) {
1239 evaluatingRegexp = true;
1240 found._tokenstart = sub.position(0);
1241 found._tokensize = 0;
1245 // Handle the other params of key
1246 if (found.keytype == KeyInfo::isIgnored)
1248 else if (found.keytype == KeyInfo::isRegex) {
1251 found._tokenstart = sub.position(0);
1252 if (found.parenthesiscount == 0) {
1253 // Probably to be discarded
1254 if (interval.par[sub.position(0) + sub.str(3).length()] == ' ')
1255 found.head = "\\" + sub.str(3) + " ";
1257 found.head = "\\" + sub.str(3);
1258 found._tokensize = found.head.length();
1259 found._dataStart = found._dataEnd;
1262 if (found.parenthesiscount == 1) {
1263 found.head = "\\" + sub.str(3) + "{";
1265 else if (found.parenthesiscount == 2) {
1266 found.head = sub.str(0);
1267 found._tokensize = found.head.length();
1269 found._dataStart = found._tokenstart + found.head.length();
1270 found._dataEnd = interval.findclosing(found._dataStart, interval.par.length());
1273 entries.push_back(found);
1277 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI)
1279 stringstream s(keysstring);
1281 KeyInfo keyII(keyI);
1282 const char delim = '|';
1283 while (getline(s, key, delim)) {
1288 void LatexInfo::buildKeys()
1290 static bool keysBuilt = false;
1292 if (keysBuilt) return;
1293 KeyInfo foreign = KeyInfo(KeyInfo::isMain, 2);
1294 KeyInfo standard = KeyInfo(KeyInfo::isStandard,1);
1295 KeyInfo regex = KeyInfo(KeyInfo::isRegex, 1);
1296 KeyInfo color = KeyInfo(KeyInfo::isStandard, 2);
1297 KeyInfo character = KeyInfo(KeyInfo::isChar, 1);
1298 KeyInfo sectioning = KeyInfo(KeyInfo::isSectioning,1);
1299 KeyInfo toremove = KeyInfo(KeyInfo::doRemove, 1);
1300 KeyInfo leadremove = KeyInfo(KeyInfo::leadRemove,1);
1301 KeyInfo ignoreMe = KeyInfo(KeyInfo::isIgnored, 0);
1303 // Know statdard keys with 1 parameter.
1304 // Split is done, if not at start of region
1305 makeKey("textsf|texttt|textbf|textit|emph|noun|uuline|uline|sout|xout|uwave",standard);
1306 makeKey("section|subsection|subsubsection|paragraph|subparagraph", sectioning); /* let it survive */
1307 makeKey("section*|subsection*|subsubsection*", sectioning); /* let it survive */
1308 makeKey("title|part|part*", sectioning); /* let it survive */
1310 // Regex, split is not done, (but should it?)
1311 makeKey("regexp", regex);
1313 // Split is done, if not at start of region
1314 makeKey("textcolor", color);
1316 // Split is done always.
1317 makeKey("foreignlanguage", foreign);
1321 makeKey("backslash|textbackslash", character);
1323 // Known macros to remove (including their parameter)
1325 makeKey("inputencoding|shortcut", toremove);
1327 // Macros to remove, but let the parameter survive
1329 toremove.parenthesiscount = 0;
1330 makeKey("url|href|menuitem|footnote|code", leadremove);
1332 // Same effect as previous, parameter will survive (because there is no one anyway)
1334 leadremove.parenthesiscount = 0;
1335 makeKey("noindent|footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", leadremove);
1337 // Survives, like known character
1338 makeKey("lyx", ignoreMe);
1343 * Keep the list of actual opened parentheses actual
1344 * (e.g. depth == 4 means there are 4 '{' not processed yet)
1346 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
1349 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
1353 if (c == '\\') skip = 1;
1354 else if (c == '{') {
1357 else if (c == '}') {
1358 handleCloseP(i, closingAllowed);
1364 string Intervall::show(int lastpos)
1366 int idx = 0; /* int intervalls */
1370 for (idx = 0; idx <= ignoreidx; idx++) {
1371 while (i < lastpos) {
1373 if (i <= borders[idx].low) {
1374 if (borders[idx].low > lastpos)
1375 printsize = lastpos - i;
1377 printsize = borders[idx].low - i;
1378 s += par.substr(i, printsize);
1380 if (i >= borders[idx].low)
1381 i = borders[idx].upper;
1384 i = borders[idx].upper;
1390 s += par.substr(i, lastpos-i);
1396 void Intervall::output(ostringstream &os, int lastpos)
1398 // get number of chars to output
1399 int idx = 0; /* int intervalls */
1401 for (idx = 0; idx <= ignoreidx; idx++) {
1404 if (i <= borders[idx].low) {
1405 if (borders[idx].low > lastpos)
1406 printsize = lastpos - i;
1408 printsize = borders[idx].low - i;
1409 os << par.substr(i, printsize);
1411 handleParentheses(i, false);
1412 if (i >= borders[idx].low)
1413 i = borders[idx].upper;
1416 i = borders[idx].upper;
1423 os << par.substr(i, lastpos-i);
1425 handleParentheses(lastpos, false);
1426 for (int i = actualdeptindex; i > 0; --i) {
1429 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
1432 void LatexInfo::processRegion(ostringstream &os, int start, int region_end)
1434 int old_start = start;
1435 while (start < region_end) {
1436 if (interval.par[start] == '{') {
1437 int closing = interval.findclosing(start+1, region_end);
1438 interval.addIntervall(start, start+1);
1439 interval.addIntervall(closing, closing+1);
1441 start = interval.nextNotIgnored(start+1);
1443 start = interval.nextNotIgnored(old_start);
1444 if (start < region_end) {
1445 interval.output(os, region_end);
1446 interval.addIntervall(start, region_end);
1450 int LatexInfo::process(ostringstream &os, int actualidx, bool faking)
1452 KeyInfo &actual = getKeyInfo(actualidx);
1453 int nextKeyIdx = getNextKey();
1454 int start, old_start;
1455 int end = interval.nextNotIgnored(actual._dataEnd);
1456 old_start = interval.nextNotIgnored(actual._dataStart);
1458 // Adapt for start of first open parenthesis
1459 interval.setForDefaultLang(actual._tokenstart + actual._tokensize);
1461 if (actual.keytype == KeyInfo::isMain) {
1462 // Fake for opened braces
1463 interval.resetOpenedP(actual._dataStart-1);
1466 if ((nextKeyIdx < 0) ||
1467 (entries[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
1468 (entries[nextKeyIdx].keytype == KeyInfo::invalid)) {
1469 processRegion(os, old_start, end);
1473 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
1474 if (nextKey.keytype == KeyInfo::isMain) {
1475 end = nextKey._tokenstart;
1478 switch (nextKey.keytype)
1480 case KeyInfo::isChar: {
1481 old_start = nextKey._dataEnd+1;
1482 nextKeyIdx = getNextKey();
1485 case KeyInfo::isStandard: {
1486 // Split on this key
1487 processRegion(os, old_start, nextKey._tokenstart);
1488 old_start = nextKey._dataEnd+1;
1489 nextKeyIdx = process(os, nextKeyIdx, false);
1492 case KeyInfo::isSectioning: {
1493 // Discard space before _tokenstart
1495 for (count = 0; count < nextKey._tokenstart; count++) {
1496 if (interval.par[nextKey._tokenstart-count-1] != ' ')
1499 interval.addIntervall(nextKey._tokenstart-count, nextKey._tokenstart);
1500 processRegion(os, old_start, nextKey._tokenstart);
1501 old_start = nextKey._dataEnd+1;
1502 nextKeyIdx = process(os, nextKeyIdx, false);
1505 case KeyInfo::doRemove: {
1506 // Remove the key with all parameters
1507 interval.addIntervall(nextKey._tokenstart, nextKey._dataEnd+1);
1508 nextKeyIdx = getNextKey();
1511 case KeyInfo::leadRemove: {
1512 // Disable output of header of this key
1513 // ( == remove header)
1514 if (nextKey.parenthesiscount == 0) {
1515 // "{\tiny{} ...}" ==> "{{} ...}"
1516 interval.addIntervall(nextKey._tokenstart, nextKey._tokenstart + nextKey._tokensize);
1519 // Remove header hull, that is "\url{abcd}" ==> "abcd"
1520 interval.addIntervall(nextKey._tokenstart, nextKey._dataStart);
1521 interval.addIntervall(nextKey._dataEnd, nextKey._dataEnd+1);
1523 nextKeyIdx = getNextKey();
1526 case KeyInfo::isRegex: {
1527 /* DO NOT SPLIT ON REGEX
1528 // Copy regexp part as is
1529 // Do split in any case
1530 processRegion(os, old_start, nextKey._tokenstart);
1531 // Now split on end of regexp{ ...} too
1532 interval.output(os, nextKey._dataEnd+1);
1533 old_start = nextKey._dataEnd+1;
1534 interval.addIntervall(nextKey._tokenstart, nextKey._dataEnd+1);
1536 nextKeyIdx = getNextKey();
1539 case KeyInfo::isIgnored: {
1540 // Treat like a character for now
1541 nextKeyIdx = getNextKey();
1544 case KeyInfo::isMain:
1545 // This cannot happen, already handled
1547 case KeyInfo::invalid:
1548 // This cannot happen, already handled
1551 // LYXERR0("Unhandled keytype");
1552 nextKeyIdx = getNextKey();
1557 // now nextKey is either invalid or is outside of actual._dataEnd
1558 // output the remaing and discard myself
1559 start = interval.nextNotIgnored(actual._dataStart);
1560 processRegion(os, start, end);
1561 if (interval.par[end] == '}') {
1563 // This is the normal case.
1564 // But if using the firstlanguage, the closing may be missing
1566 interval.addIntervall(actual._tokenstart, end);
1568 // Adapt for start of first open parenthesis
1573 string splitOnKnownMacros(string par) {
1576 int firstkeyIdx = li.getFirstKey();
1578 if (firstkeyIdx >= 0) {
1579 int nextkeyIdx = li.process(os, firstkeyIdx, true);
1580 KeyInfo &firstKey = li.getKeyInfo(firstkeyIdx);
1581 while (nextkeyIdx >= 0) {
1582 // Check for a possible gap between the last
1583 // entry and this one
1584 int datastart = li.nextNotIgnored(firstKey._dataStart);
1585 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
1586 if (nextKey._tokenstart > datastart) {
1588 firstKey._dataStart = datastart;
1589 firstKey._dataEnd = nextKey._tokenstart;
1590 (void) li.setNextKey(nextkeyIdx);
1591 // Fake the last opened parenthesis
1592 int testkey = li.process(os, firstkeyIdx, true); /* The returned key should be the same */
1593 if (testkey != nextkeyIdx) {
1594 LYXERR(Debug::FIND,"Something's wrong");
1598 if (nextKey.keytype != KeyInfo::isMain) {
1599 firstKey._dataStart = datastart;
1600 firstKey._dataEnd = nextKey._dataEnd+1;
1601 (void) li.setNextKey(nextkeyIdx);
1602 nextkeyIdx = li.process(os, firstkeyIdx, true);
1605 nextkeyIdx = li.process(os, nextkeyIdx, false);
1609 // Handle the remaining
1610 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
1611 firstKey._dataEnd = par.length();
1612 if (firstKey._dataStart +1 < firstKey._dataEnd)
1613 (void) li.process(os, firstkeyIdx, true);
1617 s = ""; /* found end */
1622 * Try to unify the language specs in the latexified text.
1623 * Resulting modified string is set to "", if
1624 * the searched tex does not contain all the features in the search pattern
1626 static string correctlanguagesetting(string par, bool from_regex, bool withformat)
1628 static Features regex_f;
1629 static int missed = 0;
1630 static bool regex_with_format = false;
1632 int parlen = par.length();
1634 while ((parlen > 0) && (par[parlen-1] == '\n')) {
1639 // Split the latex input into pieces which
1640 // can be digested by our search engine
1641 LYXERR(Debug::FIND, "input: \"" << par << "\"");
1642 result = splitOnKnownMacros(par);
1643 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
1646 result = par.substr(0, parlen);
1647 bool handle_colors = false;
1651 regex_f = identifyFeatures(result);
1652 string features = "";
1653 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1654 string a = it->first;
1655 regex_with_format = true;
1656 if (a.compare(0,10,"textcolor{") == 0)
1657 handle_colors = true;
1658 features += " " + a;
1659 // LYXERR0("Identified regex format:" << a);
1661 LYXERR(Debug::FIND, "Identified Features" << features);
1664 } else if (regex_with_format) {
1665 Features info = identifyFeatures(result);
1666 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
1667 string a = it->first;
1668 bool b = it->second;
1669 if (b && ! info[a]) {
1671 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
1674 else if (a.compare(0,10,"textcolor{") == 0)
1675 handle_colors = true;
1679 // LYXERR0("No regex formats");
1681 // remove possible disturbing macros
1682 while (regex_replace(result, result, "\\\\(noindent )", ""))
1684 // Either not found language spec,or is single and closed spec or empty
1687 static regex const parreg("((\\n)?\\\\[a-z]+par)\\{");
1691 for (sregex_iterator it(result.begin(), result.end(), parreg), end; it != end; ++it) {
1693 string token = sub.str(1);
1694 pars.push_back(token);
1696 for (list<string>::const_iterator li = pars.begin(); li != pars.end(); ++li) {
1698 int ti = result.find(token);
1699 int tokensize = token.size() + 1;
1701 int tc = findclosing(result, ti + tokensize, result.size());
1703 result = result.substr(0, ti) + result.substr(ti + tokensize, tc - ti -tokensize) + result.substr(tc+1);
1707 if (handle_colors) {
1708 while (regex_replace(result, result, "(\\{\\\\textcolor\\{[a-z]+\\}\\{)\\s*\\{\\}\\s*", "$1"));
1709 while (regex_replace(result, result, "\\{\\\\textcolor\\{[a-z]+\\}\\{\\s*\\}\\s*\\}", ""));
1715 // Remove trailing closure of math, macros and environments, so to catch parts of them.
1716 static int identifyClosing(string & t)
1718 int open_braces = 0;
1720 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
1721 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
1723 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
1725 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
1727 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
1737 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
1738 : p_buf(&buf), p_first_buf(&buf), opt(opt)
1740 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
1741 docstring const & ds = stringifySearchBuffer(find_buf, opt);
1742 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
1743 // When using regexp, braces are hacked already by escape_for_regex()
1744 par_as_string = normalize(ds, !use_regexp);
1746 close_wildcards = 0;
1748 size_t lead_size = 0;
1749 // correct the language settings
1750 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
1751 if (opt.ignoreformat) {
1753 // if par_as_string_nolead were emty,
1754 // the following call to findAux will always *find* the string
1755 // in the checked data, and thus always using the slow
1756 // examining of the current text part.
1757 par_as_string_nolead = par_as_string;
1760 lead_size = identifyLeading(par_as_string);
1761 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
1762 lead_as_string = par_as_string.substr(0, lead_size);
1763 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
1767 open_braces = identifyClosing(par_as_string);
1768 identifyClosing(par_as_string_nolead);
1769 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1770 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
1772 string lead_as_regexp;
1773 if (lead_size > 0) {
1774 // @todo No need to search for \regexp{} insets in leading material
1775 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
1776 par_as_string = par_as_string_nolead;
1777 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
1778 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1780 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
1781 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
1782 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1784 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
1785 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
1786 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
1787 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
1788 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
1789 || regex_replace(par_as_string, par_as_string,
1790 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
1791 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
1792 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
1796 if (!opt.ignoreformat) {
1797 // Remove extra '\}' at end
1798 while ( regex_replace(par_as_string, par_as_string, "(.*)\\\\}$", "$1")) {
1802 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
1803 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
1804 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
1805 // replace '[^...]' with '[^...\}\{\\]'
1806 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
1807 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
1808 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
1810 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
1812 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
1813 LYXERR(Debug::FIND, "Open braces: " << open_braces);
1814 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
1815 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
1817 // If entered regexp must match at begin of searched string buffer
1818 // Kornel: Added parentheses to use $1 for size of the leading string
1822 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
1823 // Unfortunately is '\1', '\2', etc not working for strings with extra format
1824 // so the convert has no effect in that case
1825 for (int i = 8; i > 0; --i) {
1826 string orig = "\\\\" + std::to_string(i);
1827 string dest = "\\" + std::to_string(i+1);
1828 while (regex_replace(par_as_string, par_as_string, orig, dest));
1830 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
1831 regexp2_str = "(" + lead_as_regexp + ").*" + par_as_string;
1833 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
1834 regexp = lyx::regex(regexp_str);
1836 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
1837 regexp2 = lyx::regex(regexp2_str);
1842 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
1845 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
1848 docstring docstr = stringifyFromForSearch(opt, cur, len);
1849 string str = normalize(docstr, true);
1850 if (!opt.ignoreformat) {
1851 str = correctlanguagesetting(str, false, !opt.ignoreformat);
1853 if (str.empty()) return(-1);
1854 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
1855 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
1858 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
1859 regex const *p_regexp;
1860 regex_constants::match_flag_type flags;
1862 flags = regex_constants::match_continuous;
1865 flags = regex_constants::match_default;
1866 p_regexp = ®exp2;
1868 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
1869 if (re_it == sregex_iterator())
1871 match_results<string::const_iterator> const & m = *re_it;
1873 if (0) { // Kornel Benko: DO NOT CHECKK
1874 // Check braces on the segment that matched the entire regexp expression,
1875 // plus the last subexpression, if a (.*?) was inserted in the constructor.
1876 if (!braces_match(m[0].first, m[0].second, open_braces))
1880 // Check braces on segments that matched all (.*?) subexpressions,
1881 // except the last "padding" one inserted by lyx.
1882 for (size_t i = 1; i < m.size() - 1; ++i)
1883 if (!braces_match(m[i].first, m[i].second, open_braces))
1886 // Exclude from the returned match length any length
1887 // due to close wildcards added at end of regexp
1888 // and also the length of the leading (e.g. '\emph{')
1890 // Whole found string, including the leading: m[0].second - m[0].first
1891 // Size of the leading string: m[1].second - m[1].first
1892 int leadingsize = 0;
1894 leadingsize = m[1].second - m[1].first;
1896 for (size_t i = 0; i < m.size(); i++) {
1897 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
1899 if (close_wildcards == 0)
1900 result = m[0].second - m[0].first;
1903 result = m[m.size() - close_wildcards].first - m[0].first;
1905 if (result > leadingsize)
1906 result -= leadingsize;
1912 // else !use_regexp: but all code paths above return
1913 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1914 << par_as_string << "', str='" << str << "'");
1915 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1916 << lead_as_string << "', par_as_string_nolead='"
1917 << par_as_string_nolead << "'");
1920 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1921 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1922 if (str.substr(0, par_as_string.size()) == par_as_string)
1923 return par_as_string.size();
1925 size_t pos = str.find(par_as_string_nolead);
1926 if (pos != string::npos)
1927 return par_as_string.size();
1933 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1935 int res = findAux(cur, len, at_begin);
1937 "res=" << res << ", at_begin=" << at_begin
1938 << ", matchword=" << opt.matchword
1939 << ", inTexted=" << cur.inTexted());
1940 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1942 Paragraph const & par = cur.paragraph();
1943 bool ws_left = (cur.pos() > 0)
1944 ? par.isWordSeparator(cur.pos() - 1)
1946 bool ws_right = (cur.pos() + res < par.size())
1947 ? par.isWordSeparator(cur.pos() + res)
1950 "cur.pos()=" << cur.pos() << ", res=" << res
1951 << ", separ: " << ws_left << ", " << ws_right
1953 if (ws_left && ws_right)
1959 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1962 if (! opt.casesensitive)
1963 t = lyx::to_utf8(lowercase(s));
1965 t = lyx::to_utf8(s);
1966 // Remove \n at begin
1967 while (!t.empty() && t[0] == '\n')
1970 while (!t.empty() && t[t.size() - 1] == '\n')
1971 t = t.substr(0, t.size() - 1);
1973 // Replace all other \n with spaces
1974 while ((pos = t.find("\n")) != string::npos)
1975 t.replace(pos, 1, " ");
1976 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1977 // Kornel: Added textsl, textsf, textit, texttt and noun
1978 // + allow to seach for colored text too
1979 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1980 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
1981 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1982 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
1983 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1985 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor)\\{[a-z]+\\}(\\{(\\\\item |\\{\\})?\\})+", ""));
1986 // FIXME - check what preceeds the brace
1988 if (opt.ignoreformat)
1989 while (regex_replace(t, t, "\\{", "_x_<")
1990 || regex_replace(t, t, "\\}", "_x_>"))
1991 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1993 while (regex_replace(t, t, "\\\\\\{", "_x_<")
1994 || regex_replace(t, t, "\\\\\\}", "_x_>"))
1995 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
2002 docstring stringifyFromCursor(DocIterator const & cur, int len)
2004 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
2005 if (cur.inTexted()) {
2006 Paragraph const & par = cur.paragraph();
2007 // TODO what about searching beyond/across paragraph breaks ?
2008 // TODO Try adding a AS_STR_INSERTS as last arg
2009 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
2010 int(par.size()) : cur.pos() + len;
2011 OutputParams runparams(&cur.buffer()->params().encoding());
2012 runparams.nice = true;
2013 runparams.flavor = OutputParams::LATEX;
2014 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
2015 // No side effect of file copying and image conversion
2016 runparams.dryrun = true;
2017 LYXERR(Debug::FIND, "Stringifying with cur: "
2018 << cur << ", from pos: " << cur.pos() << ", end: " << end);
2019 return par.asString(cur.pos(), end,
2020 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
2022 } else if (cur.inMathed()) {
2024 CursorSlice cs = cur.top();
2025 MathData md = cs.cell();
2026 MathData::const_iterator it_end =
2027 (( len == -1 || cs.pos() + len > int(md.size()))
2029 : md.begin() + cs.pos() + len );
2030 for (MathData::const_iterator it = md.begin() + cs.pos();
2032 s = s + asString(*it);
2033 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
2036 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2041 /** Computes the LaTeX export of buf starting from cur and ending len positions
2042 * after cur, if len is positive, or at the paragraph or innermost inset end
2045 docstring latexifyFromCursor(DocIterator const & cur, int len)
2047 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
2048 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
2049 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
2050 Buffer const & buf = *cur.buffer();
2052 odocstringstream ods;
2054 OutputParams runparams(&buf.params().encoding());
2055 runparams.nice = false;
2056 runparams.flavor = OutputParams::LATEX;
2057 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2058 // No side effect of file copying and image conversion
2059 runparams.dryrun = true;
2060 runparams.for_search = true;
2062 if (cur.inTexted()) {
2063 // @TODO what about searching beyond/across paragraph breaks ?
2064 pos_type endpos = cur.paragraph().size();
2065 if (len != -1 && endpos > cur.pos() + len)
2066 endpos = cur.pos() + len;
2067 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
2068 string(), cur.pos(), endpos);
2069 string s = lyx::to_utf8(ods.str());
2070 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
2071 return(lyx::from_utf8(s));
2072 } else if (cur.inMathed()) {
2073 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
2074 for (int s = cur.depth() - 1; s >= 0; --s) {
2075 CursorSlice const & cs = cur[s];
2076 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
2078 cs.asInsetMath()->asHullInset()->header_write(ws);
2083 CursorSlice const & cs = cur.top();
2084 MathData md = cs.cell();
2085 MathData::const_iterator it_end =
2086 ((len == -1 || cs.pos() + len > int(md.size()))
2088 : md.begin() + cs.pos() + len);
2089 for (MathData::const_iterator it = md.begin() + cs.pos();
2091 ods << asString(*it);
2093 // Retrieve the math environment type, and add '$' or '$]'
2094 // or others (\end{equation}) accordingly
2095 for (int s = cur.depth() - 1; s >= 0; --s) {
2096 CursorSlice const & cs2 = cur[s];
2097 InsetMath * inset = cs2.asInsetMath();
2098 if (inset && inset->asHullInset()) {
2100 inset->asHullInset()->footer_write(ws);
2104 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
2106 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
2112 /** Finalize an advanced find operation, advancing the cursor to the innermost
2113 ** position that matches, plus computing the length of the matching text to
2116 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
2118 // Search the foremost position that matches (avoids find of entire math
2119 // inset when match at start of it)
2121 DocIterator old_cur(cur.buffer());
2123 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
2127 } while (cur && cur.depth() > d && match(cur) > 0);
2129 if (match(cur) <= 0) return 0;
2130 LYXERR(Debug::FIND, "Ok");
2132 // Compute the match length
2134 if (cur.pos() + len > cur.lastpos())
2136 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2137 while (cur.pos() + len <= cur.lastpos() && match(cur, len) <= 0) {
2139 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
2141 // Length of matched text (different from len param)
2142 int old_len = match(cur, len);
2143 if (old_len < 0) old_len = 0;
2145 // Greedy behaviour while matching regexps
2146 while ((new_len = match(cur, len + 1)) > old_len) {
2149 LYXERR(Debug::FIND, "verifying match with len = " << len);
2156 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
2160 while (!theApp()->longOperationCancelled() && cur) {
2161 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
2162 int match_len = match(cur, -1, false);
2163 LYXERR(Debug::FIND, "match_len: " << match_len);
2164 if (match_len > 0) {
2165 int match_len_zero_count = 0;
2166 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
2167 LYXERR(Debug::FIND, "Advancing cur: " << cur);
2168 int match_len2 = match(cur);
2169 LYXERR(Debug::FIND, "match_len2: " << match_len2);
2170 if (match_len2 > 0) {
2171 // Sometimes in finalize we understand it wasn't a match
2172 // and we need to continue the outest loop
2173 int len = findAdvFinalize(cur, match);
2178 if (match_len2 >= 0) {
2179 if (match_len2 == 0)
2180 match_len_zero_count++;
2182 match_len_zero_count = 0;
2185 if (++match_len_zero_count > 3) {
2186 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
2187 match_len_zero_count = 0;
2195 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
2196 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
2199 // This should exit nested insets, if any, or otherwise undefine the currsor.
2200 cur.pos() = cur.lastpos();
2201 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
2209 /// Find the most backward consecutive match within same paragraph while searching backwards.
2210 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
2212 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2213 DocIterator tmp_cur = cur;
2214 int len = findAdvFinalize(tmp_cur, match);
2215 Inset & inset = cur.inset();
2216 for (; cur != cur_begin; cur.backwardPos()) {
2217 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
2218 DocIterator new_cur = cur;
2219 new_cur.backwardPos();
2220 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
2222 int new_len = findAdvFinalize(new_cur, match);
2227 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
2233 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
2237 // Backup of original position
2238 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
2239 if (cur == cur_begin)
2242 DocIterator cur_orig(cur);
2243 bool pit_changed = false;
2246 bool found_match = match(cur, -1, false);
2250 cur.pos() = cur.lastpos();
2252 cur.pos() = cur_orig.pos();
2253 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
2254 DocIterator cur_prev_iter;
2256 found_match = match(cur);
2257 LYXERR(Debug::FIND, "findBackAdv3: found_match="
2258 << found_match << ", cur: " << cur);
2260 return findMostBackwards(cur, match);
2262 // Stop if begin of document reached
2263 if (cur == cur_begin)
2265 cur_prev_iter = cur;
2269 if (cur == cur_begin)
2276 } while (!theApp()->longOperationCancelled());
2284 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
2285 DocIterator const & cur, int len)
2287 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
2289 if (!opt.ignoreformat)
2290 return latexifyFromCursor(cur, len);
2292 return stringifyFromCursor(cur, len);
2296 FindAndReplaceOptions::FindAndReplaceOptions(
2297 docstring const & find_buf_name, bool casesensitive,
2298 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
2299 docstring const & repl_buf_name, bool keep_case,
2300 SearchScope scope, SearchRestriction restr)
2301 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
2302 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
2303 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
2311 /** Check if 'len' letters following cursor are all non-lowercase */
2312 static bool allNonLowercase(Cursor const & cur, int len)
2314 pos_type beg_pos = cur.selectionBegin().pos();
2315 pos_type end_pos = cur.selectionBegin().pos() + len;
2316 if (len > cur.lastpos() + 1 - beg_pos) {
2317 LYXERR(Debug::FIND, "This should not happen, more debug needed");
2318 len = cur.lastpos() + 1 - beg_pos;
2319 end_pos = beg_pos + len;
2321 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
2322 if (isLowerCase(cur.paragraph().getChar(pos)))
2328 /** Check if first letter is upper case and second one is lower case */
2329 static bool firstUppercase(Cursor const & cur)
2332 pos_type pos = cur.selectionBegin().pos();
2333 if (pos >= cur.lastpos() - 1) {
2334 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
2337 ch1 = cur.paragraph().getChar(pos);
2338 ch2 = cur.paragraph().getChar(pos + 1);
2339 bool result = isUpperCase(ch1) && isLowerCase(ch2);
2340 LYXERR(Debug::FIND, "firstUppercase(): "
2341 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
2342 << ch2 << "(" << char(ch2) << ")"
2343 << ", result=" << result << ", cur=" << cur);
2348 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
2350 ** \fixme What to do with possible further paragraphs in replace buffer ?
2352 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
2354 ParagraphList::iterator pit = buffer.paragraphs().begin();
2355 LASSERT(pit->size() >= 1, /**/);
2356 pos_type right = pos_type(1);
2357 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
2358 right = pit->size();
2359 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
2365 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
2367 Cursor & cur = bv->cursor();
2368 if (opt.repl_buf_name == docstring()
2369 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
2370 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2373 DocIterator sel_beg = cur.selectionBegin();
2374 DocIterator sel_end = cur.selectionEnd();
2375 if (&sel_beg.inset() != &sel_end.inset()
2376 || sel_beg.pit() != sel_end.pit()
2377 || sel_beg.idx() != sel_end.idx())
2379 int sel_len = sel_end.pos() - sel_beg.pos();
2380 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
2381 << ", sel_len: " << sel_len << endl);
2384 LASSERT(sel_len > 0, return);
2386 if (!matchAdv(sel_beg, sel_len))
2389 // Build a copy of the replace buffer, adapted to the KeepCase option
2390 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
2392 repl_buffer_orig.write(oss);
2393 string lyx = oss.str();
2394 Buffer repl_buffer("", false);
2395 repl_buffer.setUnnamed(true);
2396 LASSERT(repl_buffer.readString(lyx), return);
2397 if (opt.keep_case && sel_len >= 2) {
2398 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
2399 if (cur.inTexted()) {
2400 if (firstUppercase(cur))
2401 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
2402 else if (allNonLowercase(cur, sel_len))
2403 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
2406 cap::cutSelection(cur, false);
2407 if (cur.inTexted()) {
2408 repl_buffer.changeLanguage(
2409 repl_buffer.language(),
2410 cur.getFont().language());
2411 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
2412 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
2413 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
2414 repl_buffer.params().documentClassPtr(),
2415 bv->buffer().errorList("Paste"));
2416 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
2417 sel_len = repl_buffer.paragraphs().begin()->size();
2418 } else if (cur.inMathed()) {
2419 odocstringstream ods;
2421 OutputParams runparams(&repl_buffer.params().encoding());
2422 runparams.nice = false;
2423 runparams.flavor = OutputParams::LATEX;
2424 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
2425 runparams.dryrun = true;
2426 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
2427 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
2428 docstring repl_latex = ods.str();
2429 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
2431 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
2432 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
2433 repl_latex = from_utf8(s);
2434 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
2435 MathData ar(cur.buffer());
2436 asArray(repl_latex, ar, Parse::NORMAL);
2438 sel_len = ar.size();
2439 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2441 if (cur.pos() >= sel_len)
2442 cur.pos() -= sel_len;
2445 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
2446 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
2447 bv->processUpdateFlags(Update::Force);
2451 /// Perform a FindAdv operation.
2452 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
2457 // e.g., when invoking word-findadv from mini-buffer wither with
2458 // wrong options syntax or before ever opening advanced F&R pane
2459 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
2463 MatchStringAdv matchAdv(bv->buffer(), opt);
2464 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
2466 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
2467 findAdvReplace(bv, opt, matchAdv);
2470 match_len = findForwardAdv(cur, matchAdv);
2472 match_len = findBackwardsAdv(cur, matchAdv);
2474 // This may only be raised by lyx::regex()
2475 bv->message(_("Invalid regular expression!"));
2479 if (match_len == 0) {
2480 bv->message(_("Match not found!"));
2484 bv->message(_("Match found!"));
2486 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
2487 bv->putSelectionAt(cur, match_len, !opt.forward);
2493 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
2495 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
2496 << opt.casesensitive << ' '
2497 << opt.matchword << ' '
2498 << opt.forward << ' '
2499 << opt.expandmacros << ' '
2500 << opt.ignoreformat << ' '
2501 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
2502 << opt.keep_case << ' '
2503 << int(opt.scope) << ' '
2506 LYXERR(Debug::FIND, "built: " << os.str());
2512 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
2514 LYXERR(Debug::FIND, "parsing");
2518 while (line != "EOSS") {
2522 if (is.eof()) // Tolerate malformed request
2526 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
2527 opt.find_buf_name = from_utf8(s);
2528 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
2529 is.get(); // Waste space before replace string
2532 while (line != "EOSS") {
2536 if (is.eof()) // Tolerate malformed request
2540 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
2541 opt.repl_buf_name = from_utf8(s);
2542 is >> opt.keep_case;
2545 opt.scope = FindAndReplaceOptions::SearchScope(i);
2547 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
2549 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
2550 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
2551 << opt.scope << ' ' << opt.restr);