3 * This file is part of LyX, the document processor.
4 * Licence 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"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
28 #include "OutputParams.h"
29 #include "output_latex.h"
30 #include "Paragraph.h"
31 #include "ParIterator.h"
35 #include "mathed/InsetMath.h"
36 #include "mathed/InsetMathGrid.h"
37 #include "mathed/InsetMathHull.h"
38 #include "mathed/MathStream.h"
40 #include "frontends/alert.h"
42 #include "support/convert.h"
43 #include "support/debug.h"
44 #include "support/docstream.h"
45 #include "support/gettext.h"
46 #include "support/lstrings.h"
48 #include <boost/regex.hpp>
51 using namespace lyx::support;
57 bool parse_bool(docstring & howto)
62 howto = split(howto, var, ' ');
67 class MatchString : public binary_function<Paragraph, pos_type, bool>
70 MatchString(docstring const & str, bool cs, bool mw)
71 : str(str), cs(cs), mw(mw)
74 // returns true if the specified string is at the specified position
75 // del specifies whether deleted strings in ct mode will be considered
76 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
78 return par.find(str, cs, mw, pos, del);
86 // match whole words only
91 bool findForward(DocIterator & cur, MatchString const & match,
94 for (; cur; cur.forwardChar())
96 match(cur.paragraph(), cur.pos(), find_del))
102 bool findBackwards(DocIterator & cur, MatchString const & match,
103 bool find_del = true)
107 if (cur.inTexted() &&
108 match(cur.paragraph(), cur.pos(), find_del))
115 bool findChange(DocIterator & cur)
117 for (; cur; cur.forwardPos())
118 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos()))
124 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
127 frontend::Alert::error(_("Search error"), _("Search string is empty"));
134 bool find(BufferView * bv, docstring const & searchstr,
135 bool cs, bool mw, bool fw, bool find_del = true)
137 if (!searchAllowed(bv, searchstr))
140 DocIterator cur = bv->cursor();
142 MatchString const match(searchstr, cs, mw);
144 bool found = fw ? findForward(cur, match, find_del) :
145 findBackwards(cur, match, find_del);
148 bv->putSelectionAt(cur, searchstr.length(), !fw);
154 int replaceAll(BufferView * bv,
155 docstring const & searchstr, docstring const & replacestr,
158 Buffer & buf = bv->buffer();
160 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
163 MatchString const match(searchstr, cs, mw);
166 int const rsize = replacestr.size();
167 int const ssize = searchstr.size();
170 cur.setCursor(doc_iterator_begin(buf.inset()));
171 while (findForward(cur, match, false)) {
172 // Backup current cursor position and font.
173 pos_type const pos = cur.pos();
174 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
176 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
177 buf.params().trackChanges);
178 cur.paragraph().insert(pos, replacestr, font,
179 Change(buf.params().trackChanges ?
180 Change::INSERTED : Change::UNCHANGED));
181 for (int i = 0; i < rsize + striked; ++i)
187 bv->putSelectionAt(doc_iterator_begin(buf.inset()), 0, false);
194 bool stringSelected(BufferView * bv, docstring const & searchstr,
195 bool cs, bool mw, bool fw)
197 // if nothing selected or selection does not equal search
198 // string search and select next occurance and return
199 docstring const & str1 = searchstr;
200 docstring const str2 = bv->cursor().selectionAsString(false);
201 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
202 find(bv, searchstr, cs, mw, fw);
210 int replace(BufferView * bv, docstring const & searchstr,
211 docstring const & replacestr, bool cs, bool mw, bool fw)
213 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
216 if (!stringSelected(bv, searchstr, cs, mw, fw))
219 Cursor & cur = bv->cursor();
220 cap::replaceSelectionWithString(cur, replacestr, fw);
221 bv->buffer().markDirty();
222 find(bv, searchstr, cs, mw, fw, false);
223 bv->buffer().updateMacros();
224 bv->processUpdateFlags(Update::Force | Update::FitCursor);
232 docstring const find2string(docstring const & search,
233 bool casesensitive, bool matchword, bool forward)
237 << int(casesensitive) << ' '
238 << int(matchword) << ' '
244 docstring const replace2string(docstring const & search, docstring const & replace,
245 bool casesensitive, bool matchword,
246 bool all, bool forward)
251 << int(casesensitive) << ' '
252 << int(matchword) << ' '
259 bool find(BufferView * bv, FuncRequest const & ev)
261 if (!bv || ev.action != LFUN_WORD_FIND)
264 //lyxerr << "find called, cmd: " << ev << endl;
266 // data is of the form
268 // <casesensitive> <matchword> <forward>"
270 docstring howto = split(ev.argument(), search, '\n');
272 bool casesensitive = parse_bool(howto);
273 bool matchword = parse_bool(howto);
274 bool forward = parse_bool(howto);
276 return find(bv, search, casesensitive, matchword, forward);
280 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
282 if (!bv || ev.action != LFUN_WORD_REPLACE)
285 // data is of the form
288 // <casesensitive> <matchword> <all> <forward>"
291 docstring howto = split(ev.argument(), search, '\n');
292 howto = split(howto, rplc, '\n');
294 bool casesensitive = parse_bool(howto);
295 bool matchword = parse_bool(howto);
296 bool all = parse_bool(howto);
297 bool forward = parse_bool(howto);
300 int const replace_count = all
301 ? replaceAll(bv, search, rplc, casesensitive, matchword)
302 : replace(bv, search, rplc, casesensitive, matchword, forward);
304 Buffer & buf = bv->buffer();
305 if (replace_count == 0) {
306 // emit message signal.
307 buf.message(_("String not found!"));
309 if (replace_count == 1) {
310 // emit message signal.
311 buf.message(_("String has been replaced."));
313 docstring str = convert<docstring>(replace_count);
314 str += _(" strings have been replaced.");
315 // emit message signal.
320 // if we have deleted characters, we do not replace at all, but
321 // rather search for the next occurence
322 if (find(bv, search, casesensitive, matchword, forward))
325 bv->message(_("String not found!"));
330 bool findNextChange(BufferView * bv)
332 DocIterator cur = bv->cursor();
334 if (!findChange(cur))
337 bv->cursor().setCursor(cur);
338 bv->cursor().resetAnchor();
340 Change orig_change = cur.paragraph().lookupChange(cur.pos());
342 CursorSlice & tip = cur.top();
343 for (; !tip.at_end(); tip.forwardPos()) {
344 Change change = tip.paragraph().lookupChange(tip.pos());
345 if (change != orig_change)
349 // Now put cursor to end of selection:
350 bv->cursor().setCursor(cur);
351 bv->cursor().setSelection();
358 typedef vector<pair<string, string> > Escapes;
360 /// A map of symbols and their escaped equivalent needed within a regex.
361 Escapes const & get_regexp_escapes()
363 static Escapes escape_map;
364 if (escape_map.empty()) {
365 escape_map.push_back(pair<string, string>("\\", "\\\\"));
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>(".", "\\."));
381 /// A map of lyx escaped strings and their unescaped equivalent.
382 Escapes const & get_lyx_unescapes() {
383 static Escapes escape_map;
384 if (escape_map.empty()) {
385 escape_map.push_back(pair<string, string>("{*}", "*"));
386 escape_map.push_back(pair<string, string>("{[}", "["));
387 escape_map.push_back(pair<string, string>("\\$", "$"));
388 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
389 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
390 escape_map.push_back(pair<string, string>("\\sim ", "~"));
391 escape_map.push_back(pair<string, string>("\\^", "^"));
396 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
397 ** the found occurrence were escaped.
399 string apply_escapes(string s, Escapes const & escape_map)
401 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
402 Escapes::const_iterator it;
403 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
404 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
405 unsigned int pos = 0;
406 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
407 s.replace(pos, it->first.length(), it->second);
408 // LYXERR(Debug::DEBUG, "After escape: " << s);
409 pos += it->second.length();
410 // LYXERR(Debug::DEBUG, "pos: " << pos);
413 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
417 /** Return the position of the closing brace matching the open one at s[pos],
418 ** or s.size() if not found.
420 size_t find_matching_brace(string const & s, size_t pos)
422 BOOST_ASSERT(s[pos] == '{');
424 for (++pos; pos < s.size(); ++pos) {
427 else if (s[pos] == '{')
429 else if (s[pos] == '}') {
431 if (open_braces == 0)
438 /// Within \regex{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
439 string escape_for_regex(string s)
442 while (pos < s.size()) {
443 size_t new_pos = s.find("\\regexp{", pos);
444 if (new_pos == string::npos)
446 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
447 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
448 LYXERR(Debug::DEBUG, "t : " << t);
449 t = apply_escapes(t, get_regexp_escapes());
450 s.replace(pos, new_pos - pos, t);
451 new_pos = pos + t.size();
452 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
453 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
454 if (new_pos == s.size())
456 size_t end_pos = find_matching_brace(s, new_pos + 7);
457 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
458 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
459 LYXERR(Debug::DEBUG, "t : " << t);
460 if (end_pos == s.size()) {
461 s.replace(new_pos, end_pos - new_pos, t);
463 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
466 s.replace(new_pos, end_pos + 1 - new_pos, t);
467 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
468 pos = new_pos + t.size();
469 LYXERR(Debug::DEBUG, "pos: " << pos);
474 /// Wrapper for boost::regex_replace with simpler interface
475 bool regex_replace(string const & s, string & t, string const & searchstr,
476 string const & replacestr)
478 boost::regex e(searchstr);
480 ostream_iterator<char, char> it(oss);
481 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
482 // tolerate t and s be references to the same variable
483 bool rv = (s != oss.str());
488 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
490 ** Verify that closed braces exactly match open braces. This avoids that, for example,
491 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
494 ** Number of open braces that must remain open at the end for the verification to succeed.
496 bool braces_match(string::const_iterator const & beg,
497 string::const_iterator const & end, int unmatched = 0)
500 string::const_iterator it = beg;
501 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
502 for (; it != end; ++it) {
503 // Skip escaped braces in the count
508 } else if (*it == '{') {
510 } else if (*it == '}') {
511 if (open_pars == 0) {
512 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
518 if (open_pars != unmatched) {
519 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
522 LYXERR(Debug::DEBUG, "Braces match as expected");
526 /** The class performing a match between a position in the document and the FindAdvOptions.
528 ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
529 ** to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
531 class MatchStringAdv {
533 MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt);
535 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
536 ** constructor as opt.search, under the opt.* options settings.
539 ** The length of the matching text, or zero if no match was found.
541 int operator()(DocIterator const & cur, int len = -1) const;
545 lyx::Buffer const & buf;
547 FindAdvOptions const & opt;
550 /** Normalize a stringified or latexified LyX paragraph.
554 ** <li>if search is not casesensitive, then lowercase the string;
555 ** <li>remove any newline at begin or end of the string;
556 ** <li>replace any newline in the middle of the string with a simple space;
557 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
560 ** @todo Normalization should also expand macros, if the corresponding
561 ** search option was checked.
563 string normalize(docstring const & s) const;
564 // normalized string to search
565 string par_as_string;
566 // regular expression to use for searching
568 // unmatched open braces in the search string/regexp
570 // number of (.*?) subexpressions added at end of search regexp for closing
571 // environments, math mode, styles, etc...
576 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt)
579 par_as_string = normalize(opt.search);
584 // Remove trailing closure of math, macros and environments, so to catch parts of them.
586 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
587 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
589 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
591 // @todo need to account for open square braces as well ?
592 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
594 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
596 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
602 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
603 BOOST_ASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces));
604 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
606 par_as_string = escape_for_regex(par_as_string);
607 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
608 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
610 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
611 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
612 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
613 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
614 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
615 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
616 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
617 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
621 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
622 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
623 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
624 BOOST_ASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces));
625 // Entered regexp must match at begin of searched string buffer
626 par_as_string = string("\\`") + par_as_string;
627 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
628 regexp = boost::regex(par_as_string);
632 int MatchStringAdv::operator()(DocIterator const & cur, int len) const
634 docstring docstr = stringifyFromForSearch(opt, buf, cur, len);
635 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
636 string str = normalize(docstr);
637 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
639 if (str.substr(0, par_as_string.size()) == par_as_string)
640 return par_as_string.size();
642 // Try all possible regexp matches, until one that verifies the braces match test is found
643 boost::sregex_iterator re_it(str.begin(), str.end(), regexp);
644 boost::sregex_iterator re_it_end;
645 for (; re_it != re_it_end; ++re_it) {
646 boost::match_results<string::const_iterator> const & m = *re_it;
647 // Check braces on the segment that matched the entire regexp expression,
648 // plus the last subexpression, if a (.*?) was inserted in the constructor.
649 if (! braces_match(m[0].first, m[0].second, open_braces))
651 // Check braces on segments that matched all (.*?) subexpressions.
652 for (size_t i = 1; i < m.size(); ++i)
653 if (! braces_match(m[i].first, m[i].second))
655 // Exclude from the returned match length any length due to close wildcards added at end of regexp
656 if (close_wildcards == 0)
657 return m[0].second - m[0].first;
659 return m[m.size() - close_wildcards].first - m[0].first;
666 string MatchStringAdv::normalize(docstring const & s) const
669 if (! opt.casesensitive)
670 t = lyx::to_utf8(lowercase(s));
673 // Remove \n at begin
674 while (t.size() > 0 && t[0] == '\n')
677 while (t.size() > 0 && t[t.size() - 1] == '\n')
678 t = t.substr(0, t.size() - 1);
680 // Replace all other \n with spaces
681 while ((pos = t.find("\n")) != string::npos)
682 t.replace(pos, 1, " ");
683 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
684 while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
690 docstring stringifyFromCursor(DocIterator const & cur, int len)
692 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
693 if (cur.inTexted()) {
694 Paragraph const & par = cur.paragraph();
695 // TODO what about searching beyond/across paragraph breaks ?
696 // TODO Try adding a AS_STR_INSERTS as last arg
697 return par.asString(cur.pos(), ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len, AS_STR_INSETS);
698 } else if (cur.inMathed()) {
700 CursorSlice cs = cur.top();
701 MathData md = cs.cell();
702 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
703 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
707 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
711 /** Computes the LaTeX export of buf starting from cur and ending len positions after cur,
712 ** if len is positive, or at the paragraph or innermost inset end if len is -1.
714 docstring latexifyFromCursor(Buffer const & buf, DocIterator const & cur, int len)
716 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
717 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
718 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
719 BOOST_ASSERT(buf.isLatex());
722 odocstringstream ods;
723 OutputParams runparams(&buf.params().encoding());
724 runparams.nice = false;
725 runparams.flavor = OutputParams::LATEX;
726 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
727 // No side effect of file copying and image conversion
728 runparams.dryrun = true;
730 if (cur.inTexted()) {
731 // @TODO what about searching beyond/across paragraph breaks ?
732 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
733 for (int i = 0; i < cur.pit(); ++i)
735 // ParagraphList::const_iterator pit_end = pit;
737 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
738 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
739 cur.pos(), ( len == -1 || cur.pos() + len > int(pit->size()) ) ? -1 : cur.pos() + len);
740 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
741 } else if (cur.inMathed()) {
742 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
743 for (int s = cur.depth() - 1; s >= 0; --s) {
744 CursorSlice const & cs = cur[s];
745 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
747 cs.asInsetMath()->asHullInset()->header_write(ws);
752 CursorSlice const & cs = cur.top();
753 MathData md = cs.cell();
754 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
755 ? md.end() : md.begin() + cs.pos() + len );
756 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
759 // MathData md = cur.cell();
760 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
761 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
762 // MathAtom const & ma = *it;
763 // ma.nucleus()->latex(buf, ods, runparams);
766 // Retrieve the math environment type, and add '$' or '$]' or others (\end{equation}) accordingly
767 for (int s = cur.depth() - 1; s >= 0; --s) {
768 CursorSlice const & cs = cur[s];
769 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
771 cs.asInsetMath()->asHullInset()->footer_write(ws);
775 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
777 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
782 /** Finalize an advanced find operation, advancing the cursor to the innermost
783 ** position that matches, plus computing the length of the matching text to
786 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
788 // Search the foremost position that matches (avoids find of entire math inset when match at start of it)
792 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
796 } while (cur && cur.depth() > d && match(cur) > 0);
798 BOOST_ASSERT(match(cur) > 0);
799 LYXERR(Debug::DEBUG, "Ok");
801 // Compute the match length
803 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
804 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
806 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
808 int old_len = match(cur, len); // Length of matched text (different from len param)
810 // Greedy behaviour while matching regexps
811 while ((new_len = match(cur, len + 1)) > old_len) {
814 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
820 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
824 for (; cur; cur.forwardPos()) {
825 // odocstringstream ods;
826 // ods << _("Searching ... ") << (cur.bottom().lastpit() - cur.bottom().pit()) * 100 / total;
827 // cur.message(ods.str());
829 return findAdvFinalize(cur, match);
835 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
836 // if (cur.pos() > 0 || cur.depth() > 0)
837 // cur.backwardPos();
838 DocIterator cur_orig(cur);
840 findAdvFinalize(cur_orig, match);
841 // int total = cur.bottom().pit() + 1;
842 for (; cur; cur.backwardPos()) {
843 // odocstringstream ods;
844 // ods << _("Searching ... ") << (total - cur.bottom().pit()) * 100 / total;
845 // cur.message(ods.str());
847 // Find the most backward consecutive match within same paragraph while searching backwards.
851 int len = findAdvFinalize(cur, match);
856 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
857 } while (cur && cur.pit() == pit && match(cur)
858 && (len = findAdvFinalize(cur, match)) > old_len);
861 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
862 LYXERR(Debug::DEBUG, "cur : " << cur);
870 } // anonym namespace
873 docstring stringifyFromForSearch(FindAdvOptions const & opt, Buffer const & buf,
874 DocIterator const & cur, int len)
876 if (! opt.ignoreformat)
877 return latexifyFromCursor(buf, cur, len);
879 return stringifyFromCursor(cur, len);
883 lyx::FindAdvOptions::FindAdvOptions(docstring const & search, bool casesensitive,
884 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
886 : search(search), casesensitive(casesensitive), matchword(matchword),
887 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
892 /// Perform a FindAdv operation.
893 bool findAdv(BufferView * bv, FindAdvOptions const & opt)
895 DocIterator cur = bv->cursor();
898 if (opt.search.empty()) {
899 bv->message(_("Search text is empty !"));
902 // if (! bv->buffer()) {
903 // bv->message(_("No open document !"));
908 MatchStringAdv const matchAdv(bv->buffer(), opt);
910 match_len = findForwardAdv(cur, matchAdv);
912 match_len = findBackwardsAdv(cur, matchAdv);
914 // This may only be raised by boost::regex()
915 bv->message(_("Invalid regular expression !"));
919 if (match_len == 0) {
920 bv->message(_("Match not found !"));
924 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
925 bv->putSelectionAt(cur, match_len, ! opt.forward);
926 bv->message(_("Match found !"));
933 void findAdv(BufferView * bv, FuncRequest const & ev)
935 if (!bv || ev.action != LFUN_WORD_FINDADV)
939 istringstream iss(to_utf8(ev.argument()));
945 ostringstream & operator<<(ostringstream & os, lyx::FindAdvOptions const & opt)
947 os << to_utf8(opt.search) << "\nEOSS\n"
948 << opt.casesensitive << ' '
949 << opt.matchword << ' '
950 << opt.forward << ' '
951 << opt.expandmacros << ' '
952 << opt.ignoreformat << ' '
955 LYXERR(Debug::DEBUG, "built: " << os.str());
960 istringstream & operator>>(istringstream & is, lyx::FindAdvOptions & opt)
962 LYXERR(Debug::DEBUG, "parsing");
966 while (line != "EOSS") {
970 if (is.eof()) // Tolerate malformed request
974 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
975 opt.search = from_utf8(s);
976 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
977 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
978 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);