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"
59 using namespace lyx::support;
65 bool parse_bool(docstring & howto)
70 howto = split(howto, var, ' ');
78 MatchString(docstring const & str, bool cs, bool mw)
79 : str(str), case_sens(cs), whole_words(mw)
82 // returns true if the specified string is at the specified position
83 // del specifies whether deleted strings in ct mode will be considered
84 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
86 return par.find(str, case_sens, whole_words, pos, del);
94 // match whole words only
99 int findForward(DocIterator & cur, MatchString const & match,
100 bool find_del = true)
102 for (; cur; cur.forwardChar())
103 if (cur.inTexted()) {
104 int len = match(cur.paragraph(), cur.pos(), find_del);
112 int findBackwards(DocIterator & cur, MatchString const & match,
113 bool find_del = true)
117 if (cur.inTexted()) {
118 int len = match(cur.paragraph(), cur.pos(), find_del);
127 bool searchAllowed(docstring const & str)
130 frontend::Alert::error(_("Search error"), _("Search string is empty"));
137 bool findOne(BufferView * bv, docstring const & searchstr,
138 bool case_sens, bool whole, bool forward,
139 bool find_del = true, bool check_wrap = false)
141 if (!searchAllowed(searchstr))
144 DocIterator cur = forward
145 ? bv->cursor().selectionEnd()
146 : bv->cursor().selectionBegin();
148 MatchString const match(searchstr, case_sens, whole);
150 int match_len = forward
151 ? findForward(cur, match, find_del)
152 : findBackwards(cur, match, find_del);
155 bv->putSelectionAt(cur, match_len, !forward);
156 else if (check_wrap) {
157 DocIterator cur_orig(bv->cursor());
160 q = _("End of file reached while searching forward.\n"
161 "Continue searching from the beginning?");
163 q = _("Beginning of file reached while searching backward.\n"
164 "Continue searching from the end?");
165 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
166 q, 0, 1, _("&Yes"), _("&No"));
167 if (wrap_answer == 0) {
169 bv->cursor().clear();
170 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
172 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
173 bv->cursor().backwardPos();
175 bv->clearSelection();
176 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
179 bv->cursor().setCursor(cur_orig);
183 return match_len > 0;
187 int replaceAll(BufferView * bv,
188 docstring const & searchstr, docstring const & replacestr,
189 bool case_sens, bool whole)
191 Buffer & buf = bv->buffer();
193 if (!searchAllowed(searchstr) || buf.isReadonly())
196 DocIterator cur_orig(bv->cursor());
198 MatchString const match(searchstr, case_sens, whole);
201 int const rsize = replacestr.size();
202 int const ssize = searchstr.size();
205 cur.setCursor(doc_iterator_begin(&buf));
206 int match_len = findForward(cur, match, false);
207 while (match_len > 0) {
208 // Backup current cursor position and font.
209 pos_type const pos = cur.pos();
210 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
212 int striked = ssize -
213 cur.paragraph().eraseChars(pos, pos + match_len,
214 buf.params().track_changes);
215 cur.paragraph().insert(pos, replacestr, font,
216 Change(buf.params().track_changes
218 : Change::UNCHANGED));
219 for (int i = 0; i < rsize + striked; ++i)
222 match_len = findForward(cur, match, false);
225 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
227 cur_orig.fixIfBroken();
228 bv->setCursor(cur_orig);
234 // the idea here is that we are going to replace the string that
235 // is selected IF it is the search string.
236 // if there is a selection, but it is not the search string, then
237 // we basically ignore it. (FIXME We ought to replace only within
239 // if there is no selection, then:
240 // (i) if some search string has been provided, then we find it.
241 // (think of how the dialog works when you hit "replace" the
243 // (ii) if no search string has been provided, then we treat the
244 // word the cursor is in as the search string. (why? i have no
245 // idea.) but this only works in text?
247 // returns the number of replacements made (one, if any) and
248 // whether anything at all was done.
249 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
250 docstring const & replacestr, bool case_sens,
251 bool whole, bool forward, bool findnext)
253 Cursor & cur = bv->cursor();
255 if (!cur.selection()) {
256 // no selection, non-empty search string: find it
257 if (!searchstr.empty()) {
258 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
259 return make_pair(found, 0);
261 // empty search string
264 return make_pair(false, 0);
265 // select current word and treat it as the search string.
266 // This causes a minor bug as undo will restore this selection,
267 // which the user did not create (#8986).
268 cur.innerText()->selectWord(cur, WHOLE_WORD);
269 searchstr = cur.selectionAsString(false);
272 // if we still don't have a search string, report the error
274 if (!searchAllowed(searchstr))
275 return make_pair(false, 0);
277 bool have_selection = cur.selection();
278 docstring const selected = cur.selectionAsString(false);
281 ? searchstr == selected
282 : compare_no_case(searchstr, selected) == 0;
284 // no selection or current selection is not search word:
285 // just find the search word
286 if (!have_selection || !match) {
287 found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
288 return make_pair(found, 0);
291 // we're now actually ready to replace. if the buffer is
292 // read-only, we can't, though.
293 if (bv->buffer().isReadonly())
294 return make_pair(false, 0);
296 cap::replaceSelectionWithString(cur, replacestr);
298 cur.pos() += replacestr.length();
299 LASSERT(cur.pos() <= cur.lastpos(),
300 cur.pos() = cur.lastpos());
303 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
305 return make_pair(true, 1);
311 docstring const find2string(docstring const & search,
312 bool casesensitive, bool matchword, bool forward)
316 << int(casesensitive) << ' '
317 << int(matchword) << ' '
323 docstring const replace2string(docstring const & replace,
324 docstring const & search,
325 bool casesensitive, bool matchword,
326 bool all, bool forward, bool findnext)
329 ss << replace << '\n'
331 << int(casesensitive) << ' '
332 << int(matchword) << ' '
334 << int(forward) << ' '
340 bool lyxfind(BufferView * bv, FuncRequest const & ev)
342 if (!bv || ev.action() != LFUN_WORD_FIND)
345 //lyxerr << "find called, cmd: " << ev << endl;
347 // data is of the form
349 // <casesensitive> <matchword> <forward>"
351 docstring howto = split(ev.argument(), search, '\n');
353 bool casesensitive = parse_bool(howto);
354 bool matchword = parse_bool(howto);
355 bool forward = parse_bool(howto);
357 return findOne(bv, search, casesensitive, matchword, forward, true, true);
361 bool lyxreplace(BufferView * bv,
362 FuncRequest const & ev, bool has_deleted)
364 if (!bv || ev.action() != LFUN_WORD_REPLACE)
367 // data is of the form
370 // <casesensitive> <matchword> <all> <forward> <findnext>"
373 docstring howto = split(ev.argument(), rplc, '\n');
374 howto = split(howto, search, '\n');
376 bool casesensitive = parse_bool(howto);
377 bool matchword = parse_bool(howto);
378 bool all = parse_bool(howto);
379 bool forward = parse_bool(howto);
380 bool findnext = howto.empty() ? true : parse_bool(howto);
385 int replace_count = 0;
387 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
388 update = replace_count > 0;
391 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
393 replace_count = rv.second;
396 Buffer const & buf = bv->buffer();
398 // emit message signal.
399 buf.message(_("String not found."));
401 if (replace_count == 0) {
402 buf.message(_("String found."));
403 } else if (replace_count == 1) {
404 buf.message(_("String has been replaced."));
406 docstring const str =
407 bformat(_("%1$d strings have been replaced."), replace_count);
411 } else if (findnext) {
412 // if we have deleted characters, we do not replace at all, but
413 // rather search for the next occurence
414 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
417 bv->message(_("String not found."));
423 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
425 for (; cur; cur.forwardPos())
426 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
430 DocIterator cur_orig(bv->cursor());
431 docstring q = _("End of file reached while searching forward.\n"
432 "Continue searching from the beginning?");
433 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
434 q, 0, 1, _("&Yes"), _("&No"));
435 if (wrap_answer == 0) {
436 bv->cursor().clear();
437 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
438 bv->clearSelection();
439 cur.setCursor(bv->cursor().selectionBegin());
440 if (findNextChange(bv, cur, false))
443 bv->cursor().setCursor(cur_orig);
450 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
452 for (cur.backwardPos(); cur; cur.backwardPos()) {
453 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
458 DocIterator cur_orig(bv->cursor());
459 docstring q = _("Beginning of file reached while searching backward.\n"
460 "Continue searching from the end?");
461 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
462 q, 0, 1, _("&Yes"), _("&No"));
463 if (wrap_answer == 0) {
464 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
465 bv->cursor().backwardPos();
466 bv->clearSelection();
467 cur.setCursor(bv->cursor().selectionBegin());
468 if (findPreviousChange(bv, cur, false))
471 bv->cursor().setCursor(cur_orig);
478 bool selectChange(Cursor & cur, bool forward)
480 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
482 Change ch = cur.paragraph().lookupChange(cur.pos());
484 CursorSlice tip1 = cur.top();
485 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
486 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
487 if (!ch2.isSimilarTo(ch))
490 CursorSlice tip2 = cur.top();
491 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
493 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
494 if (!ch2.isSimilarTo(ch)) {
495 // take a step forward to correctly set the selection
503 cur.bv().mouseSetCursor(cur, false);
505 cur.bv().mouseSetCursor(cur, true);
513 bool findChange(BufferView * bv, bool forward)
516 cur.setCursor(forward ? bv->cursor().selectionEnd()
517 : bv->cursor().selectionBegin());
518 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
519 return selectChange(cur, forward);
524 bool findNextChange(BufferView * bv)
526 return findChange(bv, true);
530 bool findPreviousChange(BufferView * bv)
532 return findChange(bv, false);
539 typedef vector<pair<string, string> > Escapes;
541 /// A map of symbols and their escaped equivalent needed within a regex.
542 /// @note Beware of order
543 Escapes const & get_regexp_escapes()
545 typedef std::pair<std::string, std::string> P;
547 static Escapes escape_map;
548 if (escape_map.empty()) {
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(".", "_x_."));
559 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
560 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
561 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
562 escape_map.push_back(P("_x_", "\\"));
567 /// A map of lyx escaped strings and their unescaped equivalent.
568 Escapes const & get_lyx_unescapes()
570 typedef std::pair<std::string, std::string> P;
572 static Escapes escape_map;
573 if (escape_map.empty()) {
574 escape_map.push_back(P("\\%", "%"));
575 escape_map.push_back(P("\\mathcircumflex ", "^"));
576 escape_map.push_back(P("\\mathcircumflex", "^"));
577 escape_map.push_back(P("\\backslash ", "\\"));
578 escape_map.push_back(P("\\backslash", "\\"));
579 escape_map.push_back(P("\\\\{", "_x_<"));
580 escape_map.push_back(P("\\\\}", "_x_>"));
581 escape_map.push_back(P("\\sim ", "~"));
582 escape_map.push_back(P("\\sim", "~"));
587 /// A map of escapes turning a regexp matching text to one matching latex.
588 Escapes const & get_regexp_latex_escapes()
590 typedef std::pair<std::string, std::string> P;
592 static Escapes escape_map;
593 if (escape_map.empty()) {
594 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
595 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
596 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
597 escape_map.push_back(P("\\[", "\\{\\[\\}"));
598 escape_map.push_back(P("\\]", "\\{\\]\\}"));
599 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
600 escape_map.push_back(P("%", "\\\\\\%"));
605 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
606 ** the found occurrence were escaped.
608 string apply_escapes(string s, Escapes const & escape_map)
610 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
611 Escapes::const_iterator it;
612 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
613 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
614 unsigned int pos = 0;
615 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
616 s.replace(pos, it->first.length(), it->second);
617 LYXERR(Debug::FIND, "After escape: " << s);
618 pos += it->second.length();
619 // LYXERR(Debug::FIND, "pos: " << pos);
622 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
627 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
628 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
629 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
630 string escape_for_regex(string s, bool match_latex)
633 while (pos < s.size()) {
634 size_t new_pos = s.find("\\regexp{", pos);
635 if (new_pos == string::npos)
637 LYXERR(Debug::FIND, "new_pos: " << new_pos);
638 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
639 LYXERR(Debug::FIND, "t [lyx]: " << t);
640 t = apply_escapes(t, get_regexp_escapes());
641 LYXERR(Debug::FIND, "t [rxp]: " << t);
642 s.replace(pos, new_pos - pos, t);
643 new_pos = pos + t.size();
644 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
645 LYXERR(Debug::FIND, "new_pos: " << new_pos);
646 if (new_pos == s.size())
648 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
649 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
650 LYXERR(Debug::FIND, "end_pos: " << end_pos);
651 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
652 LYXERR(Debug::FIND, "t in regexp : " << t);
653 t = apply_escapes(t, get_lyx_unescapes());
654 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
656 t = apply_escapes(t, get_regexp_latex_escapes());
657 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
659 if (end_pos == s.size()) {
660 s.replace(new_pos, end_pos - new_pos, t);
661 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
664 s.replace(new_pos, end_pos + 13 - new_pos, t);
665 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
666 pos = new_pos + t.size();
667 LYXERR(Debug::FIND, "pos: " << pos);
673 /// Wrapper for lyx::regex_replace with simpler interface
674 bool regex_replace(string const & s, string & t, string const & searchstr,
675 string const & replacestr)
677 lyx::regex e(searchstr, regex_constants::ECMAScript);
679 ostream_iterator<char, char> it(oss);
680 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
681 // tolerate t and s be references to the same variable
682 bool rv = (s != oss.str());
688 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
690 ** Verify that closed braces exactly match open braces. This avoids that, for example,
691 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
694 ** Number of open braces that must remain open at the end for the verification to succeed.
696 bool braces_match(string::const_iterator const & beg,
697 string::const_iterator const & end,
701 string::const_iterator it = beg;
702 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
703 for (; it != end; ++it) {
704 // Skip escaped braces in the count
709 } else if (*it == '{') {
711 } else if (*it == '}') {
712 if (open_pars == 0) {
713 LYXERR(Debug::FIND, "Found unmatched closed brace");
719 if (open_pars != unmatched) {
720 LYXERR(Debug::FIND, "Found " << open_pars
721 << " instead of " << unmatched
722 << " unmatched open braces at the end of count");
725 LYXERR(Debug::FIND, "Braces match as expected");
730 /** The class performing a match between a position in the document and the FindAdvOptions.
732 class MatchStringAdv {
734 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
736 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
737 ** constructor as opt.search, under the opt.* options settings.
740 ** If set, then match is searched only against beginning of text starting at cur.
741 ** If unset, then match is searched anywhere in text starting at cur.
744 ** The length of the matching text, or zero if no match was found.
746 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
751 /// first buffer on which search was started
752 lyx::Buffer * const p_first_buf;
754 FindAndReplaceOptions const & opt;
757 /// Auxiliary find method (does not account for opt.matchword)
758 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
760 /** Normalize a stringified or latexified LyX paragraph.
764 ** <li>if search is not casesensitive, then lowercase the string;
765 ** <li>remove any newline at begin or end of the string;
766 ** <li>replace any newline in the middle of the string with a simple space;
767 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
770 ** @todo Normalization should also expand macros, if the corresponding
771 ** search option was checked.
773 string normalize(docstring const & s, bool hack_braces) const;
774 // normalized string to search
775 string par_as_string;
776 // regular expression to use for searching
778 // same as regexp, but prefixed with a ".*"
780 // leading format material as string
781 string lead_as_string;
782 // par_as_string after removal of lead_as_string
783 string par_as_string_nolead;
784 // unmatched open braces in the search string/regexp
786 // number of (.*?) subexpressions added at end of search regexp for closing
787 // environments, math mode, styles, etc...
789 // Are we searching with regular expressions ?
794 static docstring buffer_to_latex(Buffer & buffer)
796 OutputParams runparams(&buffer.params().encoding());
797 odocstringstream ods;
799 runparams.nice = true;
800 runparams.flavor = OutputParams::LATEX;
801 runparams.linelen = 80; //lyxrc.plaintext_linelen;
802 // No side effect of file copying and image conversion
803 runparams.dryrun = true;
804 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 while (regex_replace(t, t, REGEX_BOS "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
847 || regex_replace(t, t, REGEX_BOS "\\$", "")
848 || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
849 || regex_replace(t, t, REGEX_BOS "\\\\item ", "")
850 || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
851 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
856 // Remove trailing closure of math, macros and environments, so to catch parts of them.
857 static int identifyClosing(string & t)
861 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
862 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
864 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
866 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
868 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
878 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
879 : p_buf(&buf), p_first_buf(&buf), opt(opt)
881 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
882 docstring const & ds = stringifySearchBuffer(find_buf, opt);
883 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
884 // When using regexp, braces are hacked already by escape_for_regex()
885 par_as_string = normalize(ds, !use_regexp);
889 size_t lead_size = 0;
890 if (opt.ignoreformat) {
892 // if par_as_string_nolead were emty,
893 // the following call to findAux will always *find* the string
894 // in the checked data, and thus always using the slow
895 // examining of the current text part.
896 par_as_string_nolead = par_as_string;
899 lead_size = identifyLeading(par_as_string);
900 lead_as_string = par_as_string.substr(0, lead_size);
901 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
905 open_braces = identifyClosing(par_as_string);
906 identifyClosing(par_as_string_nolead);
907 LYXERR(Debug::FIND, "Open braces: " << open_braces);
908 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
910 string lead_as_regexp;
912 // @todo No need to search for \regexp{} insets in leading material
913 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
914 par_as_string = par_as_string_nolead;
915 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
916 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
918 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
919 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
920 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
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 '\\\]' ('\]' has been escaped by escape_for_regex)
925 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
926 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
927 || regex_replace(par_as_string, par_as_string,
928 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
929 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
930 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
934 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
935 LYXERR(Debug::FIND, "Open braces: " << open_braces);
936 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
937 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
939 // If entered regexp must match at begin of searched string buffer
940 string regexp_str = lead_as_regexp + par_as_string;
941 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
942 regexp = lyx::regex(regexp_str);
944 // If entered regexp may match wherever in searched string buffer
945 string regexp2_str = lead_as_regexp + ".*" + par_as_string;
946 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
947 regexp2 = lyx::regex(regexp2_str);
952 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
955 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
958 docstring docstr = stringifyFromForSearch(opt, cur, len);
959 string str = normalize(docstr, true);
960 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
961 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
964 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
965 regex const *p_regexp;
966 regex_constants::match_flag_type flags;
968 flags = regex_constants::match_continuous;
971 flags = regex_constants::match_default;
974 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
975 if (re_it == sregex_iterator())
977 match_results<string::const_iterator> const & m = *re_it;
979 // Check braces on the segment that matched the entire regexp expression,
980 // plus the last subexpression, if a (.*?) was inserted in the constructor.
981 if (!braces_match(m[0].first, m[0].second, open_braces))
984 // Check braces on segments that matched all (.*?) subexpressions,
985 // except the last "padding" one inserted by lyx.
986 for (size_t i = 1; i < m.size() - 1; ++i)
987 if (!braces_match(m[i].first, m[i].second))
990 // Exclude from the returned match length any length
991 // due to close wildcards added at end of regexp
992 if (close_wildcards == 0)
993 return m[0].second - m[0].first;
995 return m[m.size() - close_wildcards].first - m[0].first;
998 // else !use_regexp: but all code paths above return
999 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
1000 << par_as_string << "', str='" << str << "'");
1001 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
1002 << lead_as_string << "', par_as_string_nolead='"
1003 << par_as_string_nolead << "'");
1006 LYXERR(Debug::FIND, "size=" << par_as_string.size()
1007 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
1008 if (str.substr(0, par_as_string.size()) == par_as_string)
1009 return par_as_string.size();
1011 size_t pos = str.find(par_as_string_nolead);
1012 if (pos != string::npos)
1013 return par_as_string.size();
1019 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
1021 int res = findAux(cur, len, at_begin);
1023 "res=" << res << ", at_begin=" << at_begin
1024 << ", matchword=" << opt.matchword
1025 << ", inTexted=" << cur.inTexted());
1026 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
1028 Paragraph const & par = cur.paragraph();
1029 bool ws_left = (cur.pos() > 0)
1030 ? par.isWordSeparator(cur.pos() - 1)
1032 bool ws_right = (cur.pos() + res < par.size())
1033 ? par.isWordSeparator(cur.pos() + res)
1036 "cur.pos()=" << cur.pos() << ", res=" << res
1037 << ", separ: " << ws_left << ", " << ws_right
1039 if (ws_left && ws_right)
1045 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
1048 if (! opt.casesensitive)
1049 t = lyx::to_utf8(lowercase(s));
1051 t = lyx::to_utf8(s);
1052 // Remove \n at begin
1053 while (!t.empty() && t[0] == '\n')
1056 while (!t.empty() && t[t.size() - 1] == '\n')
1057 t = t.substr(0, t.size() - 1);
1059 // Replace all other \n with spaces
1060 while ((pos = t.find("\n")) != string::npos)
1061 t.replace(pos, 1, " ");
1062 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
1063 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
1064 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
1065 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
1067 // FIXME - check what preceeds the brace
1069 if (opt.ignoreformat)
1070 while (regex_replace(t, t, "\\{", "_x_<")
1071 || regex_replace(t, t, "\\}", "_x_>"))
1072 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1074 while (regex_replace(t, t, "\\\\\\{", "_x_<")
1075 || regex_replace(t, t, "\\\\\\}", "_x_>"))
1076 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1083 docstring stringifyFromCursor(DocIterator const & cur, int len)
1085 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1086 if (cur.inTexted()) {
1087 Paragraph const & par = cur.paragraph();
1088 // TODO what about searching beyond/across paragraph breaks ?
1089 // TODO Try adding a AS_STR_INSERTS as last arg
1090 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1091 int(par.size()) : cur.pos() + len;
1092 OutputParams runparams(&cur.buffer()->params().encoding());
1093 runparams.nice = true;
1094 runparams.flavor = OutputParams::LATEX;
1095 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1096 // No side effect of file copying and image conversion
1097 runparams.dryrun = true;
1098 LYXERR(Debug::FIND, "Stringifying with cur: "
1099 << cur << ", from pos: " << cur.pos() << ", end: " << end);
1100 return par.asString(cur.pos(), end,
1101 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
1103 } else if (cur.inMathed()) {
1104 CursorSlice cs = cur.top();
1105 MathData md = cs.cell();
1106 MathData::const_iterator it_end =
1107 (( len == -1 || cs.pos() + len > int(md.size()))
1109 : md.begin() + cs.pos() + len );
1111 for (MathData::const_iterator it = md.begin() + cs.pos();
1114 docstring s = asString(md2);
1115 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1118 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1123 /** Computes the LaTeX export of buf starting from cur and ending len positions
1124 * after cur, if len is positive, or at the paragraph or innermost inset end
1127 docstring latexifyFromCursor(DocIterator const & cur, int len)
1129 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1130 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1131 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1132 Buffer const & buf = *cur.buffer();
1134 odocstringstream ods;
1136 OutputParams runparams(&buf.params().encoding());
1137 runparams.nice = false;
1138 runparams.flavor = OutputParams::LATEX;
1139 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1140 // No side effect of file copying and image conversion
1141 runparams.dryrun = true;
1143 if (cur.inTexted()) {
1144 // @TODO what about searching beyond/across paragraph breaks ?
1145 pos_type endpos = cur.paragraph().size();
1146 if (len != -1 && endpos > cur.pos() + len)
1147 endpos = cur.pos() + len;
1148 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1149 string(), cur.pos(), endpos);
1150 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1151 } else if (cur.inMathed()) {
1152 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1153 for (int s = cur.depth() - 1; s >= 0; --s) {
1154 CursorSlice const & cs = cur[s];
1155 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1157 cs.asInsetMath()->asHullInset()->header_write(ws);
1162 CursorSlice const & cs = cur.top();
1163 MathData md = cs.cell();
1164 MathData::const_iterator it_end =
1165 ((len == -1 || cs.pos() + len > int(md.size()))
1167 : md.begin() + cs.pos() + len);
1169 for (MathData::const_iterator it = md.begin() + cs.pos();
1172 ods << asString(md2);
1174 // Retrieve the math environment type, and add '$' or '$]'
1175 // or others (\end{equation}) accordingly
1176 for (int s = cur.depth() - 1; s >= 0; --s) {
1177 CursorSlice const & cs = cur[s];
1178 InsetMath * inset = cs.asInsetMath();
1179 if (inset && inset->asHullInset()) {
1181 inset->asHullInset()->footer_write(ws);
1185 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1187 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1193 /** Finalize an advanced find operation, advancing the cursor to the innermost
1194 ** position that matches, plus computing the length of the matching text to
1197 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1199 // Search the foremost position that matches (avoids find of entire math
1200 // inset when match at start of it)
1202 DocIterator old_cur(cur.buffer());
1204 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1208 } while (cur && cur.depth() > d && match(cur) > 0);
1210 LASSERT(match(cur) > 0, return 0);
1211 LYXERR(Debug::FIND, "Ok");
1213 // Compute the match length
1215 if (cur.pos() + len > cur.lastpos())
1217 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1218 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1220 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1222 // Length of matched text (different from len param)
1223 int old_len = match(cur, len);
1225 // Greedy behaviour while matching regexps
1226 while ((new_len = match(cur, len + 1)) > old_len) {
1229 LYXERR(Debug::FIND, "verifying match with len = " << len);
1236 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1240 while (!theApp()->longOperationCancelled() && cur) {
1241 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1242 int match_len = match(cur, -1, false);
1243 LYXERR(Debug::FIND, "match_len: " << match_len);
1245 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1246 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1247 int match_len = match(cur);
1248 LYXERR(Debug::FIND, "match_len: " << match_len);
1250 // Sometimes in finalize we understand it wasn't a match
1251 // and we need to continue the outest loop
1252 int len = findAdvFinalize(cur, match);
1260 if (cur.pit() < cur.lastpit()) {
1261 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1264 // This should exit nested insets, if any, or otherwise undefine the currsor.
1265 cur.pos() = cur.lastpos();
1266 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1274 /// Find the most backward consecutive match within same paragraph while searching backwards.
1275 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1277 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1278 DocIterator tmp_cur = cur;
1279 int len = findAdvFinalize(tmp_cur, match);
1280 Inset & inset = cur.inset();
1281 for (; cur != cur_begin; cur.backwardPos()) {
1282 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1283 DocIterator new_cur = cur;
1284 new_cur.backwardPos();
1285 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1287 int new_len = findAdvFinalize(new_cur, match);
1292 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1298 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1302 // Backup of original position
1303 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1304 if (cur == cur_begin)
1307 DocIterator cur_orig(cur);
1308 bool pit_changed = false;
1311 bool found_match = match(cur, -1, false);
1315 cur.pos() = cur.lastpos();
1317 cur.pos() = cur_orig.pos();
1318 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1319 DocIterator cur_prev_iter;
1321 found_match = match(cur);
1322 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1323 << found_match << ", cur: " << cur);
1325 return findMostBackwards(cur, match);
1327 // Stop if begin of document reached
1328 if (cur == cur_begin)
1330 cur_prev_iter = cur;
1334 if (cur == cur_begin)
1341 } while (!theApp()->longOperationCancelled());
1349 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1350 DocIterator const & cur, int len)
1352 LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(),
1353 return docstring());
1354 if (!opt.ignoreformat)
1355 return latexifyFromCursor(cur, len);
1357 return stringifyFromCursor(cur, len);
1361 FindAndReplaceOptions::FindAndReplaceOptions(
1362 docstring const & find_buf_name, bool casesensitive,
1363 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1364 docstring const & repl_buf_name, bool keep_case,
1365 SearchScope scope, SearchRestriction restr)
1366 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1367 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1368 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr)
1376 /** Check if 'len' letters following cursor are all non-lowercase */
1377 static bool allNonLowercase(Cursor const & cur, int len)
1379 pos_type beg_pos = cur.selectionBegin().pos();
1380 pos_type end_pos = cur.selectionBegin().pos() + len;
1381 if (len > cur.lastpos() + 1 - beg_pos) {
1382 LYXERR(Debug::FIND, "This should not happen, more debug needed");
1383 len = cur.lastpos() + 1 - beg_pos;
1384 end_pos = beg_pos + len;
1386 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
1387 if (isLowerCase(cur.paragraph().getChar(pos)))
1393 /** Check if first letter is upper case and second one is lower case */
1394 static bool firstUppercase(Cursor const & cur)
1397 pos_type pos = cur.selectionBegin().pos();
1398 if (pos >= cur.lastpos() - 1) {
1399 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1402 ch1 = cur.paragraph().getChar(pos);
1403 ch2 = cur.paragraph().getChar(pos + 1);
1404 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1405 LYXERR(Debug::FIND, "firstUppercase(): "
1406 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1407 << ch2 << "(" << char(ch2) << ")"
1408 << ", result=" << result << ", cur=" << cur);
1413 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1415 ** \fixme What to do with possible further paragraphs in replace buffer ?
1417 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1419 ParagraphList::iterator pit = buffer.paragraphs().begin();
1420 LASSERT(pit->size() >= 1, /**/);
1421 pos_type right = pos_type(1);
1422 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1423 right = pit->size();
1424 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
1430 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1432 Cursor & cur = bv->cursor();
1433 if (opt.repl_buf_name == docstring()
1434 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
1435 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1438 DocIterator sel_beg = cur.selectionBegin();
1439 DocIterator sel_end = cur.selectionEnd();
1440 if (&sel_beg.inset() != &sel_end.inset()
1441 || sel_beg.pit() != sel_end.pit()
1442 || sel_beg.idx() != sel_end.idx())
1444 int sel_len = sel_end.pos() - sel_beg.pos();
1445 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1446 << ", sel_len: " << sel_len << endl);
1449 LASSERT(sel_len > 0, return);
1451 if (!matchAdv(sel_beg, sel_len))
1454 // Build a copy of the replace buffer, adapted to the KeepCase option
1455 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1457 repl_buffer_orig.write(oss);
1458 string lyx = oss.str();
1459 Buffer repl_buffer("", false);
1460 repl_buffer.setInternal(true);
1461 repl_buffer.setUnnamed(true);
1462 LASSERT(repl_buffer.readString(lyx), return);
1463 if (opt.keep_case && sel_len >= 2) {
1464 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
1465 if (cur.inTexted()) {
1466 if (firstUppercase(cur))
1467 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1468 else if (allNonLowercase(cur, sel_len))
1469 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1472 cap::cutSelection(cur, false);
1473 if (cur.inTexted()) {
1474 repl_buffer.changeLanguage(
1475 repl_buffer.language(),
1476 cur.getFont().language());
1477 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1478 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1479 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1480 repl_buffer.params().documentClassPtr(),
1481 bv->buffer().errorList("Paste"));
1482 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1483 sel_len = repl_buffer.paragraphs().begin()->size();
1484 } else if (cur.inMathed()) {
1485 odocstringstream ods;
1487 OutputParams runparams(&repl_buffer.params().encoding());
1488 runparams.nice = false;
1489 runparams.flavor = OutputParams::LATEX;
1490 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1491 runparams.dryrun = true;
1492 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1493 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1494 docstring repl_latex = ods.str();
1495 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1497 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1498 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1499 repl_latex = from_utf8(s);
1500 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1501 MathData ar(cur.buffer());
1502 asArray(repl_latex, ar, Parse::NORMAL);
1504 sel_len = ar.size();
1505 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1507 if (cur.pos() >= sel_len)
1508 cur.pos() -= sel_len;
1511 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1512 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1513 bv->processUpdateFlags(Update::Force);
1517 /// Perform a FindAdv operation.
1518 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1523 // e.g., when invoking word-findadv from mini-buffer wither with
1524 // wrong options syntax or before ever opening advanced F&R pane
1525 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
1529 MatchStringAdv matchAdv(bv->buffer(), opt);
1530 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
1532 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
1533 findAdvReplace(bv, opt, matchAdv);
1536 match_len = findForwardAdv(cur, matchAdv);
1538 match_len = findBackwardsAdv(cur, matchAdv);
1540 // This may only be raised by lyx::regex()
1541 bv->message(_("Invalid regular expression!"));
1545 if (match_len == 0) {
1546 bv->message(_("Match not found!"));
1550 bv->message(_("Match found!"));
1552 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1553 bv->putSelectionAt(cur, match_len, !opt.forward);
1559 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1561 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1562 << opt.casesensitive << ' '
1563 << opt.matchword << ' '
1564 << opt.forward << ' '
1565 << opt.expandmacros << ' '
1566 << opt.ignoreformat << ' '
1567 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1568 << opt.keep_case << ' '
1569 << int(opt.scope) << ' '
1572 LYXERR(Debug::FIND, "built: " << os.str());
1578 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1580 LYXERR(Debug::FIND, "parsing");
1584 while (line != "EOSS") {
1588 if (is.eof()) // Tolerate malformed request
1592 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1593 opt.find_buf_name = from_utf8(s);
1594 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1595 is.get(); // Waste space before replace string
1598 while (line != "EOSS") {
1602 if (is.eof()) // Tolerate malformed request
1606 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1607 opt.repl_buf_name = from_utf8(s);
1608 is >> opt.keep_case;
1611 opt.scope = FindAndReplaceOptions::SearchScope(i);
1613 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
1615 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1616 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
1617 << opt.scope << ' ' << opt.restr);