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, bool next)
122 for (; cur; next ? cur.forwardPos() : cur.backwardPos())
123 if (cur.inTexted() && !cur.paragraph().isUnchanged(cur.pos())) {
125 // if we search backwards, take a step forward
126 // to correctly set the anchor
135 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
138 frontend::Alert::error(_("Search error"), _("Search string is empty"));
145 bool find(BufferView * bv, docstring const & searchstr,
146 bool cs, bool mw, bool fw, bool find_del = true)
148 if (!searchAllowed(bv, searchstr))
151 DocIterator cur = bv->cursor();
153 MatchString const match(searchstr, cs, mw);
155 bool found = fw ? findForward(cur, match, find_del) :
156 findBackwards(cur, match, find_del);
159 bv->putSelectionAt(cur, searchstr.length(), !fw);
165 int replaceAll(BufferView * bv,
166 docstring const & searchstr, docstring const & replacestr,
169 Buffer & buf = bv->buffer();
171 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
174 MatchString const match(searchstr, cs, mw);
177 int const rsize = replacestr.size();
178 int const ssize = searchstr.size();
181 cur.setCursor(doc_iterator_begin(&buf));
182 while (findForward(cur, match, false)) {
183 // Backup current cursor position and font.
184 pos_type const pos = cur.pos();
185 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
187 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
188 buf.params().trackChanges);
189 cur.paragraph().insert(pos, replacestr, font,
190 Change(buf.params().trackChanges ?
191 Change::INSERTED : Change::UNCHANGED));
192 for (int i = 0; i < rsize + striked; ++i)
198 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
205 bool stringSelected(BufferView * bv, docstring const & searchstr,
206 bool cs, bool mw, bool fw)
208 // if nothing selected or selection does not equal search
209 // string search and select next occurance and return
210 docstring const & str1 = searchstr;
211 docstring const str2 = bv->cursor().selectionAsString(false);
212 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
213 find(bv, searchstr, cs, mw, fw);
221 int replace(BufferView * bv, docstring const & searchstr,
222 docstring const & replacestr, bool cs, bool mw, bool fw)
224 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
227 if (!stringSelected(bv, searchstr, cs, mw, fw))
230 Cursor & cur = bv->cursor();
231 cap::replaceSelectionWithString(cur, replacestr, fw);
232 bv->buffer().markDirty();
233 find(bv, searchstr, cs, mw, fw, false);
234 bv->buffer().updateMacros();
235 bv->processUpdateFlags(Update::Force | Update::FitCursor);
243 docstring const find2string(docstring const & search,
244 bool casesensitive, bool matchword, bool forward)
248 << int(casesensitive) << ' '
249 << int(matchword) << ' '
255 docstring const replace2string(docstring const & search, docstring const & replace,
256 bool casesensitive, bool matchword,
257 bool all, bool forward)
262 << int(casesensitive) << ' '
263 << int(matchword) << ' '
270 bool find(BufferView * bv, FuncRequest const & ev)
272 if (!bv || ev.action != LFUN_WORD_FIND)
275 //lyxerr << "find called, cmd: " << ev << endl;
277 // data is of the form
279 // <casesensitive> <matchword> <forward>"
281 docstring howto = split(ev.argument(), search, '\n');
283 bool casesensitive = parse_bool(howto);
284 bool matchword = parse_bool(howto);
285 bool forward = parse_bool(howto);
287 return find(bv, search, casesensitive, matchword, forward);
291 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
293 if (!bv || ev.action != LFUN_WORD_REPLACE)
296 // data is of the form
299 // <casesensitive> <matchword> <all> <forward>"
302 docstring howto = split(ev.argument(), search, '\n');
303 howto = split(howto, rplc, '\n');
305 bool casesensitive = parse_bool(howto);
306 bool matchword = parse_bool(howto);
307 bool all = parse_bool(howto);
308 bool forward = parse_bool(howto);
311 int const replace_count = all
312 ? replaceAll(bv, search, rplc, casesensitive, matchword)
313 : replace(bv, search, rplc, casesensitive, matchword, forward);
315 Buffer & buf = bv->buffer();
316 if (replace_count == 0) {
317 // emit message signal.
318 buf.message(_("String not found!"));
320 if (replace_count == 1) {
321 // emit message signal.
322 buf.message(_("String has been replaced."));
324 docstring str = convert<docstring>(replace_count);
325 str += _(" strings have been replaced.");
326 // emit message signal.
331 // if we have deleted characters, we do not replace at all, but
332 // rather search for the next occurence
333 if (find(bv, search, casesensitive, matchword, forward))
336 bv->message(_("String not found!"));
341 bool findNextChange(BufferView * bv)
343 return findChange(bv, true);
347 bool findPreviousChange(BufferView * bv)
349 return findChange(bv, false);
353 bool findChange(BufferView * bv, bool next)
355 if (bv->cursor().selection()) {
356 // set the cursor at the beginning or at the end of the selection
357 // before searching. Otherwise, the current change will be found.
358 if (next != bv->cursor().top() > bv->cursor().anchor())
359 bv->cursor().setCursorToAnchor();
362 DocIterator cur = bv->cursor();
364 // Are we within a change ? Then first search forward (backward),
365 // clear the selection and search the other way around (see the end
366 // of this function). This will avoid changes to be selected half.
367 bool search_both_sides = false;
369 Change change_next_pos
370 = cur.paragraph().lookupChange(cur.pos());
371 Change change_prev_pos
372 = cur.paragraph().lookupChange(cur.pos() - 1);
373 if (change_next_pos.isSimilarTo(change_prev_pos))
374 search_both_sides = true;
377 if (!findChange(cur, next))
380 bv->cursor().setCursor(cur);
381 bv->cursor().resetAnchor();
384 // take a step into the change
387 Change orig_change = cur.paragraph().lookupChange(cur.pos());
389 CursorSlice & tip = cur.top();
391 for (; !tip.at_end(); tip.forwardPos()) {
392 Change change = tip.paragraph().lookupChange(tip.pos());
393 if (change != orig_change)
397 for (; !tip.at_begin(); tip.backwardPos()) {
398 Change change = tip.paragraph().lookupChange(tip.pos());
399 if (change != orig_change) {
400 // take a step forward to correctly set the selection
407 // Now put cursor to end of selection:
408 bv->cursor().setCursor(cur);
409 bv->cursor().setSelection();
411 if (search_both_sides) {
412 bv->cursor().setSelection(false);
413 findChange(bv, !next);
421 typedef vector<pair<string, string> > Escapes;
423 /// A map of symbols and their escaped equivalent needed within a regex.
424 Escapes const & get_regexp_escapes()
426 static Escapes escape_map;
427 if (escape_map.empty()) {
428 escape_map.push_back(pair<string, string>("\\", "\\\\"));
429 escape_map.push_back(pair<string, string>("^", "\\^"));
430 escape_map.push_back(pair<string, string>("$", "\\$"));
431 escape_map.push_back(pair<string, string>("{", "\\{"));
432 escape_map.push_back(pair<string, string>("}", "\\}"));
433 escape_map.push_back(pair<string, string>("[", "\\["));
434 escape_map.push_back(pair<string, string>("]", "\\]"));
435 escape_map.push_back(pair<string, string>("(", "\\("));
436 escape_map.push_back(pair<string, string>(")", "\\)"));
437 escape_map.push_back(pair<string, string>("+", "\\+"));
438 escape_map.push_back(pair<string, string>("*", "\\*"));
439 escape_map.push_back(pair<string, string>(".", "\\."));
444 /// A map of lyx escaped strings and their unescaped equivalent.
445 Escapes const & get_lyx_unescapes() {
446 static Escapes escape_map;
447 if (escape_map.empty()) {
448 escape_map.push_back(pair<string, string>("{*}", "*"));
449 escape_map.push_back(pair<string, string>("{[}", "["));
450 escape_map.push_back(pair<string, string>("\\$", "$"));
451 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
452 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
453 escape_map.push_back(pair<string, string>("\\sim ", "~"));
454 escape_map.push_back(pair<string, string>("\\^", "^"));
459 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
460 ** the found occurrence were escaped.
462 string apply_escapes(string s, Escapes const & escape_map)
464 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
465 Escapes::const_iterator it;
466 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
467 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
468 unsigned int pos = 0;
469 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
470 s.replace(pos, it->first.length(), it->second);
471 // LYXERR(Debug::DEBUG, "After escape: " << s);
472 pos += it->second.length();
473 // LYXERR(Debug::DEBUG, "pos: " << pos);
476 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
480 /** Return the position of the closing brace matching the open one at s[pos],
481 ** or s.size() if not found.
483 size_t find_matching_brace(string const & s, size_t pos)
485 LASSERT(s[pos] == '{', /* */);
487 for (++pos; pos < s.size(); ++pos) {
490 else if (s[pos] == '{')
492 else if (s[pos] == '}') {
494 if (open_braces == 0)
501 /// Within \regex{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
502 string escape_for_regex(string s)
505 while (pos < s.size()) {
506 size_t new_pos = s.find("\\regexp{", pos);
507 if (new_pos == string::npos)
509 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
510 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
511 LYXERR(Debug::DEBUG, "t : " << t);
512 t = apply_escapes(t, get_regexp_escapes());
513 s.replace(pos, new_pos - pos, t);
514 new_pos = pos + t.size();
515 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
516 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
517 if (new_pos == s.size())
519 size_t end_pos = find_matching_brace(s, new_pos + 7);
520 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
521 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
522 LYXERR(Debug::DEBUG, "t : " << t);
523 if (end_pos == s.size()) {
524 s.replace(new_pos, end_pos - new_pos, t);
526 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
529 s.replace(new_pos, end_pos + 1 - new_pos, t);
530 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
531 pos = new_pos + t.size();
532 LYXERR(Debug::DEBUG, "pos: " << pos);
537 /// Wrapper for boost::regex_replace with simpler interface
538 bool regex_replace(string const & s, string & t, string const & searchstr,
539 string const & replacestr)
541 boost::regex e(searchstr);
543 ostream_iterator<char, char> it(oss);
544 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
545 // tolerate t and s be references to the same variable
546 bool rv = (s != oss.str());
551 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
553 ** Verify that closed braces exactly match open braces. This avoids that, for example,
554 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
557 ** Number of open braces that must remain open at the end for the verification to succeed.
559 bool braces_match(string::const_iterator const & beg,
560 string::const_iterator const & end, int unmatched = 0)
563 string::const_iterator it = beg;
564 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
565 for (; it != end; ++it) {
566 // Skip escaped braces in the count
571 } else if (*it == '{') {
573 } else if (*it == '}') {
574 if (open_pars == 0) {
575 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
581 if (open_pars != unmatched) {
582 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
585 LYXERR(Debug::DEBUG, "Braces match as expected");
589 /** The class performing a match between a position in the document and the FindAdvOptions.
591 ** @todo The user-entered regexp expression(s) should be enclosed within something like \regexp{},
592 ** to be written by a dedicated Inset, so to avoid escaping it in escape_for_regex().
594 class MatchStringAdv {
596 MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt);
598 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
599 ** constructor as opt.search, under the opt.* options settings.
602 ** If set, then match is searched only against beginning of text starting at cur.
603 ** If unset, then match is searched anywhere in text starting at cur.
606 ** The length of the matching text, or zero if no match was found.
608 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
612 lyx::Buffer const & buf;
614 FindAndReplaceOptions const & opt;
617 /** Normalize a stringified or latexified LyX paragraph.
621 ** <li>if search is not casesensitive, then lowercase the string;
622 ** <li>remove any newline at begin or end of the string;
623 ** <li>replace any newline in the middle of the string with a simple space;
624 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
627 ** @todo Normalization should also expand macros, if the corresponding
628 ** search option was checked.
630 string normalize(docstring const & s) const;
631 // normalized string to search
632 string par_as_string;
633 // regular expression to use for searching
635 // same as regexp, but prefixed with a ".*"
636 boost::regex regexp2;
637 // unmatched open braces in the search string/regexp
639 // number of (.*?) subexpressions added at end of search regexp for closing
640 // environments, math mode, styles, etc...
645 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt)
648 par_as_string = normalize(opt.search);
653 // Remove trailing closure of math, macros and environments, so to catch parts of them.
655 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
656 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
658 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
660 // @todo need to account for open square braces as well ?
661 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
663 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
665 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
671 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
672 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
673 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
675 par_as_string = escape_for_regex(par_as_string);
676 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
677 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
679 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
680 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
681 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
682 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
683 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
684 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
685 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
686 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
690 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
691 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
692 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
693 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
694 // Entered regexp must match at begin of searched string buffer
695 par_as_string = string("\\`") + par_as_string;
696 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
697 regexp = boost::regex(par_as_string);
698 regexp2 = boost::regex(string(".*") + par_as_string);
703 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
705 docstring docstr = stringifyFromForSearch(opt, cur, len);
706 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
707 string str = normalize(docstr);
708 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
711 if (str.substr(0, par_as_string.size()) == par_as_string)
712 return par_as_string.size();
714 size_t pos = str.find(par_as_string);
715 if (pos != string::npos)
716 return par_as_string.size();
719 // Try all possible regexp matches, until one that verifies the braces match test is found
720 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
721 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
722 boost::sregex_iterator re_it_end;
723 for (; re_it != re_it_end; ++re_it) {
724 boost::match_results<string::const_iterator> const & m = *re_it;
725 // Check braces on the segment that matched the entire regexp expression,
726 // plus the last subexpression, if a (.*?) was inserted in the constructor.
727 if (! braces_match(m[0].first, m[0].second, open_braces))
729 // Check braces on segments that matched all (.*?) subexpressions.
730 for (size_t i = 1; i < m.size(); ++i)
731 if (! braces_match(m[i].first, m[i].second))
733 // Exclude from the returned match length any length due to close wildcards added at end of regexp
734 if (close_wildcards == 0)
735 return m[0].second - m[0].first;
737 return m[m.size() - close_wildcards].first - m[0].first;
744 string MatchStringAdv::normalize(docstring const & s) const
747 if (! opt.casesensitive)
748 t = lyx::to_utf8(lowercase(s));
751 // Remove \n at begin
752 while (t.size() > 0 && t[0] == '\n')
755 while (t.size() > 0 && t[t.size() - 1] == '\n')
756 t = t.substr(0, t.size() - 1);
758 // Replace all other \n with spaces
759 while ((pos = t.find("\n")) != string::npos)
760 t.replace(pos, 1, " ");
761 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
762 while (regex_replace(t, t, "\\\\[a-zA-Z_]+(\\{\\})+", ""))
768 docstring stringifyFromCursor(DocIterator const & cur, int len)
770 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
771 if (cur.inTexted()) {
772 Paragraph const & par = cur.paragraph();
773 // TODO what about searching beyond/across paragraph breaks ?
774 // TODO Try adding a AS_STR_INSERTS as last arg
775 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len;
776 OutputParams runparams(&cur.buffer()->params().encoding());
778 runparams.nice = true;
779 runparams.flavor = OutputParams::LATEX;
780 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
781 // No side effect of file copying and image conversion
782 runparams.dryrun = true;
783 LYXERR(Debug::DEBUG, "Stringifying with cur: " << cur << ", from pos: " << cur.pos() << ", end: " << end);
784 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
785 } else if (cur.inMathed()) {
787 CursorSlice cs = cur.top();
788 MathData md = cs.cell();
789 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
790 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
794 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
798 /** Computes the LaTeX export of buf starting from cur and ending len positions
799 * after cur, if len is positive, or at the paragraph or innermost inset end
803 docstring latexifyFromCursor(DocIterator const & cur, int len)
805 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
806 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
807 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
808 Buffer const & buf = *cur.buffer();
809 LASSERT(buf.isLatex(), /* */);
812 odocstringstream ods;
813 OutputParams runparams(&buf.params().encoding());
814 runparams.nice = false;
815 runparams.flavor = OutputParams::LATEX;
816 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
817 // No side effect of file copying and image conversion
818 runparams.dryrun = true;
820 if (cur.inTexted()) {
821 // @TODO what about searching beyond/across paragraph breaks ?
822 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
823 for (int i = 0; i < cur.pit(); ++i)
825 // ParagraphList::const_iterator pit_end = pit;
827 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
828 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
829 ? pit->size() : cur.pos() + len;
830 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
832 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
833 } else if (cur.inMathed()) {
834 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
835 for (int s = cur.depth() - 1; s >= 0; --s) {
836 CursorSlice const & cs = cur[s];
837 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
839 cs.asInsetMath()->asHullInset()->header_write(ws);
844 CursorSlice const & cs = cur.top();
845 MathData md = cs.cell();
846 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
847 ? md.end() : md.begin() + cs.pos() + len );
848 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
851 // MathData md = cur.cell();
852 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
853 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
854 // MathAtom const & ma = *it;
855 // ma.nucleus()->latex(buf, ods, runparams);
858 // Retrieve the math environment type, and add '$' or '$]'
859 // or others (\end{equation}) accordingly
860 for (int s = cur.depth() - 1; s >= 0; --s) {
861 CursorSlice const & cs = cur[s];
862 InsetMath * inset = cs.asInsetMath();
863 if (inset && inset->asHullInset()) {
865 inset->asHullInset()->footer_write(ws);
869 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
871 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
876 /** Finalize an advanced find operation, advancing the cursor to the innermost
877 ** position that matches, plus computing the length of the matching text to
880 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
882 // Search the foremost position that matches (avoids find of entire math
883 // inset when match at start of it)
885 DocIterator old_cur(cur.buffer());
887 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
891 } while (cur && cur.depth() > d && match(cur) > 0);
893 LASSERT(match(cur) > 0, /* */);
894 LYXERR(Debug::DEBUG, "Ok");
896 // Compute the match length
898 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
899 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
901 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
903 // Length of matched text (different from len param)
904 int old_len = match(cur, len);
906 // Greedy behaviour while matching regexps
907 while ((new_len = match(cur, len + 1)) > old_len) {
910 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
917 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
923 while (cur && !match(cur, -1, false)) {
924 if (cur.pit() < cur.lastpit())
930 for (; cur; cur.forwardPos()) {
932 return findAdvFinalize(cur, match);
934 wrap_answer = frontend::Alert::prompt(
936 _("End of document reached while searching forward\n"
938 "Continue searching from beginning ?"),
939 0, 1, _("&Yes"), _("&No"));
941 cur.push_back(CursorSlice(match.buf.inset()));
942 } while (wrap_answer == 0);
948 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
949 // if (cur.pos() > 0 || cur.depth() > 0)
950 // cur.backwardPos();
951 DocIterator cur_orig(cur);
953 findAdvFinalize(cur_orig, match);
954 // int total = cur.bottom().pit() + 1;
957 // TODO No ! così non va.
958 bool pit_changed = false;
959 while (cur && !match(cur, -1, false)) {
969 if (cur && pit_changed)
970 cur.pos() = cur.lastpos();
971 for (; cur; cur.backwardPos()) {
973 // Find the most backward consecutive match within same paragraph while searching backwards.
977 int len = findAdvFinalize(cur, match);
982 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
983 } while (cur && cur.pit() == pit && match(cur)
984 && (len = findAdvFinalize(cur, match)) > old_len);
987 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
988 LYXERR(Debug::DEBUG, "cur : " << cur);
993 wrap_answer = frontend::Alert::prompt(
995 _("Beginning of document reached while searching backwards\n"
997 "Continue searching from end ?"),
998 0, 1, _("&Yes"), _("&No"));
999 cur = doc_iterator_end(&match.buf);
1001 } while (wrap_answer == 0);
1005 } // anonym namespace
1008 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1009 DocIterator const & cur, int len)
1011 if (!opt.ignoreformat)
1012 return latexifyFromCursor(cur, len);
1014 return stringifyFromCursor(cur, len);
1018 lyx::FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1019 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1020 bool regexp, docstring const & replace)
1021 : search(search), casesensitive(casesensitive), matchword(matchword),
1022 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1023 regexp(regexp), replace(replace)
1027 /// Perform a FindAdv operation.
1028 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1030 DocIterator cur = bv->cursor();
1033 if (opt.search.empty()) {
1034 bv->message(_("Search text is empty!"));
1037 // if (! bv->buffer()) {
1038 // bv->message(_("No open document !"));
1043 MatchStringAdv const matchAdv(bv->buffer(), opt);
1045 match_len = findForwardAdv(cur, matchAdv);
1047 match_len = findBackwardsAdv(cur, matchAdv);
1049 // This may only be raised by boost::regex()
1050 bv->message(_("Invalid regular expression!"));
1054 if (match_len == 0) {
1055 bv->message(_("Match not found!"));
1059 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
1060 bv->putSelectionAt(cur, match_len, ! opt.forward);
1061 bv->message(_("Match found!"));
1062 if (opt.replace != docstring(from_utf8(LYX_FR_NULL_STRING))) {
1063 dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1070 void findAdv(BufferView * bv, FuncRequest const & ev)
1072 if (!bv || ev.action != LFUN_WORD_FINDADV)
1075 FindAndReplaceOptions opt;
1076 istringstream iss(to_utf8(ev.argument()));
1082 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1084 os << to_utf8(opt.search) << "\nEOSS\n"
1085 << opt.casesensitive << ' '
1086 << opt.matchword << ' '
1087 << opt.forward << ' '
1088 << opt.expandmacros << ' '
1089 << opt.ignoreformat << ' '
1090 << opt.regexp << ' '
1091 << to_utf8(opt.replace) << "\nEOSS\n";
1093 LYXERR(Debug::DEBUG, "built: " << os.str());
1098 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1100 LYXERR(Debug::DEBUG, "parsing");
1104 while (line != "EOSS") {
1108 if (is.eof()) // Tolerate malformed request
1112 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
1113 opt.search = from_utf8(s);
1114 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1115 is.get(); // Waste space before replace string
1118 while (line != "EOSS") {
1122 if (is.eof()) // Tolerate malformed request
1126 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1127 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);
1128 LYXERR(Debug::DEBUG, "replacing with: '" << s << "'");
1129 opt.replace = from_utf8(s);