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 "BufferParams.h"
22 #include "BufferView.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "OutputParams.h"
28 #include "output_latex.h"
29 #include "Paragraph.h"
30 #include "ParIterator.h"
33 #include "FuncRequest.h"
36 #include "mathed/InsetMath.h"
37 #include "mathed/InsetMathGrid.h"
38 #include "mathed/InsetMathHull.h"
39 #include "mathed/MathStream.h"
41 #include "frontends/alert.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
48 #include "support/lassert.h"
50 #include <boost/regex.hpp>
51 #include <boost/next_prior.hpp>
54 using namespace lyx::support;
60 bool parse_bool(docstring & howto)
65 howto = split(howto, var, ' ');
70 class MatchString : public binary_function<Paragraph, pos_type, bool>
73 MatchString(docstring const & str, bool cs, bool mw)
74 : str(str), cs(cs), mw(mw)
77 // returns true if the specified string is at the specified position
78 // del specifies whether deleted strings in ct mode will be considered
79 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
81 return par.find(str, cs, mw, pos, del);
89 // match whole words only
94 bool findForward(DocIterator & cur, MatchString const & match,
97 for (; cur; cur.forwardChar())
99 match(cur.paragraph(), cur.pos(), find_del))
105 bool findBackwards(DocIterator & cur, MatchString const & match,
106 bool find_del = true)
110 if (cur.inTexted() &&
111 match(cur.paragraph(), cur.pos(), find_del))
118 bool findChange(DocIterator & cur)
120 for (; cur; cur.forwardPos())
121 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos()))
127 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
130 frontend::Alert::error(_("Search error"), _("Search string is empty"));
137 bool find(BufferView * bv, docstring const & searchstr,
138 bool cs, bool mw, bool fw, bool find_del = true)
140 if (!searchAllowed(bv, searchstr))
143 DocIterator cur = bv->cursor();
145 MatchString const match(searchstr, cs, mw);
147 bool found = fw ? findForward(cur, match, find_del) :
148 findBackwards(cur, match, find_del);
151 bv->putSelectionAt(cur, searchstr.length(), !fw);
157 int replaceAll(BufferView * bv,
158 docstring const & searchstr, docstring const & replacestr,
161 Buffer & buf = bv->buffer();
163 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
166 MatchString const match(searchstr, cs, mw);
169 int const rsize = replacestr.size();
170 int const ssize = searchstr.size();
173 cur.setCursor(doc_iterator_begin(&buf));
174 while (findForward(cur, match, false)) {
175 // Backup current cursor position and font.
176 pos_type const pos = cur.pos();
177 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
179 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
180 buf.params().trackChanges);
181 cur.paragraph().insert(pos, replacestr, font,
182 Change(buf.params().trackChanges ?
183 Change::INSERTED : Change::UNCHANGED));
184 for (int i = 0; i < rsize + striked; ++i)
190 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
197 bool stringSelected(BufferView * bv, docstring const & searchstr,
198 bool cs, bool mw, bool fw)
200 // if nothing selected or selection does not equal search
201 // string search and select next occurance and return
202 docstring const & str1 = searchstr;
203 docstring const str2 = bv->cursor().selectionAsString(false);
204 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
205 find(bv, searchstr, cs, mw, fw);
213 int replace(BufferView * bv, docstring const & searchstr,
214 docstring const & replacestr, bool cs, bool mw, bool fw)
216 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
219 if (!stringSelected(bv, searchstr, cs, mw, fw))
222 Cursor & cur = bv->cursor();
223 cap::replaceSelectionWithString(cur, replacestr, fw);
224 bv->buffer().markDirty();
225 find(bv, searchstr, cs, mw, fw, false);
226 bv->buffer().updateMacros();
227 bv->processUpdateFlags(Update::Force | Update::FitCursor);
235 docstring const find2string(docstring const & search,
236 bool casesensitive, bool matchword, bool forward)
240 << int(casesensitive) << ' '
241 << int(matchword) << ' '
247 docstring const replace2string(docstring const & search, docstring const & replace,
248 bool casesensitive, bool matchword,
249 bool all, bool forward)
254 << int(casesensitive) << ' '
255 << int(matchword) << ' '
262 bool find(BufferView * bv, FuncRequest const & ev)
264 if (!bv || ev.action != LFUN_WORD_FIND)
267 //lyxerr << "find called, cmd: " << ev << endl;
269 // data is of the form
271 // <casesensitive> <matchword> <forward>"
273 docstring howto = split(ev.argument(), search, '\n');
275 bool casesensitive = parse_bool(howto);
276 bool matchword = parse_bool(howto);
277 bool forward = parse_bool(howto);
279 return find(bv, search, casesensitive, matchword, forward);
283 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
285 if (!bv || ev.action != LFUN_WORD_REPLACE)
288 // data is of the form
291 // <casesensitive> <matchword> <all> <forward>"
294 docstring howto = split(ev.argument(), search, '\n');
295 howto = split(howto, rplc, '\n');
297 bool casesensitive = parse_bool(howto);
298 bool matchword = parse_bool(howto);
299 bool all = parse_bool(howto);
300 bool forward = parse_bool(howto);
303 int const replace_count = all
304 ? replaceAll(bv, search, rplc, casesensitive, matchword)
305 : replace(bv, search, rplc, casesensitive, matchword, forward);
307 Buffer & buf = bv->buffer();
308 if (replace_count == 0) {
309 // emit message signal.
310 buf.message(_("String not found!"));
312 if (replace_count == 1) {
313 // emit message signal.
314 buf.message(_("String has been replaced."));
316 docstring str = convert<docstring>(replace_count);
317 str += _(" strings have been replaced.");
318 // emit message signal.
323 // if we have deleted characters, we do not replace at all, but
324 // rather search for the next occurence
325 if (find(bv, search, casesensitive, matchword, forward))
328 bv->message(_("String not found!"));
333 bool findNextChange(BufferView * bv)
335 DocIterator cur = bv->cursor();
337 if (!findChange(cur))
340 bv->cursor().setCursor(cur);
341 bv->cursor().resetAnchor();
343 Change orig_change = cur.paragraph().lookupChange(cur.pos());
345 CursorSlice & tip = cur.top();
346 for (; !tip.at_end(); tip.forwardPos()) {
347 Change change = tip.paragraph().lookupChange(tip.pos());
348 if (change != orig_change)
352 // Now put cursor to end of selection:
353 bv->cursor().setCursor(cur);
354 bv->cursor().setSelection();
361 typedef vector<pair<string, string> > Escapes;
363 /// A map of symbols and their escaped equivalent needed within a regex.
364 Escapes const & get_regexp_escapes()
366 static Escapes escape_map;
367 if (escape_map.empty()) {
368 escape_map.push_back(pair<string, string>("\\", "\\\\"));
369 escape_map.push_back(pair<string, string>("^", "\\^"));
370 escape_map.push_back(pair<string, string>("$", "\\$"));
371 escape_map.push_back(pair<string, string>("{", "\\{"));
372 escape_map.push_back(pair<string, string>("}", "\\}"));
373 escape_map.push_back(pair<string, string>("[", "\\["));
374 escape_map.push_back(pair<string, string>("]", "\\]"));
375 escape_map.push_back(pair<string, string>("(", "\\("));
376 escape_map.push_back(pair<string, string>(")", "\\)"));
377 escape_map.push_back(pair<string, string>("+", "\\+"));
378 escape_map.push_back(pair<string, string>("*", "\\*"));
379 escape_map.push_back(pair<string, string>(".", "\\."));
384 /// A map of lyx escaped strings and their unescaped equivalent.
385 Escapes const & get_lyx_unescapes() {
386 static Escapes escape_map;
387 if (escape_map.empty()) {
388 escape_map.push_back(pair<string, string>("{*}", "*"));
389 escape_map.push_back(pair<string, string>("{[}", "["));
390 escape_map.push_back(pair<string, string>("\\$", "$"));
391 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
392 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
393 escape_map.push_back(pair<string, string>("\\sim ", "~"));
394 escape_map.push_back(pair<string, string>("\\^", "^"));
399 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
400 ** the found occurrence were escaped.
402 string apply_escapes(string s, Escapes const & escape_map)
404 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
405 Escapes::const_iterator it;
406 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
407 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
408 unsigned int pos = 0;
409 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
410 s.replace(pos, it->first.length(), it->second);
411 // LYXERR(Debug::DEBUG, "After escape: " << s);
412 pos += it->second.length();
413 // LYXERR(Debug::DEBUG, "pos: " << pos);
416 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
420 /** Return the position of the closing brace matching the open one at s[pos],
421 ** or s.size() if not found.
423 size_t find_matching_brace(string const & s, size_t pos)
425 LASSERT(s[pos] == '{', /* */);
427 for (++pos; pos < s.size(); ++pos) {
430 else if (s[pos] == '{')
432 else if (s[pos] == '}') {
434 if (open_braces == 0)
441 /// Within \regex{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
442 string escape_for_regex(string s)
445 while (pos < s.size()) {
446 size_t new_pos = s.find("\\regexp{", pos);
447 if (new_pos == string::npos)
449 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
450 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
451 LYXERR(Debug::DEBUG, "t : " << t);
452 t = apply_escapes(t, get_regexp_escapes());
453 s.replace(pos, new_pos - pos, t);
454 new_pos = pos + t.size();
455 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
456 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
457 if (new_pos == s.size())
459 size_t end_pos = find_matching_brace(s, new_pos + 7);
460 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
461 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
462 LYXERR(Debug::DEBUG, "t : " << t);
463 if (end_pos == s.size()) {
464 s.replace(new_pos, end_pos - new_pos, t);
466 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
469 s.replace(new_pos, end_pos + 1 - new_pos, t);
470 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
471 pos = new_pos + t.size();
472 LYXERR(Debug::DEBUG, "pos: " << pos);
477 /// Wrapper for boost::regex_replace with simpler interface
478 bool regex_replace(string const & s, string & t, string const & searchstr,
479 string const & replacestr)
481 boost::regex e(searchstr);
483 ostream_iterator<char, char> it(oss);
484 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
485 // tolerate t and s be references to the same variable
486 bool rv = (s != oss.str());
491 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
493 ** Verify that closed braces exactly match open braces. This avoids that, for example,
494 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
497 ** Number of open braces that must remain open at the end for the verification to succeed.
499 bool braces_match(string::const_iterator const & beg,
500 string::const_iterator const & end, int unmatched = 0)
503 string::const_iterator it = beg;
504 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
505 for (; it != end; ++it) {
506 // Skip escaped braces in the count
511 } else if (*it == '{') {
513 } else if (*it == '}') {
514 if (open_pars == 0) {
515 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
521 if (open_pars != unmatched) {
522 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
525 LYXERR(Debug::DEBUG, "Braces match as expected");
529 /** The class performing a match between a position in the document and the FindAdvOptions.
531 ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
532 ** to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
534 class MatchStringAdv {
536 MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt);
538 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
539 ** constructor as opt.search, under the opt.* options settings.
542 ** If set, then match is searched only against beginning of text starting at cur.
543 ** If unset, then match is searched anywhere in text starting at cur.
546 ** The length of the matching text, or zero if no match was found.
548 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
552 lyx::Buffer const & buf;
554 FindAndReplaceOptions const & opt;
557 /** Normalize a stringified or latexified LyX paragraph.
561 ** <li>if search is not casesensitive, then lowercase the string;
562 ** <li>remove any newline at begin or end of the string;
563 ** <li>replace any newline in the middle of the string with a simple space;
564 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
567 ** @todo Normalization should also expand macros, if the corresponding
568 ** search option was checked.
570 string normalize(docstring const & s) const;
571 // normalized string to search
572 string par_as_string;
573 // regular expression to use for searching
575 // same as regexp, but prefixed with a ".*"
576 boost::regex regexp2;
577 // unmatched open braces in the search string/regexp
579 // number of (.*?) subexpressions added at end of search regexp for closing
580 // environments, math mode, styles, etc...
585 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt)
588 par_as_string = normalize(opt.search);
593 // Remove trailing closure of math, macros and environments, so to catch parts of them.
595 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
596 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
598 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
600 // @todo need to account for open square braces as well ?
601 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
603 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
605 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
611 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
612 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
613 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
615 par_as_string = escape_for_regex(par_as_string);
616 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
617 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
619 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
620 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
621 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
622 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
623 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
624 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
625 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
626 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
630 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
631 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
632 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
633 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
634 // Entered regexp must match at begin of searched string buffer
635 par_as_string = string("\\`") + par_as_string;
636 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
637 regexp = boost::regex(par_as_string);
638 regexp2 = boost::regex(string(".*") + par_as_string);
643 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
645 docstring docstr = stringifyFromForSearch(opt, cur, len);
646 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
647 string str = normalize(docstr);
648 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
651 if (str.substr(0, par_as_string.size()) == par_as_string)
652 return par_as_string.size();
654 size_t pos = str.find(par_as_string);
655 if (pos != string::npos)
656 return par_as_string.size();
659 // Try all possible regexp matches, until one that verifies the braces match test is found
660 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
661 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
662 boost::sregex_iterator re_it_end;
663 for (; re_it != re_it_end; ++re_it) {
664 boost::match_results<string::const_iterator> const & m = *re_it;
665 // Check braces on the segment that matched the entire regexp expression,
666 // plus the last subexpression, if a (.*?) was inserted in the constructor.
667 if (! braces_match(m[0].first, m[0].second, open_braces))
669 // Check braces on segments that matched all (.*?) subexpressions.
670 for (size_t i = 1; i < m.size(); ++i)
671 if (! braces_match(m[i].first, m[i].second))
673 // Exclude from the returned match length any length due to close wildcards added at end of regexp
674 if (close_wildcards == 0)
675 return m[0].second - m[0].first;
677 return m[m.size() - close_wildcards].first - m[0].first;
684 string MatchStringAdv::normalize(docstring const & s) const
687 if (! opt.casesensitive)
688 t = lyx::to_utf8(lowercase(s));
691 // Remove \n at begin
692 while (t.size() > 0 && t[0] == '\n')
695 while (t.size() > 0 && t[t.size() - 1] == '\n')
696 t = t.substr(0, t.size() - 1);
698 // Replace all other \n with spaces
699 while ((pos = t.find("\n")) != string::npos)
700 t.replace(pos, 1, " ");
701 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
702 while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
708 docstring stringifyFromCursor(DocIterator const & cur, int len)
710 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
711 if (cur.inTexted()) {
712 Paragraph const & par = cur.paragraph();
713 // TODO what about searching beyond/across paragraph breaks ?
714 // TODO Try adding a AS_STR_INSERTS as last arg
715 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len;
716 OutputParams runparams(&cur.buffer()->params().encoding());
718 runparams.nice = true;
719 runparams.flavor = OutputParams::LATEX;
720 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
721 // No side effect of file copying and image conversion
722 runparams.dryrun = true;
723 LYXERR(Debug::DEBUG, "Stringifying with cur: " << cur << ", from pos: " << cur.pos() << ", end: " << end);
724 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
725 } else if (cur.inMathed()) {
727 CursorSlice cs = cur.top();
728 MathData md = cs.cell();
729 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
730 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
734 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
738 /** Computes the LaTeX export of buf starting from cur and ending len positions
739 * after cur, if len is positive, or at the paragraph or innermost inset end
743 docstring latexifyFromCursor(DocIterator const & cur, int len)
745 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
746 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
747 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
748 Buffer const & buf = *cur.buffer();
749 LASSERT(buf.isLatex(), /* */);
752 odocstringstream ods;
753 OutputParams runparams(&buf.params().encoding());
754 runparams.nice = false;
755 runparams.flavor = OutputParams::LATEX;
756 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
757 // No side effect of file copying and image conversion
758 runparams.dryrun = true;
760 if (cur.inTexted()) {
761 // @TODO what about searching beyond/across paragraph breaks ?
762 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
763 for (int i = 0; i < cur.pit(); ++i)
765 // ParagraphList::const_iterator pit_end = pit;
767 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
768 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
769 ? pit->size() : cur.pos() + len;
770 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
772 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
773 } else if (cur.inMathed()) {
774 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
775 for (int s = cur.depth() - 1; s >= 0; --s) {
776 CursorSlice const & cs = cur[s];
777 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
779 cs.asInsetMath()->asHullInset()->header_write(ws);
784 CursorSlice const & cs = cur.top();
785 MathData md = cs.cell();
786 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
787 ? md.end() : md.begin() + cs.pos() + len );
788 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
791 // MathData md = cur.cell();
792 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
793 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
794 // MathAtom const & ma = *it;
795 // ma.nucleus()->latex(buf, ods, runparams);
798 // Retrieve the math environment type, and add '$' or '$]'
799 // or others (\end{equation}) accordingly
800 for (int s = cur.depth() - 1; s >= 0; --s) {
801 CursorSlice const & cs = cur[s];
802 InsetMath * inset = cs.asInsetMath();
803 if (inset && inset->asHullInset()) {
805 inset->asHullInset()->footer_write(ws);
809 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
811 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
816 /** Finalize an advanced find operation, advancing the cursor to the innermost
817 ** position that matches, plus computing the length of the matching text to
820 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
822 // Search the foremost position that matches (avoids find of entire math
823 // inset when match at start of it)
825 DocIterator old_cur(cur.buffer());
827 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
831 } while (cur && cur.depth() > d && match(cur) > 0);
833 LASSERT(match(cur) > 0, /* */);
834 LYXERR(Debug::DEBUG, "Ok");
836 // Compute the match length
838 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
839 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
841 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
843 // Length of matched text (different from len param)
844 int old_len = match(cur, len);
846 // Greedy behaviour while matching regexps
847 while ((new_len = match(cur, len + 1)) > old_len) {
850 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
857 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
863 while (cur && !match(cur, -1, false)) {
864 if (cur.pit() < cur.lastpit())
870 for (; cur; cur.forwardPos()) {
872 return findAdvFinalize(cur, match);
874 wrap_answer = frontend::Alert::prompt(
876 _("End of document reached while searching forward\n"
878 "Continue searching from beginning ?"),
879 0, 1, _("&Yes"), _("&No"));
881 cur.push_back(CursorSlice(match.buf.inset()));
882 } while (wrap_answer == 0);
888 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
889 // if (cur.pos() > 0 || cur.depth() > 0)
890 // cur.backwardPos();
891 DocIterator cur_orig(cur);
893 findAdvFinalize(cur_orig, match);
894 // int total = cur.bottom().pit() + 1;
897 // TODO No ! così non va.
898 bool pit_changed = false;
899 while (cur && !match(cur, -1, false)) {
909 if (cur && pit_changed)
910 cur.pos() = cur.lastpos();
911 for (; cur; cur.backwardPos()) {
913 // Find the most backward consecutive match within same paragraph while searching backwards.
917 int len = findAdvFinalize(cur, match);
922 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
923 } while (cur && cur.pit() == pit && match(cur)
924 && (len = findAdvFinalize(cur, match)) > old_len);
927 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
928 LYXERR(Debug::DEBUG, "cur : " << cur);
933 wrap_answer = frontend::Alert::prompt(
935 _("Beginning of document reached while searching backwards\n"
937 "Continue searching from end ?"),
938 0, 1, _("&Yes"), _("&No"));
939 cur = doc_iterator_end(&match.buf);
941 } while (wrap_answer == 0);
945 } // anonym namespace
948 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
949 DocIterator const & cur, int len)
951 if (!opt.ignoreformat)
952 return latexifyFromCursor(cur, len);
954 return stringifyFromCursor(cur, len);
958 lyx::FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
959 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
960 bool regexp, docstring const & replace)
961 : search(search), casesensitive(casesensitive), matchword(matchword),
962 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
963 regexp(regexp), replace(replace)
967 /// Perform a FindAdv operation.
968 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
970 DocIterator cur = bv->cursor();
973 if (opt.search.empty()) {
974 bv->message(_("Search text is empty!"));
977 // if (! bv->buffer()) {
978 // bv->message(_("No open document !"));
983 MatchStringAdv const matchAdv(bv->buffer(), opt);
985 match_len = findForwardAdv(cur, matchAdv);
987 match_len = findBackwardsAdv(cur, matchAdv);
989 // This may only be raised by boost::regex()
990 bv->message(_("Invalid regular expression!"));
994 if (match_len == 0) {
995 bv->message(_("Match not found!"));
999 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
1000 bv->putSelectionAt(cur, match_len, ! opt.forward);
1001 bv->message(_("Match found!"));
1002 if (opt.replace != docstring(from_utf8(LYX_FR_NULL_STRING))) {
1003 dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1010 void findAdv(BufferView * bv, FuncRequest const & ev)
1012 if (!bv || ev.action != LFUN_WORD_FINDADV)
1015 FindAndReplaceOptions opt;
1016 istringstream iss(to_utf8(ev.argument()));
1022 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1024 os << to_utf8(opt.search) << "\nEOSS\n"
1025 << opt.casesensitive << ' '
1026 << opt.matchword << ' '
1027 << opt.forward << ' '
1028 << opt.expandmacros << ' '
1029 << opt.ignoreformat << ' '
1030 << opt.regexp << ' '
1031 << to_utf8(opt.replace) << "\nEOSS\n";
1033 LYXERR(Debug::DEBUG, "built: " << os.str());
1038 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1040 LYXERR(Debug::DEBUG, "parsing");
1044 while (line != "EOSS") {
1048 if (is.eof()) // Tolerate malformed request
1052 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
1053 opt.search = from_utf8(s);
1054 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1055 is.get(); // Waste space before replace string
1058 while (line != "EOSS") {
1062 if (is.eof()) // Tolerate malformed request
1066 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1067 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);
1068 LYXERR(Debug::DEBUG, "replacing with: '" << s << "'");
1069 opt.replace = from_utf8(s);