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().isChanged(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 & searchstr,
206 bool cs, bool mw, bool fw)
208 // if nothing selected and searched string is empty, this
209 // means that we want to search current word at cursor position.
210 if (!bv->cursor().selection() && searchstr.empty()) {
211 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
212 searchstr = bv->cursor().selectionAsString(false);
216 // if nothing selected or selection does not equal search
217 // string search and select next occurance and return
218 docstring const & str1 = searchstr;
219 docstring const str2 = bv->cursor().selectionAsString(false);
220 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
221 find(bv, searchstr, cs, mw, fw);
229 int replace(BufferView * bv, docstring & searchstr,
230 docstring const & replacestr, bool cs, bool mw, bool fw)
232 if (!stringSelected(bv, searchstr, cs, mw, fw))
235 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
238 Cursor & cur = bv->cursor();
239 cap::replaceSelectionWithString(cur, replacestr, fw);
240 bv->buffer().markDirty();
241 find(bv, searchstr, cs, mw, fw, false);
242 bv->buffer().updateMacros();
243 bv->processUpdateFlags(Update::Force | Update::FitCursor);
251 docstring const find2string(docstring const & search,
252 bool casesensitive, bool matchword, bool forward)
256 << int(casesensitive) << ' '
257 << int(matchword) << ' '
263 docstring const replace2string(docstring const & replace,
264 docstring const & search, bool casesensitive, bool matchword,
265 bool all, bool forward)
268 ss << replace << '\n'
270 << int(casesensitive) << ' '
271 << int(matchword) << ' '
278 bool find(BufferView * bv, FuncRequest const & ev)
280 if (!bv || ev.action != LFUN_WORD_FIND)
283 //lyxerr << "find called, cmd: " << ev << endl;
285 // data is of the form
287 // <casesensitive> <matchword> <forward>"
289 docstring howto = split(ev.argument(), search, '\n');
291 bool casesensitive = parse_bool(howto);
292 bool matchword = parse_bool(howto);
293 bool forward = parse_bool(howto);
295 return find(bv, search, casesensitive, matchword, forward);
299 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
301 if (!bv || ev.action != LFUN_WORD_REPLACE)
304 // data is of the form
307 // <casesensitive> <matchword> <all> <forward>"
310 docstring howto = split(ev.argument(), rplc, '\n');
311 howto = split(howto, search, '\n');
313 bool casesensitive = parse_bool(howto);
314 bool matchword = parse_bool(howto);
315 bool all = parse_bool(howto);
316 bool forward = parse_bool(howto);
319 int const replace_count = all
320 ? replaceAll(bv, search, rplc, casesensitive, matchword)
321 : replace(bv, search, rplc, casesensitive, matchword, forward);
323 Buffer & buf = bv->buffer();
324 if (replace_count == 0) {
325 // emit message signal.
326 buf.message(_("String not found!"));
328 if (replace_count == 1) {
329 // emit message signal.
330 buf.message(_("String has been replaced."));
332 docstring str = convert<docstring>(replace_count);
333 str += _(" strings have been replaced.");
334 // emit message signal.
339 // if we have deleted characters, we do not replace at all, but
340 // rather search for the next occurence
341 if (find(bv, search, casesensitive, matchword, forward))
344 bv->message(_("String not found!"));
349 bool findNextChange(BufferView * bv)
351 return findChange(bv, true);
355 bool findPreviousChange(BufferView * bv)
357 return findChange(bv, false);
361 bool findChange(BufferView * bv, bool next)
363 if (bv->cursor().selection()) {
364 // set the cursor at the beginning or at the end of the selection
365 // before searching. Otherwise, the current change will be found.
366 if (next != (bv->cursor().top() > bv->cursor().anchor()))
367 bv->cursor().setCursorToAnchor();
370 DocIterator cur = bv->cursor();
372 // Are we within a change ? Then first search forward (backward),
373 // clear the selection and search the other way around (see the end
374 // of this function). This will avoid changes to be selected half.
375 bool search_both_sides = false;
377 Change change_next_pos
378 = cur.paragraph().lookupChange(cur.pos());
379 Change change_prev_pos
380 = cur.paragraph().lookupChange(cur.pos() - 1);
381 if (change_next_pos.isSimilarTo(change_prev_pos))
382 search_both_sides = true;
385 if (!findChange(cur, next))
388 bv->cursor().setCursor(cur);
389 bv->cursor().resetAnchor();
392 // take a step into the change
395 Change orig_change = cur.paragraph().lookupChange(cur.pos());
397 CursorSlice & tip = cur.top();
399 for (; !tip.at_end(); tip.forwardPos()) {
400 Change change = tip.paragraph().lookupChange(tip.pos());
401 if (change != orig_change)
405 for (; !tip.at_begin();) {
407 Change change = tip.paragraph().lookupChange(tip.pos());
408 if (change != orig_change) {
409 // take a step forward to correctly set the selection
416 // Now put cursor to end of selection:
417 bv->cursor().setCursor(cur);
418 bv->cursor().setSelection();
420 if (search_both_sides) {
421 bv->cursor().setSelection(false);
422 findChange(bv, !next);
430 typedef vector<pair<string, string> > Escapes;
432 /// A map of symbols and their escaped equivalent needed within a regex.
433 Escapes const & get_regexp_escapes()
435 static Escapes escape_map;
436 if (escape_map.empty()) {
437 escape_map.push_back(pair<string, string>("\\", "\\\\"));
438 escape_map.push_back(pair<string, string>("^", "\\^"));
439 escape_map.push_back(pair<string, string>("$", "\\$"));
440 escape_map.push_back(pair<string, string>("{", "\\{"));
441 escape_map.push_back(pair<string, string>("}", "\\}"));
442 escape_map.push_back(pair<string, string>("[", "\\["));
443 escape_map.push_back(pair<string, string>("]", "\\]"));
444 escape_map.push_back(pair<string, string>("(", "\\("));
445 escape_map.push_back(pair<string, string>(")", "\\)"));
446 escape_map.push_back(pair<string, string>("+", "\\+"));
447 escape_map.push_back(pair<string, string>("*", "\\*"));
448 escape_map.push_back(pair<string, string>(".", "\\."));
453 /// A map of lyx escaped strings and their unescaped equivalent.
454 Escapes const & get_lyx_unescapes() {
455 static Escapes escape_map;
456 if (escape_map.empty()) {
457 escape_map.push_back(pair<string, string>("{*}", "*"));
458 escape_map.push_back(pair<string, string>("{[}", "["));
459 escape_map.push_back(pair<string, string>("\\$", "$"));
460 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
461 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
462 escape_map.push_back(pair<string, string>("\\sim ", "~"));
463 escape_map.push_back(pair<string, string>("\\^", "^"));
468 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
469 ** the found occurrence were escaped.
471 string apply_escapes(string s, Escapes const & escape_map)
473 LYXERR(Debug::DEBUG, "Escaping: '" << s << "'");
474 Escapes::const_iterator it;
475 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
476 // LYXERR(Debug::DEBUG, "Escaping " << it->first << " as " << it->second);
477 unsigned int pos = 0;
478 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
479 s.replace(pos, it->first.length(), it->second);
480 // LYXERR(Debug::DEBUG, "After escape: " << s);
481 pos += it->second.length();
482 // LYXERR(Debug::DEBUG, "pos: " << pos);
485 LYXERR(Debug::DEBUG, "Escaped : '" << s << "'");
489 /** Return the position of the closing brace matching the open one at s[pos],
490 ** or s.size() if not found.
492 size_t find_matching_brace(string const & s, size_t pos)
494 LASSERT(s[pos] == '{', /* */);
496 for (++pos; pos < s.size(); ++pos) {
499 else if (s[pos] == '{')
501 else if (s[pos] == '}') {
503 if (open_braces == 0)
510 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
511 string escape_for_regex(string s)
514 while (pos < s.size()) {
515 size_t new_pos = s.find("\\regexp{", pos);
516 if (new_pos == string::npos)
518 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
519 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
520 LYXERR(Debug::DEBUG, "t : " << t);
521 t = apply_escapes(t, get_regexp_escapes());
522 s.replace(pos, new_pos - pos, t);
523 new_pos = pos + t.size();
524 LYXERR(Debug::DEBUG, "Regexp after escaping: " << s);
525 LYXERR(Debug::DEBUG, "new_pos: " << new_pos);
526 if (new_pos == s.size())
528 size_t end_pos = find_matching_brace(s, new_pos + 7);
529 LYXERR(Debug::DEBUG, "end_pos: " << end_pos);
530 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
531 LYXERR(Debug::DEBUG, "t : " << t);
532 if (end_pos == s.size()) {
533 s.replace(new_pos, end_pos - new_pos, t);
535 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
538 s.replace(new_pos, end_pos + 1 - new_pos, t);
539 LYXERR(Debug::DEBUG, "Regexp after \\regexp{} removal: " << s);
540 pos = new_pos + t.size();
541 LYXERR(Debug::DEBUG, "pos: " << pos);
546 /// Wrapper for boost::regex_replace with simpler interface
547 bool regex_replace(string const & s, string & t, string const & searchstr,
548 string const & replacestr)
550 boost::regex e(searchstr);
552 ostream_iterator<char, char> it(oss);
553 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
554 // tolerate t and s be references to the same variable
555 bool rv = (s != oss.str());
560 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
562 ** Verify that closed braces exactly match open braces. This avoids that, for example,
563 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
566 ** Number of open braces that must remain open at the end for the verification to succeed.
568 bool braces_match(string::const_iterator const & beg,
569 string::const_iterator const & end, int unmatched = 0)
572 string::const_iterator it = beg;
573 LYXERR(Debug::DEBUG, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
574 for (; it != end; ++it) {
575 // Skip escaped braces in the count
580 } else if (*it == '{') {
582 } else if (*it == '}') {
583 if (open_pars == 0) {
584 LYXERR(Debug::DEBUG, "Found unmatched closed brace");
590 if (open_pars != unmatched) {
591 LYXERR(Debug::DEBUG, "Found " << open_pars << " instead of " << unmatched << " unmatched open braces at the end of count");
594 LYXERR(Debug::DEBUG, "Braces match as expected");
598 /** The class performing a match between a position in the document and the FindAdvOptions.
600 class MatchStringAdv {
602 MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt);
604 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
605 ** constructor as opt.search, under the opt.* options settings.
608 ** If set, then match is searched only against beginning of text starting at cur.
609 ** If unset, then match is searched anywhere in text starting at cur.
612 ** The length of the matching text, or zero if no match was found.
614 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
618 lyx::Buffer const & buf;
620 FindAndReplaceOptions const & opt;
623 /** Normalize a stringified or latexified LyX paragraph.
627 ** <li>if search is not casesensitive, then lowercase the string;
628 ** <li>remove any newline at begin or end of the string;
629 ** <li>replace any newline in the middle of the string with a simple space;
630 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
633 ** @todo Normalization should also expand macros, if the corresponding
634 ** search option was checked.
636 string normalize(docstring const & s) const;
637 // normalized string to search
638 string par_as_string;
639 // regular expression to use for searching
641 // same as regexp, but prefixed with a ".*"
642 boost::regex regexp2;
643 // unmatched open braces in the search string/regexp
645 // number of (.*?) subexpressions added at end of search regexp for closing
646 // environments, math mode, styles, etc...
651 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt)
654 par_as_string = normalize(opt.search);
659 // Remove trailing closure of math, macros and environments, so to catch parts of them.
661 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
662 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
664 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
666 // @todo need to account for open square braces as well ?
667 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
669 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
671 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
677 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
678 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
679 LYXERR(Debug::DEBUG, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
681 par_as_string = escape_for_regex(par_as_string);
682 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
683 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
685 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
686 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
687 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
688 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
689 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
690 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
691 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
692 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
696 LYXERR(Debug::DEBUG, "par_as_string now is '" << par_as_string << "'");
697 LYXERR(Debug::DEBUG, "Open braces: " << open_braces);
698 LYXERR(Debug::DEBUG, "Close .*? : " << close_wildcards);
699 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
700 // Entered regexp must match at begin of searched string buffer
701 par_as_string = string("\\`") + par_as_string;
702 LYXERR(Debug::DEBUG, "Replaced text (to be used as regex): " << par_as_string);
703 regexp = boost::regex(par_as_string);
704 regexp2 = boost::regex(string(".*") + par_as_string);
709 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
711 docstring docstr = stringifyFromForSearch(opt, cur, len);
712 LYXERR(Debug::DEBUG, "Matching against '" << lyx::to_utf8(docstr) << "'");
713 string str = normalize(docstr);
714 LYXERR(Debug::DEBUG, "After normalization: '" << str << "'");
717 if (str.substr(0, par_as_string.size()) == par_as_string)
718 return par_as_string.size();
720 size_t pos = str.find(par_as_string);
721 if (pos != string::npos)
722 return par_as_string.size();
725 // Try all possible regexp matches, until one that verifies the braces match test is found
726 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
727 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
728 boost::sregex_iterator re_it_end;
729 for (; re_it != re_it_end; ++re_it) {
730 boost::match_results<string::const_iterator> const & m = *re_it;
731 // Check braces on the segment that matched the entire regexp expression,
732 // plus the last subexpression, if a (.*?) was inserted in the constructor.
733 if (! braces_match(m[0].first, m[0].second, open_braces))
735 // Check braces on segments that matched all (.*?) subexpressions.
736 for (size_t i = 1; i < m.size(); ++i)
737 if (! braces_match(m[i].first, m[i].second))
739 // Exclude from the returned match length any length due to close wildcards added at end of regexp
740 if (close_wildcards == 0)
741 return m[0].second - m[0].first;
743 return m[m.size() - close_wildcards].first - m[0].first;
750 string MatchStringAdv::normalize(docstring const & s) const
753 if (! opt.casesensitive)
754 t = lyx::to_utf8(lowercase(s));
757 // Remove \n at begin
758 while (t.size() > 0 && t[0] == '\n')
761 while (t.size() > 0 && t[t.size() - 1] == '\n')
762 t = t.substr(0, t.size() - 1);
764 // Replace all other \n with spaces
765 while ((pos = t.find("\n")) != string::npos)
766 t.replace(pos, 1, " ");
767 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
768 LYXERR(Debug::DEBUG, "Removing stale empty \emph{}, \textbf{} macros from: " << t);
769 while (regex_replace(t, t, "\\\\(emph|textbf)(\\{\\})+", ""))
770 LYXERR(Debug::DEBUG, " further removing stale empty \emph{}, \textbf{} macros from: " << t);
775 docstring stringifyFromCursor(DocIterator const & cur, int len)
777 LYXERR(Debug::DEBUG, "Stringifying with len=" << len << " from cursor at pos: " << cur);
778 if (cur.inTexted()) {
779 Paragraph const & par = cur.paragraph();
780 // TODO what about searching beyond/across paragraph breaks ?
781 // TODO Try adding a AS_STR_INSERTS as last arg
782 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ? int(par.size()) : cur.pos() + len;
783 OutputParams runparams(&cur.buffer()->params().encoding());
785 runparams.nice = true;
786 runparams.flavor = OutputParams::LATEX;
787 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
788 // No side effect of file copying and image conversion
789 runparams.dryrun = true;
790 LYXERR(Debug::DEBUG, "Stringifying with cur: " << cur << ", from pos: " << cur.pos() << ", end: " << end);
791 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
792 } else if (cur.inMathed()) {
794 CursorSlice cs = cur.top();
795 MathData md = cs.cell();
796 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cs.pos() + len );
797 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
801 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
805 /** Computes the LaTeX export of buf starting from cur and ending len positions
806 * after cur, if len is positive, or at the paragraph or innermost inset end
810 docstring latexifyFromCursor(DocIterator const & cur, int len)
812 LYXERR(Debug::DEBUG, "Latexifying with len=" << len << " from cursor at pos: " << cur);
813 LYXERR(Debug::DEBUG, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
814 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
815 Buffer const & buf = *cur.buffer();
816 LASSERT(buf.isLatex(), /* */);
819 odocstringstream ods;
820 OutputParams runparams(&buf.params().encoding());
821 runparams.nice = false;
822 runparams.flavor = OutputParams::LATEX;
823 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
824 // No side effect of file copying and image conversion
825 runparams.dryrun = true;
827 if (cur.inTexted()) {
828 // @TODO what about searching beyond/across paragraph breaks ?
829 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
830 for (int i = 0; i < cur.pit(); ++i)
832 // ParagraphList::const_iterator pit_end = pit;
834 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
835 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
836 ? pit->size() : cur.pos() + len;
837 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
839 LYXERR(Debug::DEBUG, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
840 } else if (cur.inMathed()) {
841 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
842 for (int s = cur.depth() - 1; s >= 0; --s) {
843 CursorSlice const & cs = cur[s];
844 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
846 cs.asInsetMath()->asHullInset()->header_write(ws);
851 CursorSlice const & cs = cur.top();
852 MathData md = cs.cell();
853 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
854 ? md.end() : md.begin() + cs.pos() + len );
855 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
858 // MathData md = cur.cell();
859 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
860 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
861 // MathAtom const & ma = *it;
862 // ma.nucleus()->latex(buf, ods, runparams);
865 // Retrieve the math environment type, and add '$' or '$]'
866 // or others (\end{equation}) accordingly
867 for (int s = cur.depth() - 1; s >= 0; --s) {
868 CursorSlice const & cs = cur[s];
869 InsetMath * inset = cs.asInsetMath();
870 if (inset && inset->asHullInset()) {
872 inset->asHullInset()->footer_write(ws);
876 LYXERR(Debug::DEBUG, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
878 LYXERR(Debug::DEBUG, "Don't know how to stringify from here: " << cur);
883 /** Finalize an advanced find operation, advancing the cursor to the innermost
884 ** position that matches, plus computing the length of the matching text to
887 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
889 // Search the foremost position that matches (avoids find of entire math
890 // inset when match at start of it)
892 DocIterator old_cur(cur.buffer());
894 LYXERR(Debug::DEBUG, "Forwarding one step (searching for innermost match)");
898 } while (cur && cur.depth() > d && match(cur) > 0);
900 LASSERT(match(cur) > 0, /* */);
901 LYXERR(Debug::DEBUG, "Ok");
903 // Compute the match length
905 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
906 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
908 LYXERR(Debug::DEBUG, "verifying unmatch with len = " << len);
910 // Length of matched text (different from len param)
911 int old_len = match(cur, len);
913 // Greedy behaviour while matching regexps
914 while ((new_len = match(cur, len + 1)) > old_len) {
917 LYXERR(Debug::DEBUG, "verifying match with len = " << len);
924 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
930 while (cur && !match(cur, -1, false)) {
931 if (cur.pit() < cur.lastpit())
937 for (; cur; cur.forwardPos()) {
939 return findAdvFinalize(cur, match);
941 wrap_answer = frontend::Alert::prompt(
943 _("End of document reached while searching forward\n"
945 "Continue searching from beginning ?"),
946 0, 1, _("&Yes"), _("&No"));
948 cur.push_back(CursorSlice(match.buf.inset()));
949 } while (wrap_answer == 0);
955 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
956 // if (cur.pos() > 0 || cur.depth() > 0)
957 // cur.backwardPos();
958 DocIterator cur_orig(cur);
960 findAdvFinalize(cur_orig, match);
961 // int total = cur.bottom().pit() + 1;
964 // TODO No ! così non va.
965 bool pit_changed = false;
966 while (cur && !match(cur, -1, false)) {
976 if (cur && pit_changed)
977 cur.pos() = cur.lastpos();
978 for (; cur; cur.backwardPos()) {
980 // Find the most backward consecutive match within same paragraph while searching backwards.
984 int len = findAdvFinalize(cur, match);
989 LYXERR(Debug::DEBUG, "old_cur: " << old_cur << ", old_len=" << len << ", cur: " << cur);
990 } while (cur && cur.pit() == pit && match(cur)
991 && (len = findAdvFinalize(cur, match)) > old_len);
994 LYXERR(Debug::DEBUG, "cur_orig : " << cur_orig);
995 LYXERR(Debug::DEBUG, "cur : " << cur);
1000 wrap_answer = frontend::Alert::prompt(
1002 _("Beginning of document reached while searching backwards\n"
1004 "Continue searching from end ?"),
1005 0, 1, _("&Yes"), _("&No"));
1006 cur = doc_iterator_end(&match.buf);
1008 } while (wrap_answer == 0);
1012 } // anonym namespace
1015 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1016 DocIterator const & cur, int len)
1018 if (!opt.ignoreformat)
1019 return latexifyFromCursor(cur, len);
1021 return stringifyFromCursor(cur, len);
1025 lyx::FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1026 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1027 bool regexp, docstring const & replace)
1028 : search(search), casesensitive(casesensitive), matchword(matchword),
1029 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1030 regexp(regexp), replace(replace)
1034 /// Perform a FindAdv operation.
1035 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1037 DocIterator cur = bv->cursor();
1040 if (opt.search.empty()) {
1041 bv->message(_("Search text is empty!"));
1044 // if (! bv->buffer()) {
1045 // bv->message(_("No open document !"));
1050 MatchStringAdv const matchAdv(bv->buffer(), opt);
1052 match_len = findForwardAdv(cur, matchAdv);
1054 match_len = findBackwardsAdv(cur, matchAdv);
1056 // This may only be raised by boost::regex()
1057 bv->message(_("Invalid regular expression!"));
1061 if (match_len == 0) {
1062 bv->message(_("Match not found!"));
1066 LYXERR(Debug::DEBUG, "Putting selection at " << cur << " with len: " << match_len);
1067 bv->putSelectionAt(cur, match_len, ! opt.forward);
1068 bv->message(_("Match found!"));
1069 if (opt.replace != docstring(from_utf8(LYX_FR_NULL_STRING))) {
1070 dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1077 void findAdv(BufferView * bv, FuncRequest const & ev)
1079 if (!bv || ev.action != LFUN_WORD_FINDADV)
1082 FindAndReplaceOptions opt;
1083 istringstream iss(to_utf8(ev.argument()));
1089 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1091 os << to_utf8(opt.search) << "\nEOSS\n"
1092 << opt.casesensitive << ' '
1093 << opt.matchword << ' '
1094 << opt.forward << ' '
1095 << opt.expandmacros << ' '
1096 << opt.ignoreformat << ' '
1097 << opt.regexp << ' '
1098 << to_utf8(opt.replace) << "\nEOSS\n";
1100 LYXERR(Debug::DEBUG, "built: " << os.str());
1105 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1107 LYXERR(Debug::DEBUG, "parsing");
1111 while (line != "EOSS") {
1115 if (is.eof()) // Tolerate malformed request
1119 LYXERR(Debug::DEBUG, "searching for: '" << s << "'");
1120 opt.search = from_utf8(s);
1121 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1122 is.get(); // Waste space before replace string
1125 while (line != "EOSS") {
1129 if (is.eof()) // Tolerate malformed request
1133 LYXERR(Debug::DEBUG, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1134 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp);
1135 LYXERR(Debug::DEBUG, "replacing with: '" << s << "'");
1136 opt.replace = from_utf8(s);