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"
34 #include "mathed/InsetMath.h"
35 #include "mathed/InsetMathGrid.h"
36 #include "mathed/InsetMathHull.h"
37 #include "mathed/MathStream.h"
39 #include "frontends/alert.h"
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/docstream.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46 #include "support/lassert.h"
48 #include <boost/regex.hpp>
49 #include <boost/next_prior.hpp>
52 using namespace lyx::support;
58 bool parse_bool(docstring & howto)
63 howto = split(howto, var, ' ');
68 class MatchString : public binary_function<Paragraph, pos_type, bool>
71 MatchString(docstring const & str, bool cs, bool mw)
72 : str(str), cs(cs), mw(mw)
75 // returns true if the specified string is at the specified position
76 // del specifies whether deleted strings in ct mode will be considered
77 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
79 return par.find(str, cs, mw, pos, del);
87 // match whole words only
92 bool findForward(DocIterator & cur, MatchString const & match,
95 for (; cur; cur.forwardChar())
97 match(cur.paragraph(), cur.pos(), find_del))
103 bool findBackwards(DocIterator & cur, MatchString const & match,
104 bool find_del = true)
108 if (cur.inTexted() &&
109 match(cur.paragraph(), cur.pos(), find_del))
116 bool findChange(DocIterator & cur)
118 for (; cur; cur.forwardPos())
119 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos()))
125 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
128 frontend::Alert::error(_("Search error"), _("Search string is empty"));
135 bool find(BufferView * bv, docstring const & searchstr,
136 bool cs, bool mw, bool fw, bool find_del = true)
138 if (!searchAllowed(bv, searchstr))
141 DocIterator cur = bv->cursor();
143 MatchString const match(searchstr, cs, mw);
145 bool found = fw ? findForward(cur, match, find_del) :
146 findBackwards(cur, match, find_del);
149 bv->putSelectionAt(cur, searchstr.length(), !fw);
155 int replaceAll(BufferView * bv,
156 docstring const & searchstr, docstring const & replacestr,
159 Buffer & buf = bv->buffer();
161 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
164 MatchString const match(searchstr, cs, mw);
167 int const rsize = replacestr.size();
168 int const ssize = searchstr.size();
171 cur.setCursor(doc_iterator_begin(&buf));
172 while (findForward(cur, match, false)) {
173 // Backup current cursor position and font.
174 pos_type const pos = cur.pos();
175 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
177 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
178 buf.params().trackChanges);
179 cur.paragraph().insert(pos, replacestr, font,
180 Change(buf.params().trackChanges ?
181 Change::INSERTED : Change::UNCHANGED));
182 for (int i = 0; i < rsize + striked; ++i)
188 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
195 bool stringSelected(BufferView * bv, docstring const & searchstr,
196 bool cs, bool mw, bool fw)
198 // if nothing selected or selection does not equal search
199 // string search and select next occurance and return
200 docstring const & str1 = searchstr;
201 docstring const str2 = bv->cursor().selectionAsString(false);
202 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
203 find(bv, searchstr, cs, mw, fw);
211 int replace(BufferView * bv, docstring const & searchstr,
212 docstring const & replacestr, bool cs, bool mw, bool fw)
214 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
217 if (!stringSelected(bv, searchstr, cs, mw, fw))
220 Cursor & cur = bv->cursor();
221 cap::replaceSelectionWithString(cur, replacestr, fw);
222 bv->buffer().markDirty();
223 find(bv, searchstr, cs, mw, fw, false);
224 bv->buffer().updateMacros();
225 bv->processUpdateFlags(Update::Force | Update::FitCursor);
233 docstring const find2string(docstring const & search,
234 bool casesensitive, bool matchword, bool forward)
238 << int(casesensitive) << ' '
239 << int(matchword) << ' '
245 docstring const replace2string(docstring const & search, docstring const & replace,
246 bool casesensitive, bool matchword,
247 bool all, bool forward)
252 << int(casesensitive) << ' '
253 << int(matchword) << ' '
260 bool find(BufferView * bv, FuncRequest const & ev)
262 if (!bv || ev.action != LFUN_WORD_FIND)
265 //lyxerr << "find called, cmd: " << ev << endl;
267 // data is of the form
269 // <casesensitive> <matchword> <forward>"
271 docstring howto = split(ev.argument(), search, '\n');
273 bool casesensitive = parse_bool(howto);
274 bool matchword = parse_bool(howto);
275 bool forward = parse_bool(howto);
277 return find(bv, search, casesensitive, matchword, forward);
281 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
283 if (!bv || ev.action != LFUN_WORD_REPLACE)
286 // data is of the form
289 // <casesensitive> <matchword> <all> <forward>"
292 docstring howto = split(ev.argument(), search, '\n');
293 howto = split(howto, rplc, '\n');
295 bool casesensitive = parse_bool(howto);
296 bool matchword = parse_bool(howto);
297 bool all = parse_bool(howto);
298 bool forward = parse_bool(howto);
301 int const replace_count = all
302 ? replaceAll(bv, search, rplc, casesensitive, matchword)
303 : replace(bv, search, rplc, casesensitive, matchword, forward);
305 Buffer & buf = bv->buffer();
306 if (replace_count == 0) {
307 // emit message signal.
308 buf.message(_("String not found!"));
310 if (replace_count == 1) {
311 // emit message signal.
312 buf.message(_("String has been replaced."));
314 docstring str = convert<docstring>(replace_count);
315 str += _(" strings have been replaced.");
316 // emit message signal.
321 // if we have deleted characters, we do not replace at all, but
322 // rather search for the next occurence
323 if (find(bv, search, casesensitive, matchword, forward))
326 bv->message(_("String not found!"));
331 bool findNextChange(BufferView * bv)
333 DocIterator cur = bv->cursor();
335 if (!findChange(cur))
338 bv->cursor().setCursor(cur);
339 bv->cursor().resetAnchor();
341 Change orig_change = cur.paragraph().lookupChange(cur.pos());
343 CursorSlice & tip = cur.top();
344 for (; !tip.at_end(); tip.forwardPos()) {
345 Change change = tip.paragraph().lookupChange(tip.pos());
346 if (change != orig_change)
350 // Now put cursor to end of selection:
351 bv->cursor().setCursor(cur);
352 bv->cursor().setSelection();
359 typedef vector<pair<string, string> > Escapes;
361 /// A map of symbols and their escaped equivalent needed within a regex.
362 Escapes const & get_regexp_escapes()
364 static Escapes escape_map;
365 if (escape_map.empty()) {
366 escape_map.push_back(pair<string, string>("\\", "\\\\"));
367 escape_map.push_back(pair<string, string>("^", "\\^"));
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>(".", "\\."));
382 /// A map of lyx escaped strings and their unescaped equivalent.
383 Escapes const & get_lyx_unescapes() {
384 static Escapes escape_map;
385 if (escape_map.empty()) {
386 escape_map.push_back(pair<string, string>("{*}", "*"));
387 escape_map.push_back(pair<string, string>("{[}", "["));
388 escape_map.push_back(pair<string, string>("\\$", "$"));
389 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
390 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
391 escape_map.push_back(pair<string, string>("\\sim ", "~"));
392 escape_map.push_back(pair<string, string>("\\^", "^"));
397 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
398 ** the found occurrence were escaped.
400 string apply_escapes(string s, Escapes const & escape_map)
402 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
403 Escapes::const_iterator it;
404 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
405 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
406 unsigned int pos = 0;
407 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
408 s.replace(pos, it->first.length(), it->second);
409 // LYXERR(Debug::DEBUG, "After escape: " << s);
410 pos += it->second.length();
411 // LYXERR(Debug::DEBUG, "pos: " << pos);
414 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
418 /** Return the position of the closing brace matching the open one at s[pos],
419 ** or s.size() if not found.
421 size_t find_matching_brace(string const & s, size_t pos)
423 LASSERT(s[pos] == '{', /* */);
425 for (++pos; pos < s.size(); ++pos) {
428 else if (s[pos] == '{')
430 else if (s[pos] == '}') {
432 if (open_braces == 0)
439 /// Within \regex{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
440 string escape_for_regex(string s)
443 while (pos < s.size()) {
444 size_t new_pos = s.find("\\regexp{", pos);
445 if (new_pos == string::npos)
447 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
448 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
449 LYXERR(Debug::DEBUG, "t : " << t);
450 t = apply_escapes(t, get_regexp_escapes());
451 s.replace(pos, new_pos - pos, t);
452 new_pos = pos + t.size();
453 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
454 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
455 if (new_pos == s.size())
457 size_t end_pos = find_matching_brace(s, new_pos + 7);
458 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
459 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
460 LYXERR(Debug::DEBUG, "t : " << t);
461 if (end_pos == s.size()) {
462 s.replace(new_pos, end_pos - new_pos, t);
464 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
467 s.replace(new_pos, end_pos + 1 - new_pos, t);
468 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
469 pos = new_pos + t.size();
470 LYXERR(Debug::DEBUG, "pos: " << pos);
475 /// Wrapper for boost::regex_replace with simpler interface
476 bool regex_replace(string const & s, string & t, string const & searchstr,
477 string const & replacestr)
479 boost::regex e(searchstr);
481 ostream_iterator<char, char> it(oss);
482 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
483 // tolerate t and s be references to the same variable
484 bool rv = (s != oss.str());
489 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
491 ** Verify that closed braces exactly match open braces. This avoids that, for example,
492 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
495 ** Number of open braces that must remain open at the end for the verification to succeed.
497 bool braces_match(string::const_iterator const & beg,
498 string::const_iterator const & end, int unmatched = 0)
501 string::const_iterator it = beg;
502 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
503 for (; it != end; ++it) {
504 // Skip escaped braces in the count
509 } else if (*it == '{') {
511 } else if (*it == '}') {
512 if (open_pars == 0) {
513 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
519 if (open_pars != unmatched) {
520 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
523 LYXERR(Debug::DEBUG, "Braces match as expected");
527 /** The class performing a match between a position in the document and the FindAdvOptions.
529 ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
530 ** to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
532 class MatchStringAdv {
534 MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt);
536 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
537 ** constructor as opt.search, under the opt.* options settings.
540 ** If set, then match is searched only against beginning of text starting at cur.
541 ** If unset, then match is searched anywhere in text starting at cur.
544 ** The length of the matching text, or zero if no match was found.
546 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
550 lyx::Buffer const & buf;
552 FindAdvOptions const & opt;
555 /** Normalize a stringified or latexified LyX paragraph.
559 ** <li>if search is not casesensitive, then lowercase the string;
560 ** <li>remove any newline at begin or end of the string;
561 ** <li>replace any newline in the middle of the string with a simple space;
562 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
565 ** @todo Normalization should also expand macros, if the corresponding
566 ** search option was checked.
568 string normalize(docstring const & s) const;
569 // normalized string to search
570 string par_as_string;
571 // regular expression to use for searching
573 // same as regexp, but prefixed with a ".*"
574 boost::regex regexp2;
575 // unmatched open braces in the search string/regexp
577 // number of (.*?) subexpressions added at end of search regexp for closing
578 // environments, math mode, styles, etc...
583 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt)
586 par_as_string = normalize(opt.search);
591 // Remove trailing closure of math, macros and environments, so to catch parts of them.
593 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
594 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
596 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
598 // @todo need to account for open square braces as well ?
599 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
601 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
603 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
609 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
610 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
611 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
613 par_as_string = escape_for_regex(par_as_string);
614 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
615 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
617 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
618 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
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 '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
622 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
623 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
624 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
628 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
629 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
630 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
631 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
632 // Entered regexp must match at begin of searched string buffer
633 par_as_string = string("\\`") + par_as_string;
634 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
635 regexp = boost::regex(par_as_string);
636 regexp2 = boost::regex(string(".*") + par_as_string);
641 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
643 docstring docstr = stringifyFromForSearch(opt, cur, len);
644 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
645 string str = normalize(docstr);
646 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
649 if (str.substr(0, par_as_string.size()) == par_as_string)
650 return par_as_string.size();
652 size_t pos = str.find(par_as_string);
653 if (pos != string::npos)
654 return par_as_string.size();
657 // Try all possible regexp matches, until one that verifies the braces match test is found
658 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
659 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
660 boost::sregex_iterator re_it_end;
661 for (; re_it != re_it_end; ++re_it) {
662 boost::match_results<string::const_iterator> const & m = *re_it;
663 // Check braces on the segment that matched the entire regexp expression,
664 // plus the last subexpression, if a (.*?) was inserted in the constructor.
665 if (! braces_match(m[0].first, m[0].second, open_braces))
667 // Check braces on segments that matched all (.*?) subexpressions.
668 for (size_t i = 1; i < m.size(); ++i)
669 if (! braces_match(m[i].first, m[i].second))
671 // Exclude from the returned match length any length due to close wildcards added at end of regexp
672 if (close_wildcards == 0)
673 return m[0].second - m[0].first;
675 return m[m.size() - close_wildcards].first - m[0].first;
682 string MatchStringAdv::normalize(docstring const & s) const
685 if (! opt.casesensitive)
686 t = lyx::to_utf8(lowercase(s));
689 // Remove \n at begin
690 while (t.size() > 0 && t[0] == '\n')
693 while (t.size() > 0 && t[t.size() - 1] == '\n')
694 t = t.substr(0, t.size() - 1);
696 // Replace all other \n with spaces
697 while ((pos = t.find("\n")) != string::npos)
698 t.replace(pos, 1, " ");
699 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
700 while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
706 docstring stringifyFromCursor(DocIterator const & cur, int len)
708 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
709 if (cur.inTexted()) {
710 Paragraph const & par = cur.paragraph();
711 // TODO what about searching beyond/across paragraph breaks ?
712 // TODO Try adding a AS_STR_INSERTS as last arg
713 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len;
714 OutputParams runparams(&cur.buffer()->params().encoding());
716 runparams.nice = true;
717 runparams.flavor = OutputParams::LATEX;
718 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
719 // No side effect of file copying and image conversion
720 runparams.dryrun = true;
721 LYXERR(Debug::DEBUG, "Stringifying with cur: " << cur << ", from pos: " << cur.pos() << ", end: " << end);
722 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
723 } else if (cur.inMathed()) {
725 CursorSlice cs = cur.top();
726 MathData md = cs.cell();
727 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
728 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
732 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
736 /** Computes the LaTeX export of buf starting from cur and ending len positions
737 * after cur, if len is positive, or at the paragraph or innermost inset end
741 docstring latexifyFromCursor(DocIterator const & cur, int len)
743 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
744 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
745 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
746 Buffer const & buf = *cur.buffer();
747 LASSERT(buf.isLatex(), /* */);
750 odocstringstream ods;
751 OutputParams runparams(&buf.params().encoding());
752 runparams.nice = false;
753 runparams.flavor = OutputParams::LATEX;
754 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
755 // No side effect of file copying and image conversion
756 runparams.dryrun = true;
758 if (cur.inTexted()) {
759 // @TODO what about searching beyond/across paragraph breaks ?
760 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
761 for (int i = 0; i < cur.pit(); ++i)
763 // ParagraphList::const_iterator pit_end = pit;
765 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
766 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
767 ? pit->size() : cur.pos() + len;
768 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
770 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
771 } else if (cur.inMathed()) {
772 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
773 for (int s = cur.depth() - 1; s >= 0; --s) {
774 CursorSlice const & cs = cur[s];
775 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
777 cs.asInsetMath()->asHullInset()->header_write(ws);
782 CursorSlice const & cs = cur.top();
783 MathData md = cs.cell();
784 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
785 ? md.end() : md.begin() + cs.pos() + len );
786 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
789 // MathData md = cur.cell();
790 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
791 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
792 // MathAtom const & ma = *it;
793 // ma.nucleus()->latex(buf, ods, runparams);
796 // Retrieve the math environment type, and add '$' or '$]'
797 // or others (\end{equation}) accordingly
798 for (int s = cur.depth() - 1; s >= 0; --s) {
799 CursorSlice const & cs = cur[s];
800 InsetMath * inset = cs.asInsetMath();
801 if (inset && inset->asHullInset()) {
803 inset->asHullInset()->footer_write(ws);
807 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
809 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
814 /** Finalize an advanced find operation, advancing the cursor to the innermost
815 ** position that matches, plus computing the length of the matching text to
818 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
820 // Search the foremost position that matches (avoids find of entire math
821 // inset when match at start of it)
823 DocIterator old_cur(cur.buffer());
825 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
829 } while (cur && cur.depth() > d && match(cur) > 0);
831 LASSERT(match(cur) > 0, /* */);
832 LYXERR(Debug::DEBUG, "Ok");
834 // Compute the match length
836 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
837 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
839 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
841 // Length of matched text (different from len param)
842 int old_len = match(cur, len);
844 // Greedy behaviour while matching regexps
845 while ((new_len = match(cur, len + 1)) > old_len) {
848 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
855 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
861 while (cur && !match(cur, -1, false)) {
862 if (cur.pit() < cur.lastpit())
868 for (; cur; cur.forwardPos()) {
870 return findAdvFinalize(cur, match);
872 wrap_answer = frontend::Alert::prompt(
874 _("End of document reached while searching forward\n"
876 "Continue searching from beginning ?"),
877 0, 1, _("&Yes"), _("&No"));
879 cur.push_back(CursorSlice(match.buf.inset()));
880 } while (wrap_answer == 0);
886 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
887 // if (cur.pos() > 0 || cur.depth() > 0)
888 // cur.backwardPos();
889 DocIterator cur_orig(cur);
891 findAdvFinalize(cur_orig, match);
892 // int total = cur.bottom().pit() + 1;
895 // TODO No ! così non va.
896 bool pit_changed = false;
897 while (cur && !match(cur, -1, false)) {
907 if (cur && pit_changed)
908 cur.pos() = cur.lastpos();
909 for (; cur; cur.backwardPos()) {
911 // Find the most backward consecutive match within same paragraph while searching backwards.
915 int len = findAdvFinalize(cur, match);
920 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
921 } while (cur && cur.pit() == pit && match(cur)
922 && (len = findAdvFinalize(cur, match)) > old_len);
925 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
926 LYXERR(Debug::DEBUG, "cur : " << cur);
931 wrap_answer = frontend::Alert::prompt(
933 _("Beginning of document reached while searching backwards\n"
935 "Continue searching from end ?"),
936 0, 1, _("&Yes"), _("&No"));
937 cur = doc_iterator_end(&match.buf);
939 } while (wrap_answer == 0);
943 } // anonym namespace
946 docstring stringifyFromForSearch(FindAdvOptions const & opt,
947 DocIterator const & cur, int len)
949 if (!opt.ignoreformat)
950 return latexifyFromCursor(cur, len);
952 return stringifyFromCursor(cur, len);
956 lyx::FindAdvOptions::FindAdvOptions(docstring const & search, bool casesensitive,
957 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
959 : search(search), casesensitive(casesensitive), matchword(matchword),
960 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
965 /// Perform a FindAdv operation.
966 bool findAdv(BufferView * bv, FindAdvOptions const & opt)
968 DocIterator cur = bv->cursor();
971 if (opt.search.empty()) {
972 bv->message(_("Search text is empty!"));
975 // if (! bv->buffer()) {
976 // bv->message(_("No open document !"));
981 MatchStringAdv const matchAdv(bv->buffer(), opt);
983 match_len = findForwardAdv(cur, matchAdv);
985 match_len = findBackwardsAdv(cur, matchAdv);
987 // This may only be raised by boost::regex()
988 bv->message(_("Invalid regular expression!"));
992 if (match_len == 0) {
993 bv->message(_("Match not found!"));
997 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
998 bv->putSelectionAt(cur, match_len, ! opt.forward);
999 bv->message(_("Match found!"));
1006 void findAdv(BufferView * bv, FuncRequest const & ev)
1008 if (!bv || ev.action != LFUN_WORD_FINDADV)
1012 istringstream iss(to_utf8(ev.argument()));
1018 ostringstream & operator<<(ostringstream & os, lyx::FindAdvOptions const & opt)
1020 os << to_utf8(opt.search) << "\nEOSS\n"
1021 << opt.casesensitive << ' '
1022 << opt.matchword << ' '
1023 << opt.forward << ' '
1024 << opt.expandmacros << ' '
1025 << opt.ignoreformat << ' '
1028 LYXERR(Debug::DEBUG, "built: " << os.str());
1033 istringstream & operator>>(istringstream & is, lyx::FindAdvOptions & opt)
1035 LYXERR(Debug::DEBUG, "parsing");
1039 while (line != "EOSS") {
1043 if (is.eof()) // Tolerate malformed request
1047 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
1048 opt.search = from_utf8(s);
1049 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1050 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1051 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);