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"
57 using namespace lyx::support;
63 bool parse_bool(docstring & howto)
68 howto = split(howto, var, ' ');
73 class MatchString : public binary_function<Paragraph, pos_type, int>
76 MatchString(docstring const & str, bool cs, bool mw)
77 : str(str), case_sens(cs), whole_words(mw)
80 // returns true if the specified string is at the specified position
81 // del specifies whether deleted strings in ct mode will be considered
82 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
84 return par.find(str, case_sens, whole_words, pos, del);
92 // match whole words only
97 int findForward(DocIterator & cur, MatchString const & match,
100 for (; cur; cur.forwardChar())
101 if (cur.inTexted()) {
102 int len = match(cur.paragraph(), cur.pos(), find_del);
110 int findBackwards(DocIterator & cur, MatchString const & match,
111 bool find_del = true)
115 if (cur.inTexted()) {
116 int len = match(cur.paragraph(), cur.pos(), find_del);
125 bool searchAllowed(docstring const & str)
128 frontend::Alert::error(_("Search error"), _("Search string is empty"));
135 bool findOne(BufferView * bv, docstring const & searchstr,
136 bool case_sens, bool whole, bool forward,
137 bool find_del = true, bool check_wrap = false)
139 if (!searchAllowed(searchstr))
142 DocIterator cur = forward
143 ? bv->cursor().selectionEnd()
144 : bv->cursor().selectionBegin();
146 MatchString const match(searchstr, case_sens, whole);
148 int match_len = forward
149 ? findForward(cur, match, find_del)
150 : findBackwards(cur, match, find_del);
153 bv->putSelectionAt(cur, match_len, !forward);
154 else if (check_wrap) {
155 DocIterator cur_orig(bv->cursor());
158 q = _("End of file reached while searching forward.\n"
159 "Continue searching from the beginning?");
161 q = _("Beginning of file reached while searching backward.\n"
162 "Continue searching from the end?");
163 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
164 q, 0, 1, _("&Yes"), _("&No"));
165 if (wrap_answer == 0) {
167 bv->cursor().clear();
168 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
170 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
171 bv->cursor().backwardPos();
173 bv->clearSelection();
174 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
177 bv->cursor().setCursor(cur_orig);
181 return match_len > 0;
185 int replaceAll(BufferView * bv,
186 docstring const & searchstr, docstring const & replacestr,
187 bool case_sens, bool whole)
189 Buffer & buf = bv->buffer();
191 if (!searchAllowed(searchstr) || buf.isReadonly())
194 DocIterator cur_orig(bv->cursor());
196 MatchString const match(searchstr, case_sens, whole);
199 int const rsize = replacestr.size();
200 int const ssize = searchstr.size();
203 cur.setCursor(doc_iterator_begin(&buf));
204 int match_len = findForward(cur, match, false);
205 while (match_len > 0) {
206 // Backup current cursor position and font.
207 pos_type const pos = cur.pos();
208 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
210 int striked = ssize -
211 cur.paragraph().eraseChars(pos, pos + match_len,
212 buf.params().track_changes);
213 cur.paragraph().insert(pos, replacestr, font,
214 Change(buf.params().track_changes
216 : Change::UNCHANGED));
217 for (int i = 0; i < rsize + striked; ++i)
220 match_len = findForward(cur, match, false);
223 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
225 cur_orig.fixIfBroken();
226 bv->setCursor(cur_orig);
232 // the idea here is that we are going to replace the string that
233 // is selected IF it is the search string.
234 // if there is a selection, but it is not the search string, then
235 // we basically ignore it. (FIXME We ought to replace only within
237 // if there is no selection, then:
238 // (i) if some search string has been provided, then we find it.
239 // (think of how the dialog works when you hit "replace" the
241 // (ii) if no search string has been provided, then we treat the
242 // word the cursor is in as the search string. (why? i have no
243 // idea.) but this only works in text?
245 // returns the number of replacements made (one, if any) and
246 // whether anything at all was done.
247 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
248 docstring const & replacestr, bool case_sens,
249 bool whole, bool forward, bool findnext)
251 Cursor & cur = bv->cursor();
253 if (!cur.selection()) {
254 // no selection, non-empty search string: find it
255 if (!searchstr.empty()) {
256 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
257 return make_pair(found, 0);
259 // empty search string
262 return make_pair(false, 0);
263 // select current word and treat it as the search string.
264 // This causes a minor bug as undo will restore this selection,
265 // which the user did not create (#8986).
266 cur.innerText()->selectWord(cur, WHOLE_WORD);
267 searchstr = cur.selectionAsString(false);
270 // if we still don't have a search string, report the error
272 if (!searchAllowed(searchstr))
273 return make_pair(false, 0);
275 bool have_selection = cur.selection();
276 docstring const selected = cur.selectionAsString(false);
279 ? searchstr == selected
280 : compare_no_case(searchstr, selected) == 0;
282 // no selection or current selection is not search word:
283 // just find the search word
284 if (!have_selection || !match) {
285 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
286 return make_pair(found, 0);
289 // we're now actually ready to replace. if the buffer is
290 // read-only, we can't, though.
291 if (bv->buffer().isReadonly())
292 return make_pair(false, 0);
294 cap::replaceSelectionWithString(cur, replacestr);
296 cur.pos() += replacestr.length();
297 LASSERT(cur.pos() <= cur.lastpos(),
298 cur.pos() = cur.lastpos());
301 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
303 return make_pair(true, 1);
309 docstring const find2string(docstring const & search,
310 bool casesensitive, bool matchword, bool forward)
314 << int(casesensitive) << ' '
315 << int(matchword) << ' '
321 docstring const replace2string(docstring const & replace,
322 docstring const & search,
323 bool casesensitive, bool matchword,
324 bool all, bool forward, bool findnext)
327 ss << replace << '\n'
329 << int(casesensitive) << ' '
330 << int(matchword) << ' '
332 << int(forward) << ' '
338 bool lyxfind(BufferView * bv, FuncRequest const & ev)
340 if (!bv || ev.action() != LFUN_WORD_FIND)
343 //lyxerr << "find called, cmd: " << ev << endl;
345 // data is of the form
347 // <casesensitive> <matchword> <forward>"
349 docstring howto = split(ev.argument(), search, '\n');
351 bool casesensitive = parse_bool(howto);
352 bool matchword = parse_bool(howto);
353 bool forward = parse_bool(howto);
355 return findOne(bv, search, casesensitive, matchword, forward, true, true);
359 bool lyxreplace(BufferView * bv,
360 FuncRequest const & ev, bool has_deleted)
362 if (!bv || ev.action() != LFUN_WORD_REPLACE)
365 // data is of the form
368 // <casesensitive> <matchword> <all> <forward> <findnext>"
371 docstring howto = split(ev.argument(), rplc, '\n');
372 howto = split(howto, search, '\n');
374 bool casesensitive = parse_bool(howto);
375 bool matchword = parse_bool(howto);
376 bool all = parse_bool(howto);
377 bool forward = parse_bool(howto);
378 bool findnext = howto.empty() ? true : parse_bool(howto);
383 int replace_count = 0;
385 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
386 update = replace_count > 0;
389 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
391 replace_count = rv.second;
394 Buffer const & buf = bv->buffer();
396 // emit message signal.
397 buf.message(_("String not found."));
399 if (replace_count == 0) {
400 buf.message(_("String found."));
401 } else if (replace_count == 1) {
402 buf.message(_("String has been replaced."));
404 docstring const str =
405 bformat(_("%1$d strings have been replaced."), replace_count);
409 } else if (findnext) {
410 // if we have deleted characters, we do not replace at all, but
411 // rather search for the next occurence
412 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
415 bv->message(_("String not found."));
421 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
423 for (; cur; cur.forwardPos())
424 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
428 DocIterator cur_orig(bv->cursor());
429 docstring q = _("End of file reached while searching forward.\n"
430 "Continue searching from the beginning?");
431 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
432 q, 0, 1, _("&Yes"), _("&No"));
433 if (wrap_answer == 0) {
434 bv->cursor().clear();
435 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
436 bv->clearSelection();
437 cur.setCursor(bv->cursor().selectionBegin());
438 if (findNextChange(bv, cur, false))
441 bv->cursor().setCursor(cur_orig);
448 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
450 for (cur.backwardPos(); cur; cur.backwardPos()) {
451 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
456 DocIterator cur_orig(bv->cursor());
457 docstring q = _("Beginning of file reached while searching backward.\n"
458 "Continue searching from the end?");
459 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
460 q, 0, 1, _("&Yes"), _("&No"));
461 if (wrap_answer == 0) {
462 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
463 bv->cursor().backwardPos();
464 bv->clearSelection();
465 cur.setCursor(bv->cursor().selectionBegin());
466 if (findPreviousChange(bv, cur, false))
469 bv->cursor().setCursor(cur_orig);
476 bool selectChange(Cursor & cur, bool forward)
478 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
480 Change ch = cur.paragraph().lookupChange(cur.pos());
482 CursorSlice tip1 = cur.top();
483 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
484 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
485 if (!ch2.isSimilarTo(ch))
488 CursorSlice tip2 = cur.top();
489 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
491 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
492 if (!ch2.isSimilarTo(ch)) {
493 // take a step forward to correctly set the selection
501 cur.bv().mouseSetCursor(cur, false);
503 cur.bv().mouseSetCursor(cur, true);
511 bool findChange(BufferView * bv, bool forward)
514 cur.setCursor(forward ? bv->cursor().selectionEnd()
515 : bv->cursor().selectionBegin());
516 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
517 return selectChange(cur, forward);
522 bool findNextChange(BufferView * bv)
524 return findChange(bv, true);
528 bool findPreviousChange(BufferView * bv)
530 return findChange(bv, false);
537 typedef vector<pair<string, string> > Escapes;
539 /// A map of symbols and their escaped equivalent needed within a regex.
540 /// @note Beware of order
541 Escapes const & get_regexp_escapes()
543 typedef std::pair<std::string, std::string> P;
545 static Escapes escape_map;
546 if (escape_map.empty()) {
547 escape_map.push_back(P("$", "_x_$"));
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("\\", "(?:\\\\|\\\\backslash)"));
558 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
559 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
560 escape_map.push_back(P("_x_", "\\"));
565 /// A map of lyx escaped strings and their unescaped equivalent.
566 Escapes const & get_lyx_unescapes()
568 typedef std::pair<std::string, std::string> P;
570 static Escapes escape_map;
571 if (escape_map.empty()) {
572 escape_map.push_back(P("\\%", "%"));
573 escape_map.push_back(P("\\mathcircumflex ", "^"));
574 escape_map.push_back(P("\\mathcircumflex", "^"));
575 escape_map.push_back(P("\\backslash ", "\\"));
576 escape_map.push_back(P("\\backslash", "\\"));
577 escape_map.push_back(P("\\\\{", "_x_<"));
578 escape_map.push_back(P("\\\\}", "_x_>"));
579 escape_map.push_back(P("\\sim ", "~"));
580 escape_map.push_back(P("\\sim", "~"));
585 /// A map of escapes turning a regexp matching text to one matching latex.
586 Escapes const & get_regexp_latex_escapes()
588 typedef std::pair<std::string, std::string> P;
590 static Escapes escape_map;
591 if (escape_map.empty()) {
592 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
593 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
594 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
595 escape_map.push_back(P("\\[", "\\{\\[\\}"));
596 escape_map.push_back(P("\\]", "\\{\\]\\}"));
597 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
598 escape_map.push_back(P("%", "\\\\\\%"));
603 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
604 ** the found occurrence were escaped.
606 string apply_escapes(string s, Escapes const & escape_map)
608 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
609 Escapes::const_iterator it;
610 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
611 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
612 unsigned int pos = 0;
613 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
614 s.replace(pos, it->first.length(), it->second);
615 LYXERR(Debug::FIND, "After escape: " << s);
616 pos += it->second.length();
617 // LYXERR(Debug::FIND, "pos: " << pos);
620 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
625 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
626 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
627 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
628 string escape_for_regex(string s, bool match_latex)
631 while (pos < s.size()) {
632 size_t new_pos = s.find("\\regexp{", pos);
633 if (new_pos == string::npos)
635 LYXERR(Debug::FIND, "new_pos: " << new_pos);
636 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
637 LYXERR(Debug::FIND, "t [lyx]: " << t);
638 t = apply_escapes(t, get_regexp_escapes());
639 LYXERR(Debug::FIND, "t [rxp]: " << t);
640 s.replace(pos, new_pos - pos, t);
641 new_pos = pos + t.size();
642 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
643 LYXERR(Debug::FIND, "new_pos: " << new_pos);
644 if (new_pos == s.size())
646 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
647 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
648 LYXERR(Debug::FIND, "end_pos: " << end_pos);
649 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
650 LYXERR(Debug::FIND, "t in regexp : " << t);
651 t = apply_escapes(t, get_lyx_unescapes());
652 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
654 t = apply_escapes(t, get_regexp_latex_escapes());
655 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
657 if (end_pos == s.size()) {
658 s.replace(new_pos, end_pos - new_pos, t);
659 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
662 s.replace(new_pos, end_pos + 13 - new_pos, t);
663 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
664 pos = new_pos + t.size();
665 LYXERR(Debug::FIND, "pos: " << pos);
671 /// Wrapper for lyx::regex_replace with simpler interface
672 bool regex_replace(string const & s, string & t, string const & searchstr,
673 string const & replacestr)
675 lyx::regex e(searchstr, regex_constants::ECMAScript);
677 ostream_iterator<char, char> it(oss);
678 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
679 // tolerate t and s be references to the same variable
680 bool rv = (s != oss.str());
686 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
688 ** Verify that closed braces exactly match open braces. This avoids that, for example,
689 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
692 ** Number of open braces that must remain open at the end for the verification to succeed.
694 bool braces_match(string::const_iterator const & beg,
695 string::const_iterator const & end,
699 string::const_iterator it = beg;
700 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
701 for (; it != end; ++it) {
702 // Skip escaped braces in the count
707 } else if (*it == '{') {
709 } else if (*it == '}') {
710 if (open_pars == 0) {
711 LYXERR(Debug::FIND, "Found unmatched closed brace");
717 if (open_pars != unmatched) {
718 LYXERR(Debug::FIND, "Found " << open_pars
719 << " instead of " << unmatched
720 << " unmatched open braces at the end of count");
723 LYXERR(Debug::FIND, "Braces match as expected");
728 /** The class performing a match between a position in the document and the FindAdvOptions.
730 class MatchStringAdv {
732 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
734 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
735 ** constructor as opt.search, under the opt.* options settings.
738 ** If set, then match is searched only against beginning of text starting at cur.
739 ** If unset, then match is searched anywhere in text starting at cur.
742 ** The length of the matching text, or zero if no match was found.
744 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
749 /// first buffer on which search was started
750 lyx::Buffer * const p_first_buf;
752 FindAndReplaceOptions const & opt;
755 /// Auxiliary find method (does not account for opt.matchword)
756 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
758 /** Normalize a stringified or latexified LyX paragraph.
762 ** <li>if search is not casesensitive, then lowercase the string;
763 ** <li>remove any newline at begin or end of the string;
764 ** <li>replace any newline in the middle of the string with a simple space;
765 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
768 ** @todo Normalization should also expand macros, if the corresponding
769 ** search option was checked.
771 string normalize(docstring const & s, bool hack_braces) const;
772 // normalized string to search
773 string par_as_string;
774 // regular expression to use for searching
776 // same as regexp, but prefixed with a ".*"
778 // leading format material as string
779 string lead_as_string;
780 // par_as_string after removal of lead_as_string
781 string par_as_string_nolead;
782 // unmatched open braces in the search string/regexp
784 // number of (.*?) subexpressions added at end of search regexp for closing
785 // environments, math mode, styles, etc...
787 // Are we searching with regular expressions ?
792 static docstring buffer_to_latex(Buffer & buffer)
794 OutputParams runparams(&buffer.params().encoding());
795 odocstringstream ods;
797 runparams.nice = true;
798 runparams.flavor = OutputParams::LATEX;
799 runparams.linelen = 80; //lyxrc.plaintext_linelen;
800 // No side effect of file copying and image conversion
801 runparams.dryrun = true;
802 pit_type const endpit = buffer.paragraphs().size();
803 for (pit_type pit = 0; pit != endpit; ++pit) {
804 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
805 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
811 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
814 if (!opt.ignoreformat) {
815 str = buffer_to_latex(buffer);
817 OutputParams runparams(&buffer.params().encoding());
818 runparams.nice = true;
819 runparams.flavor = OutputParams::LATEX;
820 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
821 runparams.dryrun = true;
822 runparams.for_search = true;
823 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
824 Paragraph const & par = buffer.paragraphs().at(pit);
825 LYXERR(Debug::FIND, "Adding to search string: '"
826 << par.asString(pos_type(0), par.size(),
827 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
830 str += par.asString(pos_type(0), par.size(),
831 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
839 /// Return separation pos between the leading material and the rest
840 static size_t identifyLeading(string const & s)
843 // @TODO Support \item[text]
844 while (regex_replace(t, t, REGEX_BOS "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
845 || regex_replace(t, t, REGEX_BOS "\\$", "")
846 || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
847 || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
848 || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
849 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
854 // Remove trailing closure of math, macros and environments, so to catch parts of them.
855 static int identifyClosing(string & t)
859 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
860 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
862 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
864 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
866 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
876 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
877 : p_buf(&buf), p_first_buf(&buf), opt(opt)
879 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
880 docstring const & ds = stringifySearchBuffer(find_buf, opt);
881 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
882 // When using regexp, braces are hacked already by escape_for_regex()
883 par_as_string = normalize(ds, !use_regexp);
887 size_t lead_size = 0;
888 if (opt.ignoreformat) {
890 // if par_as_string_nolead were emty,
891 // the following call to findAux will always *find* the string
892 // in the checked data, and thus always using the slow
893 // examining of the current text part.
894 par_as_string_nolead = par_as_string;
897 lead_size = identifyLeading(par_as_string);
898 lead_as_string = par_as_string.substr(0, lead_size);
899 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
903 open_braces = identifyClosing(par_as_string);
904 identifyClosing(par_as_string_nolead);
905 LYXERR(Debug::FIND, "Open braces: " << open_braces);
906 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
908 string lead_as_regexp;
910 // @todo No need to search for \regexp{} insets in leading material
911 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
912 par_as_string = par_as_string_nolead;
913 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
914 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
916 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
917 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
918 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
920 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
921 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
922 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
923 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
924 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
925 || regex_replace(par_as_string, par_as_string,
926 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
927 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
928 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
932 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
933 LYXERR(Debug::FIND, "Open braces: " << open_braces);
934 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
935 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
937 // If entered regexp must match at begin of searched string buffer
938 string regexp_str = lead_as_regexp + par_as_string;
939 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
940 regexp = lyx::regex(regexp_str);
942 // If entered regexp may match wherever in searched string buffer
943 string regexp2_str = lead_as_regexp + ".*" + par_as_string;
944 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
945 regexp2 = lyx::regex(regexp2_str);
950 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
953 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
956 docstring docstr = stringifyFromForSearch(opt, cur, len);
957 string str = normalize(docstr, true);
958 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
959 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
962 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
963 regex const *p_regexp;
964 regex_constants::match_flag_type flags;
966 flags = regex_constants::match_continuous;
969 flags = regex_constants::match_default;
972 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
973 if (re_it == sregex_iterator())
975 match_results<string::const_iterator> const & m = *re_it;
977 // Check braces on the segment that matched the entire regexp expression,
978 // plus the last subexpression, if a (.*?) was inserted in the constructor.
979 if (!braces_match(m[0].first, m[0].second, open_braces))
982 // Check braces on segments that matched all (.*?) subexpressions,
983 // except the last "padding" one inserted by lyx.
984 for (size_t i = 1; i < m.size() - 1; ++i)
985 if (!braces_match(m[i].first, m[i].second))
988 // Exclude from the returned match length any length
989 // due to close wildcards added at end of regexp
990 if (close_wildcards == 0)
991 return m[0].second - m[0].first;
993 return m[m.size() - close_wildcards].first - m[0].first;
996 // else !use_regexp: but all code paths above return
997 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
998 << par_as_string << "', str='" << str << "'");
999 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1000 << lead_as_string << "', par_as_string_nolead='"
1001 << par_as_string_nolead << "'");
1004 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1005 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1006 if (str.substr(0, par_as_string.size()) == par_as_string)
1007 return par_as_string.size();
1009 size_t pos = str.find(par_as_string_nolead);
1010 if (pos != string::npos)
1011 return par_as_string.size();
1017 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1019 int res = findAux(cur, len, at_begin);
1021 "res=" << res << ", at_begin=" << at_begin
1022 << ", matchword=" << opt.matchword
1023 << ", inTexted=" << cur.inTexted());
1024 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1026 Paragraph const & par = cur.paragraph();
1027 bool ws_left = (cur.pos() > 0)
1028 ? par.isWordSeparator(cur.pos() - 1)
1030 bool ws_right = (cur.pos() + res < par.size())
1031 ? par.isWordSeparator(cur.pos() + res)
1034 "cur.pos()=" << cur.pos() << ", res=" << res
1035 << ", separ: " << ws_left << ", " << ws_right
1037 if (ws_left && ws_right)
1043 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1046 if (! opt.casesensitive)
1047 t = lyx::to_utf8(lowercase(s));
1049 t = lyx::to_utf8(s);
1050 // Remove \n at begin
1051 while (!t.empty() && t[0] == '\n')
1054 while (!t.empty() && t[t.size() - 1] == '\n')
1055 t = t.substr(0, t.size() - 1);
1057 // Replace all other \n with spaces
1058 while ((pos = t.find("\n")) != string::npos)
1059 t.replace(pos, 1, " ");
1060 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1061 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1062 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
1063 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1065 // FIXME - check what preceeds the brace
1067 if (opt.ignoreformat)
1068 while (regex_replace(t, t, "\\{", "_x_<")
1069 || regex_replace(t, t, "\\}", "_x_>"))
1070 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1072 while (regex_replace(t, t, "\\\\\\{", "_x_<")
1073 || regex_replace(t, t, "\\\\\\}", "_x_>"))
1074 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1081 docstring stringifyFromCursor(DocIterator const & cur, int len)
1083 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1084 if (cur.inTexted()) {
1085 Paragraph const & par = cur.paragraph();
1086 // TODO what about searching beyond/across paragraph breaks ?
1087 // TODO Try adding a AS_STR_INSERTS as last arg
1088 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1089 int(par.size()) : cur.pos() + len;
1090 OutputParams runparams(&cur.buffer()->params().encoding());
1091 runparams.nice = true;
1092 runparams.flavor = OutputParams::LATEX;
1093 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1094 // No side effect of file copying and image conversion
1095 runparams.dryrun = true;
1096 LYXERR(Debug::FIND, "Stringifying with cur: "
1097 << cur << ", from pos: " << cur.pos() << ", end: " << end);
1098 return par.asString(cur.pos(), end,
1099 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1101 } else if (cur.inMathed()) {
1103 CursorSlice cs = cur.top();
1104 MathData md = cs.cell();
1105 MathData::const_iterator it_end =
1106 (( len == -1 || cs.pos() + len > int(md.size()))
1108 : md.begin() + cs.pos() + len );
1109 for (MathData::const_iterator it = md.begin() + cs.pos();
1111 s = s + asString(*it);
1112 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1115 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1120 /** Computes the LaTeX export of buf starting from cur and ending len positions
1121 * after cur, if len is positive, or at the paragraph or innermost inset end
1124 docstring latexifyFromCursor(DocIterator const & cur, int len)
1126 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1127 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1128 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1129 Buffer const & buf = *cur.buffer();
1131 odocstringstream ods;
1133 OutputParams runparams(&buf.params().encoding());
1134 runparams.nice = false;
1135 runparams.flavor = OutputParams::LATEX;
1136 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1137 // No side effect of file copying and image conversion
1138 runparams.dryrun = true;
1140 if (cur.inTexted()) {
1141 // @TODO what about searching beyond/across paragraph breaks ?
1142 pos_type endpos = cur.paragraph().size();
1143 if (len != -1 && endpos > cur.pos() + len)
1144 endpos = cur.pos() + len;
1145 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1146 string(), cur.pos(), endpos);
1147 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1148 } else if (cur.inMathed()) {
1149 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1150 for (int s = cur.depth() - 1; s >= 0; --s) {
1151 CursorSlice const & cs = cur[s];
1152 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1154 cs.asInsetMath()->asHullInset()->header_write(ws);
1159 CursorSlice const & cs = cur.top();
1160 MathData md = cs.cell();
1161 MathData::const_iterator it_end =
1162 ((len == -1 || cs.pos() + len > int(md.size()))
1164 : md.begin() + cs.pos() + len);
1165 for (MathData::const_iterator it = md.begin() + cs.pos();
1167 ods << asString(*it);
1169 // Retrieve the math environment type, and add '$' or '$]'
1170 // or others (\end{equation}) accordingly
1171 for (int s = cur.depth() - 1; s >= 0; --s) {
1172 CursorSlice const & cs2 = cur[s];
1173 InsetMath * inset = cs2.asInsetMath();
1174 if (inset && inset->asHullInset()) {
1176 inset->asHullInset()->footer_write(ws);
1180 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1182 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1188 /** Finalize an advanced find operation, advancing the cursor to the innermost
1189 ** position that matches, plus computing the length of the matching text to
1192 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1194 // Search the foremost position that matches (avoids find of entire math
1195 // inset when match at start of it)
1197 DocIterator old_cur(cur.buffer());
1199 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1203 } while (cur && cur.depth() > d && match(cur) > 0);
1205 LASSERT(match(cur) > 0, return 0);
1206 LYXERR(Debug::FIND, "Ok");
1208 // Compute the match length
1210 if (cur.pos() + len > cur.lastpos())
1212 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1213 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1215 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1217 // Length of matched text (different from len param)
1218 int old_len = match(cur, len);
1220 // Greedy behaviour while matching regexps
1221 while ((new_len = match(cur, len + 1)) > old_len) {
1224 LYXERR(Debug::FIND, "verifying match with len = " << len);
1231 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1235 while (!theApp()->longOperationCancelled() && cur) {
1236 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1237 int match_len = match(cur, -1, false);
1238 LYXERR(Debug::FIND, "match_len: " << match_len);
1240 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1241 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1242 int match_len2 = match(cur);
1243 LYXERR(Debug::FIND, "match_len: " << match_len2);
1245 // Sometimes in finalize we understand it wasn't a match
1246 // and we need to continue the outest loop
1247 int len = findAdvFinalize(cur, match);
1255 if (cur.pit() < cur.lastpit()) {
1256 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1259 // This should exit nested insets, if any, or otherwise undefine the currsor.
1260 cur.pos() = cur.lastpos();
1261 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1269 /// Find the most backward consecutive match within same paragraph while searching backwards.
1270 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1272 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1273 DocIterator tmp_cur = cur;
1274 int len = findAdvFinalize(tmp_cur, match);
1275 Inset & inset = cur.inset();
1276 for (; cur != cur_begin; cur.backwardPos()) {
1277 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1278 DocIterator new_cur = cur;
1279 new_cur.backwardPos();
1280 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1282 int new_len = findAdvFinalize(new_cur, match);
1287 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1293 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1297 // Backup of original position
1298 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1299 if (cur == cur_begin)
1302 DocIterator cur_orig(cur);
1303 bool pit_changed = false;
1306 bool found_match = match(cur, -1, false);
1310 cur.pos() = cur.lastpos();
1312 cur.pos() = cur_orig.pos();
1313 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1314 DocIterator cur_prev_iter;
1316 found_match = match(cur);
1317 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1318 << found_match << ", cur: " << cur);
1320 return findMostBackwards(cur, match);
1322 // Stop if begin of document reached
1323 if (cur == cur_begin)
1325 cur_prev_iter = cur;
1329 if (cur == cur_begin)
1336 } while (!theApp()->longOperationCancelled());
1344 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1345 DocIterator const & cur, int len)
1347 LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1348 return docstring());
1349 if (!opt.ignoreformat)
1350 return latexifyFromCursor(cur, len);
1352 return stringifyFromCursor(cur, len);
1356 FindAndReplaceOptions::FindAndReplaceOptions(
1357 docstring const & find_buf_name, bool casesensitive,
1358 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1359 docstring const & repl_buf_name, bool keep_case,
1360 SearchScope scope, SearchRestriction restr)
1361 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1362 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1363 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1371 /** Check if 'len' letters following cursor are all non-lowercase */
1372 static bool allNonLowercase(Cursor const & cur, int len)
1374 pos_type beg_pos = cur.selectionBegin().pos();
1375 pos_type end_pos = cur.selectionBegin().pos() + len;
1376 if (len > cur.lastpos() + 1 - beg_pos) {
1377 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1378 len = cur.lastpos() + 1 - beg_pos;
1379 end_pos = beg_pos + len;
1381 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1382 if (isLowerCase(cur.paragraph().getChar(pos)))
1388 /** Check if first letter is upper case and second one is lower case */
1389 static bool firstUppercase(Cursor const & cur)
1392 pos_type pos = cur.selectionBegin().pos();
1393 if (pos >= cur.lastpos() - 1) {
1394 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1397 ch1 = cur.paragraph().getChar(pos);
1398 ch2 = cur.paragraph().getChar(pos + 1);
1399 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1400 LYXERR(Debug::FIND, "firstUppercase(): "
1401 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1402 << ch2 << "(" << char(ch2) << ")"
1403 << ", result=" << result << ", cur=" << cur);
1408 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1410 ** \fixme What to do with possible further paragraphs in replace buffer ?
1412 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1414 ParagraphList::iterator pit = buffer.paragraphs().begin();
1415 LASSERT(pit->size() >= 1, /**/);
1416 pos_type right = pos_type(1);
1417 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1418 right = pit->size();
1419 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1425 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1427 Cursor & cur = bv->cursor();
1428 if (opt.repl_buf_name == docstring()
1429 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
1430 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1433 DocIterator sel_beg = cur.selectionBegin();
1434 DocIterator sel_end = cur.selectionEnd();
1435 if (&sel_beg.inset() != &sel_end.inset()
1436 || sel_beg.pit() != sel_end.pit()
1437 || sel_beg.idx() != sel_end.idx())
1439 int sel_len = sel_end.pos() - sel_beg.pos();
1440 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1441 << ", sel_len: " << sel_len << endl);
1444 LASSERT(sel_len > 0, return);
1446 if (!matchAdv(sel_beg, sel_len))
1449 // Build a copy of the replace buffer, adapted to the KeepCase option
1450 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1452 repl_buffer_orig.write(oss);
1453 string lyx = oss.str();
1454 Buffer repl_buffer("", false);
1455 repl_buffer.setUnnamed(true);
1456 LASSERT(repl_buffer.readString(lyx), return);
1457 if (opt.keep_case && sel_len >= 2) {
1458 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1459 if (cur.inTexted()) {
1460 if (firstUppercase(cur))
1461 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1462 else if (allNonLowercase(cur, sel_len))
1463 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1466 cap::cutSelection(cur, false, false);
1467 if (cur.inTexted()) {
1468 repl_buffer.changeLanguage(
1469 repl_buffer.language(),
1470 cur.getFont().language());
1471 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1472 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1473 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1474 repl_buffer.params().documentClassPtr(),
1475 bv->buffer().errorList("Paste"));
1476 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1477 sel_len = repl_buffer.paragraphs().begin()->size();
1478 } else if (cur.inMathed()) {
1479 odocstringstream ods;
1481 OutputParams runparams(&repl_buffer.params().encoding());
1482 runparams.nice = false;
1483 runparams.flavor = OutputParams::LATEX;
1484 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1485 runparams.dryrun = true;
1486 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1487 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1488 docstring repl_latex = ods.str();
1489 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1491 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1492 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1493 repl_latex = from_utf8(s);
1494 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1495 MathData ar(cur.buffer());
1496 asArray(repl_latex, ar, Parse::NORMAL);
1498 sel_len = ar.size();
1499 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1501 if (cur.pos() >= sel_len)
1502 cur.pos() -= sel_len;
1505 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1506 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1507 bv->processUpdateFlags(Update::Force);
1511 /// Perform a FindAdv operation.
1512 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1517 // e.g., when invoking word-findadv from mini-buffer wither with
1518 // wrong options syntax or before ever opening advanced F&R pane
1519 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1523 MatchStringAdv matchAdv(bv->buffer(), opt);
1524 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1526 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1527 findAdvReplace(bv, opt, matchAdv);
1530 match_len = findForwardAdv(cur, matchAdv);
1532 match_len = findBackwardsAdv(cur, matchAdv);
1534 // This may only be raised by lyx::regex()
1535 bv->message(_("Invalid regular expression!"));
1539 if (match_len == 0) {
1540 bv->message(_("Match not found!"));
1544 bv->message(_("Match found!"));
1546 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1547 bv->putSelectionAt(cur, match_len, !opt.forward);
1553 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1555 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1556 << opt.casesensitive << ' '
1557 << opt.matchword << ' '
1558 << opt.forward << ' '
1559 << opt.expandmacros << ' '
1560 << opt.ignoreformat << ' '
1561 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1562 << opt.keep_case << ' '
1563 << int(opt.scope) << ' '
1566 LYXERR(Debug::FIND, "built: " << os.str());
1572 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1574 LYXERR(Debug::FIND, "parsing");
1578 while (line != "EOSS") {
1582 if (is.eof()) // Tolerate malformed request
1586 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1587 opt.find_buf_name = from_utf8(s);
1588 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1589 is.get(); // Waste space before replace string
1592 while (line != "EOSS") {
1596 if (is.eof()) // Tolerate malformed request
1600 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1601 opt.repl_buf_name = from_utf8(s);
1602 is >> opt.keep_case;
1605 opt.scope = FindAndReplaceOptions::SearchScope(i);
1607 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1609 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1610 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1611 << opt.scope << ' ' << opt.restr);