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 "frontends/Application.h"
51 #include "frontends/LyXView.h"
53 #include <boost/regex.hpp>
54 #include <boost/next_prior.hpp>
57 using namespace lyx::support;
63 bool parse_bool(docstring & howto)
68 howto = split(howto, var, ' ');
73 class MatchString : public binary_function<Paragraph, pos_type, bool>
76 MatchString(docstring const & str, bool cs, bool mw)
77 : str(str), cs(cs), mw(mw)
80 // returns true if the specified string is at the specified position
81 // del specifies whether deleted strings in ct mode will be considered
82 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
84 return par.find(str, cs, mw, pos, del);
92 // match whole words only
97 bool findForward(DocIterator & cur, MatchString const & match,
100 for (; cur; cur.forwardChar())
101 if (cur.inTexted() &&
102 match(cur.paragraph(), cur.pos(), find_del))
108 bool findBackwards(DocIterator & cur, MatchString const & match,
109 bool find_del = true)
113 if (cur.inTexted() &&
114 match(cur.paragraph(), cur.pos(), find_del))
121 bool findChange(DocIterator & cur, bool next)
125 for (; cur; next ? cur.forwardPos() : cur.backwardPos())
126 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
128 // if we search backwards, take a step forward
129 // to correctly set the anchor
138 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
141 frontend::Alert::error(_("Search error"), _("Search string is empty"));
148 bool find(BufferView * bv, docstring const & searchstr,
149 bool cs, bool mw, bool fw, bool find_del = true)
151 if (!searchAllowed(bv, searchstr))
154 DocIterator cur = bv->cursor();
156 MatchString const match(searchstr, cs, mw);
158 bool found = fw ? findForward(cur, match, find_del) :
159 findBackwards(cur, match, find_del);
162 bv->putSelectionAt(cur, searchstr.length(), !fw);
168 int replaceAll(BufferView * bv,
169 docstring const & searchstr, docstring const & replacestr,
172 Buffer & buf = bv->buffer();
174 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
177 MatchString const match(searchstr, cs, mw);
180 int const rsize = replacestr.size();
181 int const ssize = searchstr.size();
184 cur.setCursor(doc_iterator_begin(&buf));
185 while (findForward(cur, match, false)) {
186 // Backup current cursor position and font.
187 pos_type const pos = cur.pos();
188 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
190 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
191 buf.params().trackChanges);
192 cur.paragraph().insert(pos, replacestr, font,
193 Change(buf.params().trackChanges ?
194 Change::INSERTED : Change::UNCHANGED));
195 for (int i = 0; i < rsize + striked; ++i)
201 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
208 bool stringSelected(BufferView * bv, docstring & searchstr,
209 bool cs, bool mw, bool fw)
211 // if nothing selected and searched string is empty, this
212 // means that we want to search current word at cursor position.
213 if (!bv->cursor().selection() && searchstr.empty()) {
214 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
215 searchstr = bv->cursor().selectionAsString(false);
219 // if nothing selected or selection does not equal search
220 // string search and select next occurance and return
221 docstring const & str1 = searchstr;
222 docstring const str2 = bv->cursor().selectionAsString(false);
223 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
224 find(bv, searchstr, cs, mw, fw);
232 int replace(BufferView * bv, docstring & searchstr,
233 docstring const & replacestr, bool cs, bool mw, bool fw)
235 if (!stringSelected(bv, searchstr, cs, mw, fw))
238 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
241 Cursor & cur = bv->cursor();
242 cap::replaceSelectionWithString(cur, replacestr, fw);
243 bv->buffer().markDirty();
244 find(bv, searchstr, cs, mw, fw, false);
245 bv->buffer().updateMacros();
246 bv->processUpdateFlags(Update::Force | Update::FitCursor);
254 docstring const find2string(docstring const & search,
255 bool casesensitive, bool matchword, bool forward)
259 << int(casesensitive) << ' '
260 << int(matchword) << ' '
266 docstring const replace2string(docstring const & replace,
267 docstring const & search, bool casesensitive, bool matchword,
268 bool all, bool forward)
271 ss << replace << '\n'
273 << int(casesensitive) << ' '
274 << int(matchword) << ' '
281 bool find(BufferView * bv, FuncRequest const & ev)
283 if (!bv || ev.action != LFUN_WORD_FIND)
286 //lyxerr << "find called, cmd: " << ev << endl;
288 // data is of the form
290 // <casesensitive> <matchword> <forward>"
292 docstring howto = split(ev.argument(), search, '\n');
294 bool casesensitive = parse_bool(howto);
295 bool matchword = parse_bool(howto);
296 bool forward = parse_bool(howto);
298 return find(bv, search, casesensitive, matchword, forward);
302 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
304 if (!bv || ev.action != LFUN_WORD_REPLACE)
307 // data is of the form
310 // <casesensitive> <matchword> <all> <forward>"
313 docstring howto = split(ev.argument(), rplc, '\n');
314 howto = split(howto, search, '\n');
316 bool casesensitive = parse_bool(howto);
317 bool matchword = parse_bool(howto);
318 bool all = parse_bool(howto);
319 bool forward = parse_bool(howto);
322 int const replace_count = all
323 ? replaceAll(bv, search, rplc, casesensitive, matchword)
324 : replace(bv, search, rplc, casesensitive, matchword, forward);
326 Buffer & buf = bv->buffer();
327 if (replace_count == 0) {
328 // emit message signal.
329 buf.message(_("String not found!"));
331 if (replace_count == 1) {
332 // emit message signal.
333 buf.message(_("String has been replaced."));
335 docstring str = convert<docstring>(replace_count);
336 str += _(" strings have been replaced.");
337 // emit message signal.
342 // if we have deleted characters, we do not replace at all, but
343 // rather search for the next occurence
344 if (find(bv, search, casesensitive, matchword, forward))
347 bv->message(_("String not found!"));
352 bool findNextChange(BufferView * bv)
354 return findChange(bv, true);
358 bool findPreviousChange(BufferView * bv)
360 return findChange(bv, false);
364 bool findChange(BufferView * bv, bool next)
366 if (bv->cursor().selection()) {
367 // set the cursor at the beginning or at the end of the selection
368 // before searching. Otherwise, the current change will be found.
369 if (next != (bv->cursor().top() > bv->cursor().anchor()))
370 bv->cursor().setCursorToAnchor();
373 DocIterator cur = bv->cursor();
375 // Are we within a change ? Then first search forward (backward),
376 // clear the selection and search the other way around (see the end
377 // of this function). This will avoid changes to be selected half.
378 bool search_both_sides = false;
380 Change change_next_pos
381 = cur.paragraph().lookupChange(cur.pos());
382 Change change_prev_pos
383 = cur.paragraph().lookupChange(cur.pos() - 1);
384 if (change_next_pos.isSimilarTo(change_prev_pos))
385 search_both_sides = true;
388 if (!findChange(cur, next))
391 bv->cursor().setCursor(cur);
392 bv->cursor().resetAnchor();
395 // take a step into the change
398 Change orig_change = cur.paragraph().lookupChange(cur.pos());
400 CursorSlice & tip = cur.top();
402 for (; !tip.at_end(); tip.forwardPos()) {
403 Change change = tip.paragraph().lookupChange(tip.pos());
404 if (change != orig_change)
408 for (; !tip.at_begin();) {
410 Change change = tip.paragraph().lookupChange(tip.pos());
411 if (change != orig_change) {
412 // take a step forward to correctly set the selection
419 // Now put cursor to end of selection:
420 bv->cursor().setCursor(cur);
421 bv->cursor().setSelection();
423 if (search_both_sides) {
424 bv->cursor().setSelection(false);
425 findChange(bv, !next);
433 typedef vector<pair<string, string> > Escapes;
435 /// A map of symbols and their escaped equivalent needed within a regex.
436 Escapes const & get_regexp_escapes()
438 static Escapes escape_map;
439 if (escape_map.empty()) {
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>(")", "\\)"));
449 escape_map.push_back(pair<string, string>("+", "\\+"));
450 escape_map.push_back(pair<string, string>("*", "\\*"));
451 escape_map.push_back(pair<string, string>(".", "\\."));
456 /// A map of lyx escaped strings and their unescaped equivalent.
457 Escapes const & get_lyx_unescapes() {
458 static Escapes escape_map;
459 if (escape_map.empty()) {
460 escape_map.push_back(pair<string, string>("{*}", "*"));
461 escape_map.push_back(pair<string, string>("{[}", "["));
462 escape_map.push_back(pair<string, string>("\\$", "$"));
463 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
464 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
465 escape_map.push_back(pair<string, string>("\\sim ", "~"));
466 escape_map.push_back(pair<string, string>("\\^", "^"));
471 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
472 ** the found occurrence were escaped.
474 string apply_escapes(string s, Escapes const & escape_map)
476 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
477 Escapes::const_iterator it;
478 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
479 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
480 unsigned int pos = 0;
481 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
482 s.replace(pos, it->first.length(), it->second);
483 // LYXERR(Debug::FIND, "After escape: " << s);
484 pos += it->second.length();
485 // LYXERR(Debug::FIND, "pos: " << pos);
488 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
492 /** Return the position of the closing brace matching the open one at s[pos],
493 ** or s.size() if not found.
495 size_t find_matching_brace(string const & s, size_t pos)
497 LASSERT(s[pos] == '{', /* */);
499 for (++pos; pos < s.size(); ++pos) {
502 else if (s[pos] == '{')
504 else if (s[pos] == '}') {
506 if (open_braces == 0)
513 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
514 string escape_for_regex(string s)
517 while (pos < s.size()) {
518 size_t new_pos = s.find("\\regexp{", pos);
519 if (new_pos == string::npos)
521 LYXERR(Debug::FIND, "new_pos: " << new_pos);
522 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
523 LYXERR(Debug::FIND, "t : " << t);
524 t = apply_escapes(t, get_regexp_escapes());
525 s.replace(pos, new_pos - pos, t);
526 new_pos = pos + t.size();
527 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
528 LYXERR(Debug::FIND, "new_pos: " << new_pos);
529 if (new_pos == s.size())
531 size_t end_pos = find_matching_brace(s, new_pos + 7);
532 LYXERR(Debug::FIND, "end_pos: " << end_pos);
533 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
534 LYXERR(Debug::FIND, "t : " << t);
535 if (end_pos == s.size()) {
536 s.replace(new_pos, end_pos - new_pos, t);
538 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
541 s.replace(new_pos, end_pos + 1 - new_pos, t);
542 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
543 pos = new_pos + t.size();
544 LYXERR(Debug::FIND, "pos: " << pos);
549 /// Wrapper for boost::regex_replace with simpler interface
550 bool regex_replace(string const & s, string & t, string const & searchstr,
551 string const & replacestr)
553 boost::regex e(searchstr);
555 ostream_iterator<char, char> it(oss);
556 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
557 // tolerate t and s be references to the same variable
558 bool rv = (s != oss.str());
563 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
565 ** Verify that closed braces exactly match open braces. This avoids that, for example,
566 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
569 ** Number of open braces that must remain open at the end for the verification to succeed.
571 bool braces_match(string::const_iterator const & beg,
572 string::const_iterator const & end, int unmatched = 0)
575 string::const_iterator it = beg;
576 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
577 for (; it != end; ++it) {
578 // Skip escaped braces in the count
583 } else if (*it == '{') {
585 } else if (*it == '}') {
586 if (open_pars == 0) {
587 LYXERR(Debug::FIND, "Found unmatched closed brace");
593 if (open_pars != unmatched) {
594 LYXERR(Debug::FIND, "Found " << open_pars
595 << " instead of " << unmatched
596 << " unmatched open braces at the end of count");
599 LYXERR(Debug::FIND, "Braces match as expected");
603 /** The class performing a match between a position in the document and the FindAdvOptions.
605 class MatchStringAdv {
607 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
609 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
610 ** constructor as opt.search, under the opt.* options settings.
613 ** If set, then match is searched only against beginning of text starting at cur.
614 ** If unset, then match is searched anywhere in text starting at cur.
617 ** The length of the matching text, or zero if no match was found.
619 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
624 /// first buffer on which search was started
625 lyx::Buffer * const p_first_buf;
627 FindAndReplaceOptions const & opt;
630 /** Normalize a stringified or latexified LyX paragraph.
634 ** <li>if search is not casesensitive, then lowercase the string;
635 ** <li>remove any newline at begin or end of the string;
636 ** <li>replace any newline in the middle of the string with a simple space;
637 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
640 ** @todo Normalization should also expand macros, if the corresponding
641 ** search option was checked.
643 string normalize(docstring const & s) const;
644 // normalized string to search
645 string par_as_string;
646 // regular expression to use for searching
648 // same as regexp, but prefixed with a ".*"
649 boost::regex regexp2;
650 // unmatched open braces in the search string/regexp
652 // number of (.*?) subexpressions added at end of search regexp for closing
653 // environments, math mode, styles, etc...
658 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
659 : p_buf(&buf), p_first_buf(&buf), opt(opt)
661 par_as_string = normalize(opt.search);
666 // Remove trailing closure of math, macros and environments, so to catch parts of them.
668 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
669 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
671 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
673 // @todo need to account for open square braces as well ?
674 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
676 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
678 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
684 LYXERR(Debug::FIND, "Open braces: " << open_braces);
685 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
686 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
688 par_as_string = escape_for_regex(par_as_string);
689 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
690 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
692 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
693 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
694 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
695 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
696 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
697 || regex_replace(par_as_string, par_as_string,
698 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
699 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
700 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
704 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
705 LYXERR(Debug::FIND, "Open braces: " << open_braces);
706 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
707 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
708 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
709 // If entered regexp must match at begin of searched string buffer
710 regexp = boost::regex(string("\\`") + par_as_string);
711 // If entered regexp may match wherever in searched string buffer
712 regexp2 = boost::regex(string("\\`.*") + par_as_string);
717 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
719 docstring docstr = stringifyFromForSearch(opt, cur, len);
720 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
721 string str = normalize(docstr);
722 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
725 if (str.substr(0, par_as_string.size()) == par_as_string)
726 return par_as_string.size();
728 size_t pos = str.find(par_as_string);
729 if (pos != string::npos)
730 return par_as_string.size();
733 // Try all possible regexp matches,
734 //until one that verifies the braces match test is found
735 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
736 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
737 boost::sregex_iterator re_it_end;
738 for (; re_it != re_it_end; ++re_it) {
739 boost::match_results<string::const_iterator> const & m = *re_it;
740 // Check braces on the segment that matched the entire regexp expression,
741 // plus the last subexpression, if a (.*?) was inserted in the constructor.
742 if (! braces_match(m[0].first, m[0].second, open_braces))
744 // Check braces on segments that matched all (.*?) subexpressions.
745 for (size_t i = 1; i < m.size(); ++i)
746 if (! braces_match(m[i].first, m[i].second))
748 // Exclude from the returned match length any length
749 // due to close wildcards added at end of regexp
750 if (close_wildcards == 0)
751 return m[0].second - m[0].first;
753 return m[m.size() - close_wildcards].first - m[0].first;
760 string MatchStringAdv::normalize(docstring const & s) const
763 if (! opt.casesensitive)
764 t = lyx::to_utf8(lowercase(s));
767 // Remove \n at begin
768 while (t.size() > 0 && t[0] == '\n')
771 while (t.size() > 0 && t[t.size() - 1] == '\n')
772 t = t.substr(0, t.size() - 1);
774 // Replace all other \n with spaces
775 while ((pos = t.find("\n")) != string::npos)
776 t.replace(pos, 1, " ");
777 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
778 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
779 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
780 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
785 docstring stringifyFromCursor(DocIterator const & cur, int len)
787 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
788 if (cur.inTexted()) {
789 Paragraph const & par = cur.paragraph();
790 // TODO what about searching beyond/across paragraph breaks ?
791 // TODO Try adding a AS_STR_INSERTS as last arg
792 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
793 int(par.size()) : cur.pos() + len;
794 OutputParams runparams(&cur.buffer()->params().encoding());
796 runparams.nice = true;
797 runparams.flavor = OutputParams::LATEX;
798 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
799 // No side effect of file copying and image conversion
800 runparams.dryrun = true;
801 LYXERR(Debug::FIND, "Stringifying with cur: "
802 << cur << ", from pos: " << cur.pos() << ", end: " << end);
803 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
804 } else if (cur.inMathed()) {
806 CursorSlice cs = cur.top();
807 MathData md = cs.cell();
808 MathData::const_iterator it_end =
809 ( ( len == -1 || cs.pos() + len > int(md.size()) )
810 ? md.end() : md.begin() + cs.pos() + len );
811 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
815 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
820 /** Computes the LaTeX export of buf starting from cur and ending len positions
821 * after cur, if len is positive, or at the paragraph or innermost inset end
824 docstring latexifyFromCursor(DocIterator const & cur, int len)
826 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
827 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
828 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
829 Buffer const & buf = *cur.buffer();
830 LASSERT(buf.isLatex(), /* */);
833 odocstringstream ods;
834 OutputParams runparams(&buf.params().encoding());
835 runparams.nice = false;
836 runparams.flavor = OutputParams::LATEX;
837 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
838 // No side effect of file copying and image conversion
839 runparams.dryrun = true;
841 if (cur.inTexted()) {
842 // @TODO what about searching beyond/across paragraph breaks ?
843 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
844 for (int i = 0; i < cur.pit(); ++i)
846 // ParagraphList::const_iterator pit_end = pit;
848 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
849 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
850 ? pit->size() : cur.pos() + len;
851 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
853 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
854 } else if (cur.inMathed()) {
855 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
856 for (int s = cur.depth() - 1; s >= 0; --s) {
857 CursorSlice const & cs = cur[s];
858 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
860 cs.asInsetMath()->asHullInset()->header_write(ws);
865 CursorSlice const & cs = cur.top();
866 MathData md = cs.cell();
867 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
868 ? md.end() : md.begin() + cs.pos() + len );
869 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
872 // MathData md = cur.cell();
873 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
874 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
875 // MathAtom const & ma = *it;
876 // ma.nucleus()->latex(buf, ods, runparams);
879 // Retrieve the math environment type, and add '$' or '$]'
880 // or others (\end{equation}) accordingly
881 for (int s = cur.depth() - 1; s >= 0; --s) {
882 CursorSlice const & cs = cur[s];
883 InsetMath * inset = cs.asInsetMath();
884 if (inset && inset->asHullInset()) {
886 inset->asHullInset()->footer_write(ws);
890 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
892 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
898 /** Finalize an advanced find operation, advancing the cursor to the innermost
899 ** position that matches, plus computing the length of the matching text to
902 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
904 // Search the foremost position that matches (avoids find of entire math
905 // inset when match at start of it)
907 DocIterator old_cur(cur.buffer());
909 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
913 } while (cur && cur.depth() > d && match(cur) > 0);
915 LASSERT(match(cur) > 0, /* */);
916 LYXERR(Debug::FIND, "Ok");
918 // Compute the match length
920 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
921 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
923 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
925 // Length of matched text (different from len param)
926 int old_len = match(cur, len);
928 // Greedy behaviour while matching regexps
929 while ((new_len = match(cur, len + 1)) > old_len) {
932 LYXERR(Debug::FIND, "verifying match with len = " << len);
938 /** Switch p_buf to point to next document buffer.
940 ** Return true if restarted from master-document buffer.
943 ** Not using p_buf->allRelatives() here, because I'm not sure
944 ** whether or not the returned order is independent of p_buf.
946 bool next_document_buffer(Buffer * & p_buf) {
947 Buffer *p_master = p_buf;
951 p_master = const_cast<Buffer *>(p_master->masterBuffer());
952 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
953 } while (p_master != p_old);
954 LASSERT(p_master != NULL, /**/);
955 std::vector<Buffer *> v_children;
956 /* Root master added as first buffer in the vector */
957 v_children.push_back(p_master);
958 p_master->getChildren(v_children, true);
959 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
960 std::vector<Buffer *>::const_iterator it = std::find(v_children.begin(), v_children.end(), p_buf);
961 LASSERT(it != v_children.end(), /**/)
963 if (it == v_children.end()) {
964 p_buf = *v_children.begin();
972 /** Switch p_buf to point to previous document buffer.
974 ** Return true if restarted from last child buffer.
977 ** Not using p_buf->allRelatives() here, because I'm not sure
978 ** whether or not the returned order is independent of p_buf.
980 bool prev_document_buffer(Buffer * & p_buf) {
981 Buffer *p_master = p_buf;
985 p_master = const_cast<Buffer *>(p_master->masterBuffer());
986 LYXERR(Debug::FIND, "p_old=" << p_old << ", p_master=" << p_master);
987 } while (p_master != p_old);
988 LASSERT(p_master != NULL, /**/);
989 std::vector<Buffer *> v_children;
990 /* Root master added as first buffer in the vector */
991 v_children.push_back(p_master);
992 p_master->getChildren(v_children, true);
993 LYXERR(Debug::FIND, "v_children.size()=" << v_children.size());
994 std::vector<Buffer *>::const_iterator it = std::find(v_children.begin(), v_children.end(), p_buf);
995 LASSERT(it != v_children.end(), /**/)
996 if (it == v_children.begin()) {
997 it = v_children.end();
1009 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1013 int wrap_answer = -1;
1015 while (cur && !match(cur, -1, false)) {
1016 if (cur.pit() < cur.lastpit())
1022 for (; cur; cur.forwardPos()) {
1024 return findAdvFinalize(cur, match);
1026 // No match has been found in current buffer
1027 bool prompt = false;
1028 if (match.opt.scope == FindAndReplaceOptions::S_BUFFER) {
1030 } else if (match.opt.scope == FindAndReplaceOptions::S_DOCUMENT) {
1031 prompt = next_document_buffer(match.p_buf);
1033 /* Unimplemented scope */
1034 LASSERT(false, /**/);
1037 if (wrap_answer != -1)
1039 wrap_answer = frontend::Alert::prompt(
1041 _("End of document/scope reached while searching forward.\n"
1043 "Continue searching from beginning?"),
1044 0, 1, _("&Yes"), _("&No"));
1047 cur.push_back(CursorSlice(match.p_buf->inset()));
1048 } while (wrap_answer != 1);
1052 /// Find the most backward consecutive match within same paragraph while searching backwards.
1053 void findMostBackwards(DocIterator & cur, MatchStringAdv const & match, int & len) {
1054 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1055 len = findAdvFinalize(cur, match);
1056 if (cur != cur_begin) {
1057 Inset & inset = cur.inset();
1059 DocIterator old_cur;
1065 LYXERR(Debug::FIND, "findMostBackwards(): old_cur="
1066 << old_cur << ", old_len=" << len << ", cur=" << cur);
1068 } while (cur != cur_begin && &cur.inset() == &inset && match(cur)
1069 && (len = findAdvFinalize(dit2, match)) > old_len);
1073 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1077 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1080 // Backup of original position (for restoring it in case match not found)
1081 DocIterator cur_orig(cur);
1082 // Position beyond which match is not considered
1083 // (set to end of document after wrap-around question)
1084 DocIterator cur_orig2(cur);
1085 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1086 /* if (match(cur_orig)) */
1087 /* findAdvFinalize(cur_orig, match); */
1088 int wrap_answer = 0;
1091 bool pit_changed = false;
1092 found_match = false;
1093 // Search in current par occurs from start to end,
1094 // but in next loop match is discarded if pos > original pos
1096 found_match = match(cur, -1, false);
1097 LYXERR(Debug::FIND, "findBackAdv0: found_match=" << found_match << ", cur: " << cur);
1098 while (cur != cur_begin) {
1106 // Search in previous pars occurs from start to end
1108 found_match = match(cur, -1, false);
1109 LYXERR(Debug::FIND, "findBackAdv1: found_match="
1110 << found_match << ", cur: " << cur);
1113 cur.pos() = cur.lastpos();
1115 cur.pos() = cur_orig2.pos();
1116 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1117 DocIterator cur_prev_iter;
1120 found_match=match(cur);
1121 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1122 << found_match << ", cur: " << cur);
1125 findMostBackwards(cur, match, len);
1126 if (&cur.inset() != &cur_orig2.inset()
1127 || !(cur.pit() == cur_orig2.pit())
1128 || cur.pos() < cur_orig2.pos())
1131 // Prevent infinite loop at begin of document
1132 if (cur == cur_begin || cur == cur_prev_iter)
1134 cur_prev_iter = cur;
1138 // No match has been found in current buffer
1139 bool prompt = false;
1140 if (match.opt.scope == FindAndReplaceOptions::S_BUFFER) {
1142 } else if (match.opt.scope == FindAndReplaceOptions::S_DOCUMENT) {
1143 prompt = prev_document_buffer(match.p_buf);
1145 /* Unimplemented scope */
1146 LASSERT(false, /**/);
1149 wrap_answer = frontend::Alert::prompt(
1151 _("Beginning of document/scope reached while searching backwards\n"
1153 "Continue searching from end?"),
1154 0, 1, _("&Yes"), _("&No"));
1156 cur = doc_iterator_end(match.p_buf);
1158 LYXERR(Debug::FIND, "findBackAdv5: cur: " << cur);
1160 } while (wrap_answer == 0);
1166 } // anonym namespace
1169 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1170 DocIterator const & cur, int len)
1172 if (!opt.ignoreformat)
1173 return latexifyFromCursor(cur, len);
1175 return stringifyFromCursor(cur, len);
1179 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1180 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1181 bool regexp, docstring const & replace, bool keep_case,
1183 : search(search), casesensitive(casesensitive), matchword(matchword),
1184 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1185 regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1190 /** Checks if the supplied character is lower-case */
1191 static bool isLowerCase(char_type ch) {
1192 return lowercase(ch) == ch;
1196 /** Checks if the supplied character is upper-case */
1197 static bool isUpperCase(char_type ch) {
1198 return uppercase(ch) == ch;
1202 /** Check if 'len' letters following cursor are all non-lowercase */
1203 static bool allNonLowercase(DocIterator const & cur, int len) {
1204 pos_type end_pos = cur.pos() + len;
1205 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1206 if (isLowerCase(cur.paragraph().getChar(pos)))
1212 /** Check if first letter is upper case and second one is lower case */
1213 static bool firstUppercase(DocIterator const & cur) {
1215 if (cur.pos() >= cur.lastpos() - 1) {
1216 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1219 ch1 = cur.paragraph().getChar(cur.pos());
1220 ch2 = cur.paragraph().getChar(cur.pos()+1);
1221 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1222 LYXERR(Debug::FIND, "firstUppercase(): "
1223 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1224 << ch2 << "(" << char(ch2) << ")"
1225 << ", result=" << result << ", cur=" << cur);
1230 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1232 ** \fixme What to do with possible further paragraphs in replace buffer ?
1234 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1235 ParagraphList::iterator pit = buffer.paragraphs().begin();
1236 pos_type right = pos_type(1);
1237 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1238 right = pit->size() + 1;
1239 pit->changeCase(buffer.params(), right, right, others_case);
1243 /// Perform a FindAdv operation.
1244 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1246 DocIterator cur = bv->cursor();
1249 if (opt.search.empty()) {
1250 bv->message(_("Search text is empty!"));
1253 // if (! bv->buffer()) {
1254 // bv->message(_("No open document !"));
1258 MatchStringAdv matchAdv(bv->buffer(), opt);
1261 match_len = findForwardAdv(cur, matchAdv);
1263 match_len = findBackwardsAdv(cur, matchAdv);
1265 // This may only be raised by boost::regex()
1266 bv->message(_("Invalid regular expression!"));
1270 if (match_len == 0) {
1271 bv->message(_("Match not found!"));
1275 LYXERR(Debug::FIND, "Putting selection at buf=" << matchAdv.p_buf
1276 << "cur=" << cur << " with len: " << match_len);
1278 theApp()->currentWindow()->selectDocumentBuffer(matchAdv.p_buf);
1279 bv = theApp()->currentWindow()->documentBufferView();
1281 bv->putSelectionAt(cur, match_len, ! opt.forward);
1282 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING))) {
1283 bv->message(_("Match found !"));
1285 string lyx = to_utf8(opt.replace);
1286 // FIXME: Seems so stupid to me to rebuild a buffer here,
1287 // when we already have one (replace_work_area_.buffer())
1288 Buffer repl_buffer("", false);
1289 repl_buffer.setUnnamed(true);
1290 if (repl_buffer.readString(lyx)) {
1291 if (opt.keep_case && match_len >= 2) {
1292 if (cur.inTexted()) {
1293 if (firstUppercase(cur))
1294 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1295 else if (allNonLowercase(cur, match_len))
1296 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1299 cap::cutSelection(bv->cursor(), false, false);
1300 if (! cur.inMathed()) {
1301 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1302 cap::pasteParagraphList(bv->cursor(), repl_buffer.paragraphs(),
1303 repl_buffer.params().documentClassPtr(),
1304 bv->buffer().errorList("Paste"));
1306 odocstringstream ods;
1307 OutputParams runparams(&repl_buffer.params().encoding());
1308 runparams.nice = false;
1309 runparams.flavor = OutputParams::LATEX;
1310 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1311 runparams.dryrun = true;
1313 TeXOnePar(repl_buffer, repl_buffer.text(),
1314 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1315 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1316 docstring repl_latex = ods.str();
1317 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1319 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1320 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1321 repl_latex = from_utf8(s);
1322 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1323 bv->cursor().niceInsert(repl_latex);
1325 bv->putSelectionAt(cur, repl_buffer.paragraphs().begin()->size(), ! opt.forward);
1326 bv->message(_("Match found and replaced !"));
1328 LASSERT(false, /**/);
1329 // dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1336 void findAdv(BufferView * bv, FuncRequest const & ev)
1338 if (!bv || ev.action != LFUN_WORD_FINDADV)
1341 FindAndReplaceOptions opt;
1342 istringstream iss(to_utf8(ev.argument()));
1348 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1350 os << to_utf8(opt.search) << "\nEOSS\n"
1351 << opt.casesensitive << ' '
1352 << opt.matchword << ' '
1353 << opt.forward << ' '
1354 << opt.expandmacros << ' '
1355 << opt.ignoreformat << ' '
1356 << opt.regexp << ' '
1357 << to_utf8(opt.replace) << "\nEOSS\n"
1358 << opt.keep_case << ' '
1361 LYXERR(Debug::FIND, "built: " << os.str());
1366 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1368 LYXERR(Debug::FIND, "parsing");
1372 while (line != "EOSS") {
1376 if (is.eof()) // Tolerate malformed request
1380 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1381 opt.search = from_utf8(s);
1382 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1383 is.get(); // Waste space before replace string
1386 while (line != "EOSS") {
1390 if (is.eof()) // Tolerate malformed request
1394 is >> opt.keep_case;
1397 opt.scope = FindAndReplaceOptions::SearchScope(i);
1398 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1399 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1400 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1401 opt.replace = from_utf8(s);