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"
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"
47 #include <boost/regex.hpp>
50 using namespace lyx::support;
56 bool parse_bool(docstring & howto)
61 howto = split(howto, var, ' ');
66 class MatchString : public binary_function<Paragraph, pos_type, bool>
69 MatchString(docstring const & str, bool cs, bool mw)
70 : str(str), cs(cs), mw(mw)
73 // returns true if the specified string is at the specified position
74 // del specifies whether deleted strings in ct mode will be considered
75 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
77 return par.find(str, cs, mw, pos, del);
85 // match whole words only
90 bool findForward(DocIterator & cur, MatchString const & match,
93 for (; cur; cur.forwardChar())
95 match(cur.paragraph(), cur.pos(), find_del))
101 bool findBackwards(DocIterator & cur, MatchString const & match,
102 bool find_del = true)
106 if (cur.inTexted() &&
107 match(cur.paragraph(), cur.pos(), find_del))
114 bool findChange(DocIterator & cur)
116 for (; cur; cur.forwardPos())
117 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos()))
123 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
126 frontend::Alert::error(_("Search error"), _("Search string is empty"));
133 bool find(BufferView * bv, docstring const & searchstr,
134 bool cs, bool mw, bool fw, bool find_del = true)
136 if (!searchAllowed(bv, searchstr))
139 DocIterator cur = bv->cursor();
141 MatchString const match(searchstr, cs, mw);
143 bool found = fw ? findForward(cur, match, find_del) :
144 findBackwards(cur, match, find_del);
147 bv->putSelectionAt(cur, searchstr.length(), !fw);
153 int replaceAll(BufferView * bv,
154 docstring const & searchstr, docstring const & replacestr,
157 Buffer & buf = bv->buffer();
159 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
162 MatchString const match(searchstr, cs, mw);
165 int const rsize = replacestr.size();
166 int const ssize = searchstr.size();
169 cur.setCursor(doc_iterator_begin(buf.inset()));
170 while (findForward(cur, match, false)) {
171 // Backup current cursor position and font.
172 pos_type const pos = cur.pos();
173 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
175 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
176 buf.params().trackChanges);
177 cur.paragraph().insert(pos, replacestr, font,
178 Change(buf.params().trackChanges ?
179 Change::INSERTED : Change::UNCHANGED));
180 for (int i = 0; i < rsize + striked; ++i)
186 bv->putSelectionAt(doc_iterator_begin(buf.inset()), 0, false);
193 bool stringSelected(BufferView * bv, docstring const & searchstr,
194 bool cs, bool mw, bool fw)
196 // if nothing selected or selection does not equal search
197 // string search and select next occurance and return
198 docstring const & str1 = searchstr;
199 docstring const str2 = bv->cursor().selectionAsString(false);
200 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
201 find(bv, searchstr, cs, mw, fw);
209 int replace(BufferView * bv, docstring const & searchstr,
210 docstring const & replacestr, bool cs, bool mw, bool fw)
212 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
215 if (!stringSelected(bv, searchstr, cs, mw, fw))
218 Cursor & cur = bv->cursor();
219 cap::replaceSelectionWithString(cur, replacestr, fw);
220 bv->buffer().markDirty();
221 find(bv, searchstr, cs, mw, fw, false);
222 bv->buffer().updateMacros();
223 bv->processUpdateFlags(Update::Force | Update::FitCursor);
231 docstring const find2string(docstring const & search,
232 bool casesensitive, bool matchword, bool forward)
236 << int(casesensitive) << ' '
237 << int(matchword) << ' '
243 docstring const replace2string(docstring const & search, docstring const & replace,
244 bool casesensitive, bool matchword,
245 bool all, bool forward)
250 << int(casesensitive) << ' '
251 << int(matchword) << ' '
258 bool find(BufferView * bv, FuncRequest const & ev)
260 if (!bv || ev.action != LFUN_WORD_FIND)
263 //lyxerr << "find called, cmd: " << ev << endl;
265 // data is of the form
267 // <casesensitive> <matchword> <forward>"
269 docstring howto = split(ev.argument(), search, '\n');
271 bool casesensitive = parse_bool(howto);
272 bool matchword = parse_bool(howto);
273 bool forward = parse_bool(howto);
275 return find(bv, search, casesensitive, matchword, forward);
279 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
281 if (!bv || ev.action != LFUN_WORD_REPLACE)
284 // data is of the form
287 // <casesensitive> <matchword> <all> <forward>"
290 docstring howto = split(ev.argument(), search, '\n');
291 howto = split(howto, rplc, '\n');
293 bool casesensitive = parse_bool(howto);
294 bool matchword = parse_bool(howto);
295 bool all = parse_bool(howto);
296 bool forward = parse_bool(howto);
299 int const replace_count = all
300 ? replaceAll(bv, search, rplc, casesensitive, matchword)
301 : replace(bv, search, rplc, casesensitive, matchword, forward);
303 Buffer & buf = bv->buffer();
304 if (replace_count == 0) {
305 // emit message signal.
306 buf.message(_("String not found!"));
308 if (replace_count == 1) {
309 // emit message signal.
310 buf.message(_("String has been replaced."));
312 docstring str = convert<docstring>(replace_count);
313 str += _(" strings have been replaced.");
314 // emit message signal.
319 // if we have deleted characters, we do not replace at all, but
320 // rather search for the next occurence
321 if (find(bv, search, casesensitive, matchword, forward))
324 bv->message(_("String not found!"));
329 bool findNextChange(BufferView * bv)
331 DocIterator cur = bv->cursor();
333 if (!findChange(cur))
336 bv->cursor().setCursor(cur);
337 bv->cursor().resetAnchor();
339 Change orig_change = cur.paragraph().lookupChange(cur.pos());
341 CursorSlice & tip = cur.top();
342 for (; !tip.at_end(); tip.forwardPos()) {
343 Change change = tip.paragraph().lookupChange(tip.pos());
344 if (change != orig_change)
348 // Now put cursor to end of selection:
349 bv->cursor().setCursor(cur);
350 bv->cursor().setSelection();
357 typedef vector<pair<string, string> > Escapes;
359 /// A map of symbols and their escaped equivalent needed within a regex.
360 Escapes const & get_regexp_escapes()
362 static Escapes escape_map;
363 if (escape_map.empty()) {
364 escape_map.push_back(pair<string, string>("\\", "\\\\"));
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>(".", "\\."));
380 /// A map of lyx escaped strings and their unescaped equivalent.
381 Escapes const & get_lyx_unescapes() {
382 static Escapes escape_map;
383 if (escape_map.empty()) {
384 escape_map.push_back(pair<string, string>("{*}", "*"));
385 escape_map.push_back(pair<string, string>("{[}", "["));
386 escape_map.push_back(pair<string, string>("\\$", "$"));
387 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
388 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
389 escape_map.push_back(pair<string, string>("\\sim ", "~"));
390 escape_map.push_back(pair<string, string>("\\^", "^"));
395 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
396 ** the found occurrence were escaped.
398 string apply_escapes(string s, Escapes const & escape_map)
400 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
401 Escapes::const_iterator it;
402 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
403 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
404 unsigned int pos = 0;
405 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
406 s.replace(pos, it->first.length(), it->second);
407 // LYXERR(Debug::DEBUG, "After escape: " << s);
408 pos += it->second.length();
409 // LYXERR(Debug::DEBUG, "pos: " << pos);
412 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
416 /** Return the position of the closing brace matching the open one at s[pos],
417 ** or s.size() if not found.
419 size_t find_matching_brace(string const & s, size_t pos)
421 BOOST_ASSERT(s[pos] == '{');
423 for (++pos; pos < s.size(); ++pos) {
426 else if (s[pos] == '{')
428 else if (s[pos] == '}') {
430 if (open_braces == 0)
437 /// Within \regex{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
438 string escape_for_regex(string s)
441 while (pos < s.size()) {
442 size_t new_pos = s.find("\\regexp{", pos);
443 if (new_pos == string::npos)
445 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
446 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
447 LYXERR(Debug::DEBUG, "t : " << t);
448 t = apply_escapes(t, get_regexp_escapes());
449 s.replace(pos, new_pos - pos, t);
450 new_pos = pos + t.size();
451 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
452 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
453 if (new_pos == s.size())
455 size_t end_pos = find_matching_brace(s, new_pos + 7);
456 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
457 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
458 LYXERR(Debug::DEBUG, "t : " << t);
459 if (end_pos == s.size()) {
460 s.replace(new_pos, end_pos - new_pos, t);
462 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
465 s.replace(new_pos, end_pos + 1 - new_pos, t);
466 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
467 pos = new_pos + t.size();
468 LYXERR(Debug::DEBUG, "pos: " << pos);
473 /// Wrapper for boost::regex_replace with simpler interface
474 bool regex_replace(string const & s, string & t, string const & searchstr,
475 string const & replacestr)
477 boost::regex e(searchstr);
479 ostream_iterator<char, char> it(oss);
480 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
481 // tolerate t and s be references to the same variable
482 bool rv = (s != oss.str());
487 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
489 ** Verify that closed braces exactly match open braces. This avoids that, for example,
490 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
493 ** Number of open braces that must remain open at the end for the verification to succeed.
495 bool braces_match(string::const_iterator const & beg,
496 string::const_iterator const & end, int unmatched = 0)
499 string::const_iterator it = beg;
500 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
501 for (; it != end; ++it) {
502 // Skip escaped braces in the count
507 } else if (*it == '{') {
509 } else if (*it == '}') {
510 if (open_pars == 0) {
511 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
517 if (open_pars != unmatched) {
518 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
521 LYXERR(Debug::DEBUG, "Braces match as expected");
525 /** The class performing a match between a position in the document and the FindAdvOptions.
527 ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
528 ** to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
530 class MatchStringAdv {
532 MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt);
534 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
535 ** constructor as opt.search, under the opt.* options settings.
538 ** The length of the matching text, or zero if no match was found.
540 int operator()(DocIterator const & cur, int len = -1) const;
544 lyx::Buffer const & buf;
546 FindAdvOptions const & opt;
549 /** Normalize a stringified or latexified LyX paragraph.
553 ** <li>if search is not casesensitive, then lowercase the string;
554 ** <li>remove any newline at begin or end of the string;
555 ** <li>replace any newline in the middle of the string with a simple space;
556 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
559 ** @todo Normalization should also expand macros, if the corresponding
560 ** search option was checked.
562 string normalize(docstring const & s) const;
563 // normalized string to search
564 string par_as_string;
565 // regular expression to use for searching
567 // unmatched open braces in the search string/regexp
569 // number of (.*?) subexpressions added at end of search regexp for closing
570 // environments, math mode, styles, etc...
575 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAdvOptions const & opt)
578 par_as_string = normalize(opt.search);
583 // Remove trailing closure of math, macros and environments, so to catch parts of them.
585 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
586 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
588 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
590 // @todo need to account for open square braces as well ?
591 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
593 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
595 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
601 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
602 BOOST_ASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces));
603 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
605 par_as_string = escape_for_regex(par_as_string);
606 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
607 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
609 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
610 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
611 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
612 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
613 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
614 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
615 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
616 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
620 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
621 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
622 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
623 BOOST_ASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces));
624 // Entered regexp must match at begin of searched string buffer
625 par_as_string = string("\\`") + par_as_string;
626 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
627 regexp = boost::regex(par_as_string);
631 int MatchStringAdv::operator()(DocIterator const & cur, int len) const
633 docstring docstr = stringifyFromForSearch(opt, buf, cur, len);
634 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
635 string str = normalize(docstr);
636 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
638 if (str.substr(0, par_as_string.size()) == par_as_string)
639 return par_as_string.size();
641 // Try all possible regexp matches, until one that verifies the braces match test is found
642 boost::sregex_iterator re_it(str.begin(), str.end(), regexp);
643 boost::sregex_iterator re_it_end;
644 for (; re_it != re_it_end; ++re_it) {
645 boost::match_results<string::const_iterator> const & m = *re_it;
646 // Check braces on the segment that matched the entire regexp expression,
647 // plus the last subexpression, if a (.*?) was inserted in the constructor.
648 if (! braces_match(m[0].first, m[0].second, open_braces))
650 // Check braces on segments that matched all (.*?) subexpressions.
651 for (size_t i = 1; i < m.size(); ++i)
652 if (! braces_match(m[i].first, m[i].second))
654 // Exclude from the returned match length any length due to close wildcards added at end of regexp
655 if (close_wildcards == 0)
656 return m[0].second - m[0].first;
658 return m[m.size() - close_wildcards].first - m[0].first;
665 string MatchStringAdv::normalize(docstring const & s) const
668 if (! opt.casesensitive)
669 t = lyx::to_utf8(lowercase(s));
672 // Remove \n at begin
673 while (t.size() > 0 && t[0] == '\n')
676 while (t.size() > 0 && t[t.size() - 1] == '\n')
677 t = t.substr(0, t.size() - 1);
679 // Replace all other \n with spaces
680 while ((pos = t.find("\n")) != string::npos)
681 t.replace(pos, 1, " ");
682 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
683 while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
689 docstring stringifyFromCursor(DocIterator const & cur, int len)
691 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
692 if (cur.inTexted()) {
693 Paragraph const & par = cur.paragraph();
694 // TODO what about searching beyond/across paragraph breaks ?
695 // TODO Try adding a AS_STR_INSERTS as last arg
696 return par.asString(cur.pos(), ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len, AS_STR_INSETS);
697 } else if (cur.inMathed()) {
699 CursorSlice cs = cur.top();
700 MathData md = cs.cell();
701 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
702 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
706 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
710 /** Computes the LaTeX export of buf starting from cur and ending len positions after cur,
711 ** if len is positive, or at the paragraph or innermost inset end if len is -1.
713 docstring latexifyFromCursor(Buffer const & buf, DocIterator const & cur, int len)
715 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
716 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
717 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
718 BOOST_ASSERT(buf.isLatex());
721 odocstringstream ods;
722 OutputParams runparams(&buf.params().encoding());
723 runparams.nice = false;
724 runparams.flavor = OutputParams::LATEX;
725 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
726 // No side effect of file copying and image conversion
727 runparams.dryrun = true;
729 if (cur.inTexted()) {
730 // @TODO what about searching beyond/across paragraph breaks ?
731 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
732 for (int i = 0; i < cur.pit(); ++i)
734 // ParagraphList::const_iterator pit_end = pit;
736 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
737 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
738 ? pit->size() : cur.pos() + len;
739 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
741 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
742 } else if (cur.inMathed()) {
743 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
744 for (int s = cur.depth() - 1; s >= 0; --s) {
745 CursorSlice const & cs = cur[s];
746 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
748 cs.asInsetMath()->asHullInset()->header_write(ws);
753 CursorSlice const & cs = cur.top();
754 MathData md = cs.cell();
755 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
756 ? md.end() : md.begin() + cs.pos() + len );
757 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
760 // MathData md = cur.cell();
761 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
762 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
763 // MathAtom const & ma = *it;
764 // ma.nucleus()->latex(buf, ods, runparams);
767 // Retrieve the math environment type, and add '$' or '$]' or others (\end{equation}) accordingly
768 for (int s = cur.depth() - 1; s >= 0; --s) {
769 CursorSlice const & cs = cur[s];
770 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
772 cs.asInsetMath()->asHullInset()->footer_write(ws);
776 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
778 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
783 /** Finalize an advanced find operation, advancing the cursor to the innermost
784 ** position that matches, plus computing the length of the matching text to
787 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
789 // Search the foremost position that matches (avoids find of entire math inset when match at start of it)
793 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
797 } while (cur && cur.depth() > d && match(cur) > 0);
799 BOOST_ASSERT(match(cur) > 0);
800 LYXERR(Debug::DEBUG, "Ok");
802 // Compute the match length
804 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
805 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
807 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
809 int old_len = match(cur, len); // Length of matched text (different from len param)
811 // Greedy behaviour while matching regexps
812 while ((new_len = match(cur, len + 1)) > old_len) {
815 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
821 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
825 for (; cur; cur.forwardPos()) {
826 // odocstringstream ods;
827 // ods << _("Searching ... ") << (cur.bottom().lastpit() - cur.bottom().pit()) * 100 / total;
828 // cur.message(ods.str());
830 return findAdvFinalize(cur, match);
836 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
837 // if (cur.pos() > 0 || cur.depth() > 0)
838 // cur.backwardPos();
839 DocIterator cur_orig(cur);
841 findAdvFinalize(cur_orig, match);
842 // int total = cur.bottom().pit() + 1;
843 for (; cur; cur.backwardPos()) {
844 // odocstringstream ods;
845 // ods << _("Searching ... ") << (total - cur.bottom().pit()) * 100 / total;
846 // cur.message(ods.str());
848 // Find the most backward consecutive match within same paragraph while searching backwards.
852 int len = findAdvFinalize(cur, match);
857 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
858 } while (cur && cur.pit() == pit && match(cur)
859 && (len = findAdvFinalize(cur, match)) > old_len);
862 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
863 LYXERR(Debug::DEBUG, "cur : " << cur);
871 } // anonym namespace
874 docstring stringifyFromForSearch(FindAdvOptions const & opt, Buffer const & buf,
875 DocIterator const & cur, int len)
877 if (! opt.ignoreformat)
878 return latexifyFromCursor(buf, cur, len);
880 return stringifyFromCursor(cur, len);
884 lyx::FindAdvOptions::FindAdvOptions(docstring const & search, bool casesensitive,
885 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
887 : search(search), casesensitive(casesensitive), matchword(matchword),
888 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
893 /// Perform a FindAdv operation.
894 bool findAdv(BufferView * bv, FindAdvOptions const & opt)
896 DocIterator cur = bv->cursor();
899 if (opt.search.empty()) {
900 bv->message(_("Search text is empty !"));
903 // if (! bv->buffer()) {
904 // bv->message(_("No open document !"));
909 MatchStringAdv const matchAdv(bv->buffer(), opt);
911 match_len = findForwardAdv(cur, matchAdv);
913 match_len = findBackwardsAdv(cur, matchAdv);
915 // This may only be raised by boost::regex()
916 bv->message(_("Invalid regular expression !"));
920 if (match_len == 0) {
921 bv->message(_("Match not found !"));
925 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
926 bv->putSelectionAt(cur, match_len, ! opt.forward);
927 bv->message(_("Match found !"));
934 void findAdv(BufferView * bv, FuncRequest const & ev)
936 if (!bv || ev.action != LFUN_WORD_FINDADV)
940 istringstream iss(to_utf8(ev.argument()));
946 ostringstream & operator<<(ostringstream & os, lyx::FindAdvOptions const & opt)
948 os << to_utf8(opt.search) << "\nEOSS\n"
949 << opt.casesensitive << ' '
950 << opt.matchword << ' '
951 << opt.forward << ' '
952 << opt.expandmacros << ' '
953 << opt.ignoreformat << ' '
956 LYXERR(Debug::DEBUG, "built: " << os.str());
961 istringstream & operator>>(istringstream & is, lyx::FindAdvOptions & opt)
963 LYXERR(Debug::DEBUG, "parsing");
967 while (line != "EOSS") {
971 if (is.eof()) // Tolerate malformed request
975 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
976 opt.search = from_utf8(s);
977 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
978 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
979 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);