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 "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
36 #include "frontends/alert.h"
38 #include "mathed/InsetMath.h"
39 #include "mathed/InsetMathGrid.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathStream.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.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;
376 DocIterator tmpcur = cur;
378 while (tmpcur.inMathed())
380 Change change_next_pos
381 = tmpcur.paragraph().lookupChange(tmpcur.pos());
382 if (change_next_pos.changed() && cur.inMathed()) {
384 search_both_sides = true;
385 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
386 Change change_prev_pos
387 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
388 if (change_next_pos.isSimilarTo(change_prev_pos))
389 search_both_sides = true;
392 if (!findChange(cur, next))
395 bv->cursor().setCursor(cur);
396 bv->cursor().resetAnchor();
399 // take a step into the change
402 Change orig_change = cur.paragraph().lookupChange(cur.pos());
404 CursorSlice & tip = cur.top();
406 for (; !tip.at_end(); tip.forwardPos()) {
407 Change change = tip.paragraph().lookupChange(tip.pos());
408 if (change != orig_change)
412 for (; !tip.at_begin();) {
414 Change change = tip.paragraph().lookupChange(tip.pos());
415 if (change != orig_change) {
416 // take a step forward to correctly set the selection
423 // Now put cursor to end of selection:
424 bv->cursor().setCursor(cur);
425 bv->cursor().setSelection();
427 if (search_both_sides) {
428 bv->cursor().setSelection(false);
429 findChange(bv, !next);
437 typedef vector<pair<string, string> > Escapes;
439 /// A map of symbols and their escaped equivalent needed within a regex.
440 Escapes const & get_regexp_escapes()
442 static Escapes escape_map;
443 if (escape_map.empty()) {
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>("(", "\\("));
452 escape_map.push_back(pair<string, string>(")", "\\)"));
453 escape_map.push_back(pair<string, string>("+", "\\+"));
454 escape_map.push_back(pair<string, string>("*", "\\*"));
455 escape_map.push_back(pair<string, string>(".", "\\."));
460 /// A map of lyx escaped strings and their unescaped equivalent.
461 Escapes const & get_lyx_unescapes() {
462 static Escapes escape_map;
463 if (escape_map.empty()) {
464 escape_map.push_back(pair<string, string>("{*}", "*"));
465 escape_map.push_back(pair<string, string>("{[}", "["));
466 escape_map.push_back(pair<string, string>("\\$", "$"));
467 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
468 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
469 escape_map.push_back(pair<string, string>("\\sim ", "~"));
470 escape_map.push_back(pair<string, string>("\\^", "^"));
475 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
476 ** the found occurrence were escaped.
478 string apply_escapes(string s, Escapes const & escape_map)
480 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
481 Escapes::const_iterator it;
482 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
483 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
484 unsigned int pos = 0;
485 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
486 s.replace(pos, it->first.length(), it->second);
487 // LYXERR(Debug::FIND, "After escape: " << s);
488 pos += it->second.length();
489 // LYXERR(Debug::FIND, "pos: " << pos);
492 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
496 /** Return the position of the closing brace matching the open one at s[pos],
497 ** or s.size() if not found.
499 size_t find_matching_brace(string const & s, size_t pos)
501 LASSERT(s[pos] == '{', /* */);
503 for (++pos; pos < s.size(); ++pos) {
506 else if (s[pos] == '{')
508 else if (s[pos] == '}') {
510 if (open_braces == 0)
517 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
518 string escape_for_regex(string s)
521 while (pos < s.size()) {
522 size_t new_pos = s.find("\\regexp{", pos);
523 if (new_pos == string::npos)
525 LYXERR(Debug::FIND, "new_pos: " << new_pos);
526 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
527 LYXERR(Debug::FIND, "t : " << t);
528 t = apply_escapes(t, get_regexp_escapes());
529 s.replace(pos, new_pos - pos, t);
530 new_pos = pos + t.size();
531 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
532 LYXERR(Debug::FIND, "new_pos: " << new_pos);
533 if (new_pos == s.size())
535 size_t end_pos = find_matching_brace(s, new_pos + 7);
536 LYXERR(Debug::FIND, "end_pos: " << end_pos);
537 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
538 LYXERR(Debug::FIND, "t : " << t);
539 if (end_pos == s.size()) {
540 s.replace(new_pos, end_pos - new_pos, t);
542 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
545 s.replace(new_pos, end_pos + 1 - new_pos, t);
546 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
547 pos = new_pos + t.size();
548 LYXERR(Debug::FIND, "pos: " << pos);
553 /// Wrapper for boost::regex_replace with simpler interface
554 bool regex_replace(string const & s, string & t, string const & searchstr,
555 string const & replacestr)
557 boost::regex e(searchstr);
559 ostream_iterator<char, char> it(oss);
560 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
561 // tolerate t and s be references to the same variable
562 bool rv = (s != oss.str());
567 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
569 ** Verify that closed braces exactly match open braces. This avoids that, for example,
570 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
573 ** Number of open braces that must remain open at the end for the verification to succeed.
575 bool braces_match(string::const_iterator const & beg,
576 string::const_iterator const & end, int unmatched = 0)
579 string::const_iterator it = beg;
580 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
581 for (; it != end; ++it) {
582 // Skip escaped braces in the count
587 } else if (*it == '{') {
589 } else if (*it == '}') {
590 if (open_pars == 0) {
591 LYXERR(Debug::FIND, "Found unmatched closed brace");
597 if (open_pars != unmatched) {
598 LYXERR(Debug::FIND, "Found " << open_pars
599 << " instead of " << unmatched
600 << " unmatched open braces at the end of count");
603 LYXERR(Debug::FIND, "Braces match as expected");
607 /** The class performing a match between a position in the document and the FindAdvOptions.
609 class MatchStringAdv {
611 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
613 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
614 ** constructor as opt.search, under the opt.* options settings.
617 ** If set, then match is searched only against beginning of text starting at cur.
618 ** If unset, then match is searched anywhere in text starting at cur.
621 ** The length of the matching text, or zero if no match was found.
623 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
628 /// first buffer on which search was started
629 lyx::Buffer * const p_first_buf;
631 FindAndReplaceOptions const & opt;
634 /// Auxiliary find method (does not account for opt.matchword)
635 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
637 /** Normalize a stringified or latexified LyX paragraph.
641 ** <li>if search is not casesensitive, then lowercase the string;
642 ** <li>remove any newline at begin or end of the string;
643 ** <li>replace any newline in the middle of the string with a simple space;
644 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
647 ** @todo Normalization should also expand macros, if the corresponding
648 ** search option was checked.
650 string normalize(docstring const & s) const;
651 // normalized string to search
652 string par_as_string;
653 // regular expression to use for searching
655 // same as regexp, but prefixed with a ".*"
656 boost::regex regexp2;
657 // unmatched open braces in the search string/regexp
659 // number of (.*?) subexpressions added at end of search regexp for closing
660 // environments, math mode, styles, etc...
665 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
666 : p_buf(&buf), p_first_buf(&buf), opt(opt)
668 par_as_string = normalize(opt.search);
673 // Remove trailing closure of math, macros and environments, so to catch parts of them.
675 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
676 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
678 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
680 // @todo need to account for open square braces as well ?
681 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
683 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
685 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
691 LYXERR(Debug::FIND, "Open braces: " << open_braces);
692 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
693 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
695 par_as_string = escape_for_regex(par_as_string);
696 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
697 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
699 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
700 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
701 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
702 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
703 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
704 || regex_replace(par_as_string, par_as_string,
705 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
706 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
707 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
711 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
712 LYXERR(Debug::FIND, "Open braces: " << open_braces);
713 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
714 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
715 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
716 // If entered regexp must match at begin of searched string buffer
717 regexp = boost::regex(string("\\`") + par_as_string);
718 // If entered regexp may match wherever in searched string buffer
719 regexp2 = boost::regex(string("\\`.*") + par_as_string);
724 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
726 docstring docstr = stringifyFromForSearch(opt, cur, len);
727 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
728 string str = normalize(docstr);
729 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
732 if (str.substr(0, par_as_string.size()) == par_as_string)
733 return par_as_string.size();
735 size_t pos = str.find(par_as_string);
736 if (pos != string::npos)
737 return par_as_string.size();
740 // Try all possible regexp matches,
741 //until one that verifies the braces match test is found
742 boost::regex const *p_regexp = at_begin ? ®exp : ®exp2;
743 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
744 boost::sregex_iterator re_it_end;
745 for (; re_it != re_it_end; ++re_it) {
746 boost::match_results<string::const_iterator> const & m = *re_it;
747 // Check braces on the segment that matched the entire regexp expression,
748 // plus the last subexpression, if a (.*?) was inserted in the constructor.
749 if (! braces_match(m[0].first, m[0].second, open_braces))
751 // Check braces on segments that matched all (.*?) subexpressions.
752 for (size_t i = 1; i < m.size(); ++i)
753 if (! braces_match(m[i].first, m[i].second))
755 // Exclude from the returned match length any length
756 // due to close wildcards added at end of regexp
757 if (close_wildcards == 0)
758 return m[0].second - m[0].first;
760 return m[m.size() - close_wildcards].first - m[0].first;
767 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
769 int res = findAux(cur, len, at_begin);
770 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
772 Paragraph const & par = cur.paragraph();
773 bool ws_left = cur.pos() > 0 ?
774 par.isWordSeparator(cur.pos() - 1) : true;
775 bool ws_right = cur.pos() + res < par.size() ?
776 par.isWordSeparator(cur.pos() + res) : true;
778 "cur.pos()=" << cur.pos() << ", res=" << res
779 << ", separ: " << ws_left << ", " << ws_right
781 if (ws_left && ws_right)
787 string MatchStringAdv::normalize(docstring const & s) const
790 if (! opt.casesensitive)
791 t = lyx::to_utf8(lowercase(s));
794 // Remove \n at begin
795 while (t.size() > 0 && t[0] == '\n')
798 while (t.size() > 0 && t[t.size() - 1] == '\n')
799 t = t.substr(0, t.size() - 1);
801 // Replace all other \n with spaces
802 while ((pos = t.find("\n")) != string::npos)
803 t.replace(pos, 1, " ");
804 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
805 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
806 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
807 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
808 regex_replace(t, t, "\\{", "@##£$%@(");
809 regex_replace(t, t, "\\}", "@##£$%@)");
814 docstring stringifyFromCursor(DocIterator const & cur, int len)
816 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
817 if (cur.inTexted()) {
818 Paragraph const & par = cur.paragraph();
819 // TODO what about searching beyond/across paragraph breaks ?
820 // TODO Try adding a AS_STR_INSERTS as last arg
821 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
822 int(par.size()) : cur.pos() + len;
823 OutputParams runparams(&cur.buffer()->params().encoding());
825 runparams.nice = true;
826 runparams.flavor = OutputParams::LATEX;
827 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
828 // No side effect of file copying and image conversion
829 runparams.dryrun = true;
830 LYXERR(Debug::FIND, "Stringifying with cur: "
831 << cur << ", from pos: " << cur.pos() << ", end: " << end);
832 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
833 } else if (cur.inMathed()) {
835 CursorSlice cs = cur.top();
836 MathData md = cs.cell();
837 MathData::const_iterator it_end =
838 ( ( len == -1 || cs.pos() + len > int(md.size()) )
839 ? md.end() : md.begin() + cs.pos() + len );
840 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
844 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
849 /** Computes the LaTeX export of buf starting from cur and ending len positions
850 * after cur, if len is positive, or at the paragraph or innermost inset end
853 docstring latexifyFromCursor(DocIterator const & cur, int len)
855 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
856 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
857 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
858 Buffer const & buf = *cur.buffer();
859 LASSERT(buf.isLatex(), /* */);
862 odocstringstream ods;
863 OutputParams runparams(&buf.params().encoding());
864 runparams.nice = false;
865 runparams.flavor = OutputParams::LATEX;
866 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
867 // No side effect of file copying and image conversion
868 runparams.dryrun = true;
870 if (cur.inTexted()) {
871 // @TODO what about searching beyond/across paragraph breaks ?
872 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
873 for (int i = 0; i < cur.pit(); ++i)
875 // ParagraphList::const_iterator pit_end = pit;
877 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
878 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
879 ? pit->size() : cur.pos() + len;
880 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
882 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
883 } else if (cur.inMathed()) {
884 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
885 for (int s = cur.depth() - 1; s >= 0; --s) {
886 CursorSlice const & cs = cur[s];
887 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
889 cs.asInsetMath()->asHullInset()->header_write(ws);
894 CursorSlice const & cs = cur.top();
895 MathData md = cs.cell();
896 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
897 ? md.end() : md.begin() + cs.pos() + len );
898 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
901 // MathData md = cur.cell();
902 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
903 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
904 // MathAtom const & ma = *it;
905 // ma.nucleus()->latex(buf, ods, runparams);
908 // Retrieve the math environment type, and add '$' or '$]'
909 // or others (\end{equation}) accordingly
910 for (int s = cur.depth() - 1; s >= 0; --s) {
911 CursorSlice const & cs = cur[s];
912 InsetMath * inset = cs.asInsetMath();
913 if (inset && inset->asHullInset()) {
915 inset->asHullInset()->footer_write(ws);
919 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
921 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
927 /** Finalize an advanced find operation, advancing the cursor to the innermost
928 ** position that matches, plus computing the length of the matching text to
931 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
933 // Search the foremost position that matches (avoids find of entire math
934 // inset when match at start of it)
936 DocIterator old_cur(cur.buffer());
938 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
942 } while (cur && cur.depth() > d && match(cur) > 0);
944 LASSERT(match(cur) > 0, /* */);
945 LYXERR(Debug::FIND, "Ok");
947 // Compute the match length
949 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
950 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
952 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
954 // Length of matched text (different from len param)
955 int old_len = match(cur, len);
957 // Greedy behaviour while matching regexps
958 while ((new_len = match(cur, len + 1)) > old_len) {
961 LYXERR(Debug::FIND, "verifying match with len = " << len);
968 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
972 while (cur && !match(cur, -1, false)) {
973 if (cur.pit() < cur.lastpit())
979 for (; cur; cur.forwardPos()) {
981 return findAdvFinalize(cur, match);
987 /// Find the most backward consecutive match within same paragraph while searching backwards.
988 void findMostBackwards(DocIterator & cur, MatchStringAdv const & match, int & len)
990 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
991 len = findAdvFinalize(cur, match);
992 if (cur != cur_begin) {
993 Inset & inset = cur.inset();
1001 LYXERR(Debug::FIND, "findMostBackwards(): old_cur="
1002 << old_cur << ", old_len=" << len << ", cur=" << cur);
1004 } while (cur != cur_begin && &cur.inset() == &inset && match(cur)
1005 && (len = findAdvFinalize(dit2, match)) > old_len);
1009 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1014 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1017 // Backup of original position
1018 DocIterator cur_orig(cur);
1019 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1020 if (cur == cur_begin)
1023 bool pit_changed = false;
1024 found_match = false;
1027 found_match = match(cur, -1, false);
1031 cur.pos() = cur.lastpos();
1033 cur.pos() = cur_orig.pos();
1034 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1035 DocIterator cur_prev_iter;
1037 found_match = match(cur);
1038 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1039 << found_match << ", cur: " << cur);
1042 findMostBackwards(cur, match, len);
1046 // Prevent infinite loop at begin of document
1047 if (cur == cur_begin || cur == cur_prev_iter)
1049 cur_prev_iter = cur;
1053 if (cur == cur_begin)
1065 } // anonym namespace
1068 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1069 DocIterator const & cur, int len)
1071 if (!opt.ignoreformat)
1072 return latexifyFromCursor(cur, len);
1074 return stringifyFromCursor(cur, len);
1078 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1079 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1080 bool regexp, docstring const & replace, bool keep_case,
1082 : search(search), casesensitive(casesensitive), matchword(matchword),
1083 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1084 regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1089 /** Checks if the supplied character is lower-case */
1090 static bool isLowerCase(char_type ch) {
1091 return lowercase(ch) == ch;
1095 /** Checks if the supplied character is upper-case */
1096 static bool isUpperCase(char_type ch) {
1097 return uppercase(ch) == ch;
1101 /** Check if 'len' letters following cursor are all non-lowercase */
1102 static bool allNonLowercase(DocIterator const & cur, int len) {
1103 pos_type end_pos = cur.pos() + len;
1104 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1105 if (isLowerCase(cur.paragraph().getChar(pos)))
1111 /** Check if first letter is upper case and second one is lower case */
1112 static bool firstUppercase(DocIterator const & cur) {
1114 if (cur.pos() >= cur.lastpos() - 1) {
1115 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1118 ch1 = cur.paragraph().getChar(cur.pos());
1119 ch2 = cur.paragraph().getChar(cur.pos()+1);
1120 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1121 LYXERR(Debug::FIND, "firstUppercase(): "
1122 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1123 << ch2 << "(" << char(ch2) << ")"
1124 << ", result=" << result << ", cur=" << cur);
1129 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1131 ** \fixme What to do with possible further paragraphs in replace buffer ?
1133 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1134 ParagraphList::iterator pit = buffer.paragraphs().begin();
1135 pos_type right = pos_type(1);
1136 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1137 right = pit->size() + 1;
1138 pit->changeCase(buffer.params(), right, right, others_case);
1142 /// Perform a FindAdv operation.
1143 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1145 DocIterator cur = bv->cursor();
1148 if (opt.search.empty()) {
1149 bv->message(_("Search text is empty!"));
1153 MatchStringAdv matchAdv(bv->buffer(), opt);
1156 match_len = findForwardAdv(cur, matchAdv);
1158 match_len = findBackwardsAdv(cur, matchAdv);
1160 // This may only be raised by boost::regex()
1161 bv->message(_("Invalid regular expression!"));
1165 if (match_len == 0) {
1166 bv->message(_("Match not found!"));
1170 LYXERR(Debug::FIND, "Putting selection at buf=" << matchAdv.p_buf
1171 << "cur=" << cur << " with len: " << match_len);
1173 bv->putSelectionAt(cur, match_len, ! opt.forward);
1174 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING))) {
1175 bv->message(_("Match found!"));
1177 string lyx = to_utf8(opt.replace);
1178 // FIXME: Seems so stupid to me to rebuild a buffer here,
1179 // when we already have one (replace_work_area_.buffer())
1180 Buffer repl_buffer("", false);
1181 repl_buffer.setUnnamed(true);
1182 if (repl_buffer.readString(lyx)) {
1183 repl_buffer.changeLanguage(
1184 repl_buffer.language(),
1185 bv->cursor().getFont().language());
1186 if (opt.keep_case && match_len >= 2) {
1187 if (cur.inTexted()) {
1188 if (firstUppercase(cur))
1189 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1190 else if (allNonLowercase(cur, match_len))
1191 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1194 cap::cutSelection(bv->cursor(), false, false);
1195 if (! cur.inMathed()) {
1196 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1197 cap::pasteParagraphList(bv->cursor(), repl_buffer.paragraphs(),
1198 repl_buffer.params().documentClassPtr(),
1199 bv->buffer().errorList("Paste"));
1201 odocstringstream ods;
1202 OutputParams runparams(&repl_buffer.params().encoding());
1203 runparams.nice = false;
1204 runparams.flavor = OutputParams::LATEX;
1205 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1206 runparams.dryrun = true;
1208 TeXOnePar(repl_buffer, repl_buffer.text(),
1209 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1210 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1211 docstring repl_latex = ods.str();
1212 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1214 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1215 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1216 repl_latex = from_utf8(s);
1217 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1218 bv->cursor().niceInsert(repl_latex);
1220 bv->putSelectionAt(cur, repl_buffer.paragraphs().begin()->size(), ! opt.forward);
1221 bv->message(_("Match found and replaced !"));
1223 LASSERT(false, /**/);
1230 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1232 os << to_utf8(opt.search) << "\nEOSS\n"
1233 << opt.casesensitive << ' '
1234 << opt.matchword << ' '
1235 << opt.forward << ' '
1236 << opt.expandmacros << ' '
1237 << opt.ignoreformat << ' '
1238 << opt.regexp << ' '
1239 << to_utf8(opt.replace) << "\nEOSS\n"
1240 << opt.keep_case << ' '
1243 LYXERR(Debug::FIND, "built: " << os.str());
1248 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1250 LYXERR(Debug::FIND, "parsing");
1254 while (line != "EOSS") {
1258 if (is.eof()) // Tolerate malformed request
1262 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1263 opt.search = from_utf8(s);
1264 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1265 is.get(); // Waste space before replace string
1268 while (line != "EOSS") {
1272 if (is.eof()) // Tolerate malformed request
1276 is >> opt.keep_case;
1279 opt.scope = FindAndReplaceOptions::SearchScope(i);
1280 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1281 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1282 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1283 opt.replace = from_utf8(s);