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 "support/regex.h"
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 DocIterator cur_orig(bv->cursor());
176 MatchString const match(searchstr, cs, mw);
179 int const rsize = replacestr.size();
180 int const ssize = searchstr.size();
183 cur.setCursor(doc_iterator_begin(&buf));
184 while (findForward(cur, match, false)) {
185 // Backup current cursor position and font.
186 pos_type const pos = cur.pos();
187 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
189 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
190 buf.params().trackChanges);
191 cur.paragraph().insert(pos, replacestr, font,
192 Change(buf.params().trackChanges ?
193 Change::INSERTED : Change::UNCHANGED));
194 for (int i = 0; i < rsize + striked; ++i)
199 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
203 cur_orig.fixIfBroken();
204 bv->setCursor(cur_orig);
210 bool stringSelected(BufferView * bv, docstring & searchstr,
211 bool cs, bool mw, bool fw)
213 // if nothing selected and searched string is empty, this
214 // means that we want to search current word at cursor position,
215 // but only if we are in texted() mode.
216 if (!bv->cursor().selection() && searchstr.empty()
217 && bv->cursor().inTexted()) {
218 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
219 searchstr = bv->cursor().selectionAsString(false);
223 // if nothing selected or selection does not equal search
224 // string search and select next occurance and return
225 docstring const & str1 = searchstr;
226 docstring const str2 = bv->cursor().selectionAsString(false);
227 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
228 find(bv, searchstr, cs, mw, fw);
236 int replace(BufferView * bv, docstring & searchstr,
237 docstring const & replacestr, bool cs, bool mw, bool fw)
239 if (!stringSelected(bv, searchstr, cs, mw, fw))
242 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
245 Cursor & cur = bv->cursor();
246 cap::replaceSelectionWithString(cur, replacestr, fw);
247 bv->buffer().markDirty();
248 find(bv, searchstr, cs, mw, fw, false);
249 bv->buffer().updateMacros();
250 bv->processUpdateFlags(Update::Force | Update::FitCursor);
258 docstring const find2string(docstring const & search,
259 bool casesensitive, bool matchword, bool forward)
263 << int(casesensitive) << ' '
264 << int(matchword) << ' '
270 docstring const replace2string(docstring const & replace,
271 docstring const & search, bool casesensitive, bool matchword,
272 bool all, bool forward)
275 ss << replace << '\n'
277 << int(casesensitive) << ' '
278 << int(matchword) << ' '
285 bool find(BufferView * bv, FuncRequest const & ev)
287 if (!bv || ev.action() != LFUN_WORD_FIND)
290 //lyxerr << "find called, cmd: " << ev << endl;
292 // data is of the form
294 // <casesensitive> <matchword> <forward>"
296 docstring howto = split(ev.argument(), search, '\n');
298 bool casesensitive = parse_bool(howto);
299 bool matchword = parse_bool(howto);
300 bool forward = parse_bool(howto);
302 return find(bv, search, casesensitive, matchword, forward);
306 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
308 if (!bv || ev.action() != LFUN_WORD_REPLACE)
311 // data is of the form
314 // <casesensitive> <matchword> <all> <forward>"
317 docstring howto = split(ev.argument(), rplc, '\n');
318 howto = split(howto, search, '\n');
320 bool casesensitive = parse_bool(howto);
321 bool matchword = parse_bool(howto);
322 bool all = parse_bool(howto);
323 bool forward = parse_bool(howto);
326 int const replace_count = all
327 ? replaceAll(bv, search, rplc, casesensitive, matchword)
328 : replace(bv, search, rplc, casesensitive, matchword, forward);
330 Buffer & buf = bv->buffer();
331 if (replace_count == 0) {
332 // emit message signal.
333 buf.message(_("String not found!"));
335 if (replace_count == 1) {
336 // emit message signal.
337 buf.message(_("String has been replaced."));
339 docstring str = convert<docstring>(replace_count);
340 str += _(" strings have been replaced.");
341 // emit message signal.
346 // if we have deleted characters, we do not replace at all, but
347 // rather search for the next occurence
348 if (find(bv, search, casesensitive, matchword, forward))
351 bv->message(_("String not found!"));
356 bool findNextChange(BufferView * bv)
358 return findChange(bv, true);
362 bool findPreviousChange(BufferView * bv)
364 return findChange(bv, false);
368 bool findChange(BufferView * bv, bool next)
370 if (bv->cursor().selection()) {
371 // set the cursor at the beginning or at the end of the selection
372 // before searching. Otherwise, the current change will be found.
373 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
374 bv->cursor().setCursorToAnchor();
377 DocIterator cur = bv->cursor();
379 // Are we within a change ? Then first search forward (backward),
380 // clear the selection and search the other way around (see the end
381 // of this function). This will avoid changes to be selected half.
382 bool search_both_sides = false;
383 DocIterator tmpcur = cur;
385 while (tmpcur.inMathed())
387 Change change_next_pos
388 = tmpcur.paragraph().lookupChange(tmpcur.pos());
389 if (change_next_pos.changed() && cur.inMathed()) {
391 search_both_sides = true;
392 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
393 Change change_prev_pos
394 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
395 if (change_next_pos.isSimilarTo(change_prev_pos))
396 search_both_sides = true;
399 if (!findChange(cur, next))
402 bv->cursor().setCursor(cur);
403 bv->cursor().resetAnchor();
406 // take a step into the change
409 Change orig_change = cur.paragraph().lookupChange(cur.pos());
411 CursorSlice & tip = cur.top();
413 for (; !tip.at_end(); tip.forwardPos()) {
414 Change change = tip.paragraph().lookupChange(tip.pos());
415 if (!change.isSimilarTo(orig_change))
419 for (; !tip.at_begin();) {
421 Change change = tip.paragraph().lookupChange(tip.pos());
422 if (!change.isSimilarTo(orig_change)) {
423 // take a step forward to correctly set the selection
430 // Now put cursor to end of selection:
431 bv->cursor().setCursor(cur);
432 bv->cursor().setSelection();
434 if (search_both_sides) {
435 bv->cursor().setSelection(false);
436 findChange(bv, !next);
444 typedef vector<pair<string, string> > Escapes;
446 /// A map of symbols and their escaped equivalent needed within a regex.
447 Escapes const & get_regexp_escapes()
449 static Escapes escape_map;
450 if (escape_map.empty()) {
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>("}", "\\}"));
456 escape_map.push_back(pair<string, string>("[", "\\["));
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>("+", "\\+"));
461 escape_map.push_back(pair<string, string>("*", "\\*"));
462 escape_map.push_back(pair<string, string>(".", "\\."));
467 /// A map of lyx escaped strings and their unescaped equivalent.
468 Escapes const & get_lyx_unescapes() {
469 static Escapes escape_map;
470 if (escape_map.empty()) {
471 escape_map.push_back(pair<string, string>("{*}", "*"));
472 escape_map.push_back(pair<string, string>("{[}", "["));
473 escape_map.push_back(pair<string, string>("\\$", "$"));
474 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
475 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
476 escape_map.push_back(pair<string, string>("\\sim ", "~"));
477 escape_map.push_back(pair<string, string>("\\^", "^"));
482 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
483 ** the found occurrence were escaped.
485 string apply_escapes(string s, Escapes const & escape_map)
487 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
488 Escapes::const_iterator it;
489 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
490 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
491 unsigned int pos = 0;
492 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
493 s.replace(pos, it->first.length(), it->second);
494 // LYXERR(Debug::FIND, "After escape: " << s);
495 pos += it->second.length();
496 // LYXERR(Debug::FIND, "pos: " << pos);
499 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
503 /** Return the position of the closing brace matching the open one at s[pos],
504 ** or s.size() if not found.
506 size_t find_matching_brace(string const & s, size_t pos)
508 LASSERT(s[pos] == '{', /* */);
510 for (++pos; pos < s.size(); ++pos) {
513 else if (s[pos] == '{')
515 else if (s[pos] == '}') {
517 if (open_braces == 0)
524 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
525 string escape_for_regex(string s)
528 while (pos < s.size()) {
529 size_t new_pos = s.find("\\regexp{{{", pos);
530 if (new_pos == string::npos)
532 LYXERR(Debug::FIND, "new_pos: " << new_pos);
533 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
534 LYXERR(Debug::FIND, "t : " << t);
535 t = apply_escapes(t, get_regexp_escapes());
536 LYXERR(Debug::FIND, "t : " << t);
537 s.replace(pos, new_pos - pos, t);
538 new_pos = pos + t.size();
539 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
540 LYXERR(Debug::FIND, "new_pos: " << new_pos);
541 if (new_pos == s.size())
543 size_t end_pos = s.find("}}}", new_pos + 10); // find_matching_brace(s, new_pos + 7);
544 LYXERR(Debug::FIND, "end_pos: " << end_pos);
545 t = apply_escapes(s.substr(new_pos + 10, end_pos - (new_pos + 10)), get_lyx_unescapes());
546 LYXERR(Debug::FIND, "t : " << t);
547 if (end_pos == s.size()) {
548 s.replace(new_pos, end_pos - new_pos, t);
550 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
553 s.replace(new_pos, end_pos + 3 - new_pos, t);
554 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
555 pos = new_pos + t.size();
556 LYXERR(Debug::FIND, "pos: " << pos);
561 /// Wrapper for lyx::regex_replace with simpler interface
562 bool regex_replace(string const & s, string & t, string const & searchstr,
563 string const & replacestr)
565 lyx::regex e(searchstr);
567 ostream_iterator<char, char> it(oss);
568 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
569 // tolerate t and s be references to the same variable
570 bool rv = (s != oss.str());
575 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
577 ** Verify that closed braces exactly match open braces. This avoids that, for example,
578 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
581 ** Number of open braces that must remain open at the end for the verification to succeed.
583 bool braces_match(string::const_iterator const & beg,
584 string::const_iterator const & end,
588 string::const_iterator it = beg;
589 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
590 for (; it != end; ++it) {
591 // Skip escaped braces in the count
596 } else if (*it == '{') {
598 } else if (*it == '}') {
599 if (open_pars == 0) {
600 LYXERR(Debug::FIND, "Found unmatched closed brace");
606 if (open_pars != unmatched) {
607 LYXERR(Debug::FIND, "Found " << open_pars
608 << " instead of " << unmatched
609 << " unmatched open braces at the end of count");
612 LYXERR(Debug::FIND, "Braces match as expected");
616 /** The class performing a match between a position in the document and the FindAdvOptions.
618 class MatchStringAdv {
620 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
622 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
623 ** constructor as opt.search, under the opt.* options settings.
626 ** If set, then match is searched only against beginning of text starting at cur.
627 ** If unset, then match is searched anywhere in text starting at cur.
630 ** The length of the matching text, or zero if no match was found.
632 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
637 /// first buffer on which search was started
638 lyx::Buffer * const p_first_buf;
640 FindAndReplaceOptions const & opt;
643 /// Auxiliary find method (does not account for opt.matchword)
644 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
646 /** Normalize a stringified or latexified LyX paragraph.
650 ** <li>if search is not casesensitive, then lowercase the string;
651 ** <li>remove any newline at begin or end of the string;
652 ** <li>replace any newline in the middle of the string with a simple space;
653 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
656 ** @todo Normalization should also expand macros, if the corresponding
657 ** search option was checked.
659 string normalize(docstring const & s) const;
660 // normalized string to search
661 string par_as_string;
662 // regular expression to use for searching
664 // same as regexp, but prefixed with a ".*"
666 // unmatched open braces in the search string/regexp
668 // number of (.*?) subexpressions added at end of search regexp for closing
669 // environments, math mode, styles, etc...
674 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
675 : p_buf(&buf), p_first_buf(&buf), opt(opt)
677 par_as_string = normalize(opt.search);
682 // Remove trailing closure of math, macros and environments, so to catch parts of them.
684 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
685 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
687 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
689 // @todo need to account for open square braces as well ?
690 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
692 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
694 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
700 LYXERR(Debug::FIND, "Open braces: " << open_braces);
701 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
703 par_as_string = escape_for_regex(par_as_string);
704 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
705 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
707 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
708 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
709 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
710 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
711 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
712 || regex_replace(par_as_string, par_as_string,
713 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
714 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
715 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
719 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
720 LYXERR(Debug::FIND, "Open braces: " << open_braces);
721 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
722 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
723 // If entered regexp must match at begin of searched string buffer
724 regexp = lyx::regex(string("\\`") + par_as_string);
725 // If entered regexp may match wherever in searched string buffer
726 regexp2 = lyx::regex(string("\\`.*") + par_as_string);
731 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
733 docstring docstr = stringifyFromForSearch(opt, cur, len);
734 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
735 string str = normalize(docstr);
736 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
739 if (str.substr(0, par_as_string.size()) == par_as_string)
740 return par_as_string.size();
742 size_t pos = str.find(par_as_string);
743 if (pos != string::npos)
744 return par_as_string.size();
747 // Try all possible regexp matches,
748 //until one that verifies the braces match test is found
749 regex const *p_regexp = at_begin ? ®exp : ®exp2;
750 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
751 sregex_iterator re_it_end;
752 for (; re_it != re_it_end; ++re_it) {
753 match_results<string::const_iterator> const & m = *re_it;
754 // Check braces on the segment that matched the entire regexp expression,
755 // plus the last subexpression, if a (.*?) was inserted in the constructor.
756 if (! braces_match(m[0].first, m[0].second, open_braces))
758 // Check braces on segments that matched all (.*?) subexpressions.
759 for (size_t i = 1; i < m.size(); ++i)
760 if (! braces_match(m[i].first, m[i].second))
762 // Exclude from the returned match length any length
763 // due to close wildcards added at end of regexp
764 if (close_wildcards == 0)
765 return m[0].second - m[0].first;
767 return m[m.size() - close_wildcards].first - m[0].first;
774 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
776 int res = findAux(cur, len, at_begin);
777 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
779 Paragraph const & par = cur.paragraph();
780 bool ws_left = cur.pos() > 0 ?
781 par.isWordSeparator(cur.pos() - 1) : true;
782 bool ws_right = cur.pos() + res < par.size() ?
783 par.isWordSeparator(cur.pos() + res) : true;
785 "cur.pos()=" << cur.pos() << ", res=" << res
786 << ", separ: " << ws_left << ", " << ws_right
788 if (ws_left && ws_right)
794 string MatchStringAdv::normalize(docstring const & s) const
797 if (! opt.casesensitive)
798 t = lyx::to_utf8(lowercase(s));
801 // Remove \n at begin
802 while (t.size() > 0 && t[0] == '\n')
805 while (t.size() > 0 && t[t.size() - 1] == '\n')
806 t = t.substr(0, t.size() - 1);
808 // Replace all other \n with spaces
809 while ((pos = t.find("\n")) != string::npos)
810 t.replace(pos, 1, " ");
811 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
812 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
813 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
814 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
819 docstring stringifyFromCursor(DocIterator const & cur, int len)
821 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
822 if (cur.inTexted()) {
823 Paragraph const & par = cur.paragraph();
824 // TODO what about searching beyond/across paragraph breaks ?
825 // TODO Try adding a AS_STR_INSERTS as last arg
826 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
827 int(par.size()) : cur.pos() + len;
828 OutputParams runparams(&cur.buffer()->params().encoding());
830 runparams.nice = true;
831 runparams.flavor = OutputParams::LATEX;
832 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
833 // No side effect of file copying and image conversion
834 runparams.dryrun = true;
835 LYXERR(Debug::FIND, "Stringifying with cur: "
836 << cur << ", from pos: " << cur.pos() << ", end: " << end);
837 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
838 } else if (cur.inMathed()) {
840 CursorSlice cs = cur.top();
841 MathData md = cs.cell();
842 MathData::const_iterator it_end =
843 ( ( len == -1 || cs.pos() + len > int(md.size()) )
844 ? md.end() : md.begin() + cs.pos() + len );
845 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
849 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
854 /** Computes the LaTeX export of buf starting from cur and ending len positions
855 * after cur, if len is positive, or at the paragraph or innermost inset end
858 docstring latexifyFromCursor(DocIterator const & cur, int len)
860 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
861 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
862 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
863 Buffer const & buf = *cur.buffer();
864 LASSERT(buf.isLatex(), /* */);
867 odocstringstream ods;
868 OutputParams runparams(&buf.params().encoding());
869 runparams.nice = false;
870 runparams.flavor = OutputParams::LATEX;
871 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
872 // No side effect of file copying and image conversion
873 runparams.dryrun = true;
875 if (cur.inTexted()) {
876 // @TODO what about searching beyond/across paragraph breaks ?
877 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
878 for (int i = 0; i < cur.pit(); ++i)
880 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
881 ? pit->size() : cur.pos() + len;
882 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
884 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
885 } else if (cur.inMathed()) {
886 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
887 for (int s = cur.depth() - 1; s >= 0; --s) {
888 CursorSlice const & cs = cur[s];
889 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
891 cs.asInsetMath()->asHullInset()->header_write(ws);
896 CursorSlice const & cs = cur.top();
897 MathData md = cs.cell();
898 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
899 ? md.end() : md.begin() + cs.pos() + len );
900 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
903 // Retrieve the math environment type, and add '$' or '$]'
904 // or others (\end{equation}) accordingly
905 for (int s = cur.depth() - 1; s >= 0; --s) {
906 CursorSlice const & cs = cur[s];
907 InsetMath * inset = cs.asInsetMath();
908 if (inset && inset->asHullInset()) {
910 inset->asHullInset()->footer_write(ws);
914 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
916 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
922 /** Finalize an advanced find operation, advancing the cursor to the innermost
923 ** position that matches, plus computing the length of the matching text to
926 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
928 // Search the foremost position that matches (avoids find of entire math
929 // inset when match at start of it)
931 DocIterator old_cur(cur.buffer());
933 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
937 } while (cur && cur.depth() > d && match(cur) > 0);
939 LASSERT(match(cur) > 0, /* */);
940 LYXERR(Debug::FIND, "Ok");
942 // Compute the match length
944 if (cur.pos() + len > cur.lastpos())
946 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
947 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
949 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
951 // Length of matched text (different from len param)
952 int old_len = match(cur, len);
954 // Greedy behaviour while matching regexps
955 while ((new_len = match(cur, len + 1)) > old_len) {
958 LYXERR(Debug::FIND, "verifying match with len = " << len);
965 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
969 while (cur && !match(cur, -1, false)) {
970 if (cur.pit() < cur.lastpit())
976 for (; cur; cur.forwardPos()) {
978 return findAdvFinalize(cur, match);
984 /// Find the most backward consecutive match within same paragraph while searching backwards.
985 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
987 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
988 DocIterator tmp_cur = cur;
989 int len = findAdvFinalize(tmp_cur, match);
990 Inset & inset = cur.inset();
991 for (; cur != cur_begin; cur.backwardPos()) {
992 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
993 DocIterator new_cur = cur;
994 new_cur.backwardPos();
995 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
997 int new_len = findAdvFinalize(new_cur, match);
1002 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1008 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1011 // Backup of original position
1012 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1013 if (cur == cur_begin)
1016 DocIterator cur_orig(cur);
1018 bool pit_changed = false;
1019 found_match = false;
1022 found_match = match(cur, -1, false);
1026 cur.pos() = cur.lastpos();
1028 cur.pos() = cur_orig.pos();
1029 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1030 DocIterator cur_prev_iter;
1032 found_match = match(cur);
1033 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1034 << found_match << ", cur: " << cur);
1036 return findMostBackwards(cur, match);
1038 // Stop if begin of document reached
1039 if (cur == cur_begin)
1041 cur_prev_iter = cur;
1045 if (cur == cur_begin)
1057 } // anonym namespace
1060 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1061 DocIterator const & cur, int len)
1063 if (!opt.ignoreformat)
1064 return latexifyFromCursor(cur, len);
1066 return stringifyFromCursor(cur, len);
1070 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1071 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1072 bool regexp, docstring const & replace, bool keep_case,
1074 : search(search), casesensitive(casesensitive), matchword(matchword),
1075 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1076 regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1081 /** Checks if the supplied character is lower-case */
1082 static bool isLowerCase(char_type ch) {
1083 return lowercase(ch) == ch;
1087 /** Checks if the supplied character is upper-case */
1088 static bool isUpperCase(char_type ch) {
1089 return uppercase(ch) == ch;
1093 /** Check if 'len' letters following cursor are all non-lowercase */
1094 static bool allNonLowercase(DocIterator const & cur, int len) {
1095 pos_type end_pos = cur.pos() + len;
1096 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1097 if (isLowerCase(cur.paragraph().getChar(pos)))
1103 /** Check if first letter is upper case and second one is lower case */
1104 static bool firstUppercase(DocIterator const & cur) {
1106 if (cur.pos() >= cur.lastpos() - 1) {
1107 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1110 ch1 = cur.paragraph().getChar(cur.pos());
1111 ch2 = cur.paragraph().getChar(cur.pos()+1);
1112 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1113 LYXERR(Debug::FIND, "firstUppercase(): "
1114 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1115 << ch2 << "(" << char(ch2) << ")"
1116 << ", result=" << result << ", cur=" << cur);
1121 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1123 ** \fixme What to do with possible further paragraphs in replace buffer ?
1125 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1126 ParagraphList::iterator pit = buffer.paragraphs().begin();
1127 pos_type right = pos_type(1);
1128 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1129 right = pit->size() + 1;
1130 pit->changeCase(buffer.params(), right, right, others_case);
1135 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1137 Cursor & cur = bv->cursor();
1138 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING)))
1140 DocIterator sel_beg = cur.selectionBegin();
1141 DocIterator sel_end = cur.selectionEnd();
1142 if (&sel_beg.inset() != &sel_end.inset()
1143 || sel_beg.pit() != sel_end.pit())
1145 int sel_len = sel_end.pos() - sel_beg.pos();
1146 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1147 << ", sel_len: " << sel_len << endl);
1150 LASSERT(sel_len > 0, /**/);
1152 if (!matchAdv(sel_beg, sel_len))
1155 string lyx = to_utf8(opt.replace);
1156 // FIXME: Seems so stupid to me to rebuild a buffer here,
1157 // when we already have one (replace_work_area_.buffer())
1158 Buffer repl_buffer("", false);
1159 repl_buffer.setUnnamed(true);
1160 LASSERT(repl_buffer.readString(lyx), /**/);
1161 repl_buffer.changeLanguage(
1162 repl_buffer.language(),
1163 cur.getFont().language());
1164 if (opt.keep_case && sel_len >= 2) {
1165 if (cur.inTexted()) {
1166 if (firstUppercase(cur))
1167 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1168 else if (allNonLowercase(cur, sel_len))
1169 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1172 cap::cutSelection(cur, false, false);
1173 if (!cur.inMathed()) {
1174 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1175 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1176 repl_buffer.params().documentClassPtr(),
1177 bv->buffer().errorList("Paste"));
1179 odocstringstream ods;
1180 OutputParams runparams(&repl_buffer.params().encoding());
1181 runparams.nice = false;
1182 runparams.flavor = OutputParams::LATEX;
1183 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1184 runparams.dryrun = true;
1186 TeXOnePar(repl_buffer, repl_buffer.text(),
1187 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1188 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1189 docstring repl_latex = ods.str();
1190 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1192 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1193 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1194 repl_latex = from_utf8(s);
1195 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1196 cur.niceInsert(repl_latex);
1198 bv->buffer().markDirty();
1199 cur.pos() -= repl_buffer.paragraphs().begin()->size();
1200 bv->putSelectionAt(DocIterator(cur), repl_buffer.paragraphs().begin()->size(), !opt.forward);
1204 /// Perform a FindAdv operation.
1205 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1210 if (opt.search.empty()) {
1211 bv->message(_("Search text is empty!"));
1216 MatchStringAdv matchAdv(bv->buffer(), opt);
1217 findAdvReplace(bv, opt, matchAdv);
1220 match_len = findForwardAdv(cur, matchAdv);
1222 match_len = findBackwardsAdv(cur, matchAdv);
1224 // This may only be raised by lyx::regex()
1225 bv->message(_("Invalid regular expression!"));
1229 if (match_len == 0) {
1230 bv->message(_("Match not found!"));
1234 bv->message(_("Match found!"));
1236 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1237 bv->putSelectionAt(cur, match_len, !opt.forward);
1243 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1245 os << to_utf8(opt.search) << "\nEOSS\n"
1246 << opt.casesensitive << ' '
1247 << opt.matchword << ' '
1248 << opt.forward << ' '
1249 << opt.expandmacros << ' '
1250 << opt.ignoreformat << ' '
1251 << opt.regexp << ' '
1252 << to_utf8(opt.replace) << "\nEOSS\n"
1253 << opt.keep_case << ' '
1256 LYXERR(Debug::FIND, "built: " << os.str());
1261 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1263 LYXERR(Debug::FIND, "parsing");
1267 while (line != "EOSS") {
1271 if (is.eof()) // Tolerate malformed request
1275 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1276 opt.search = from_utf8(s);
1277 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1278 is.get(); // Waste space before replace string
1281 while (line != "EOSS") {
1285 if (is.eof()) // Tolerate malformed request
1289 is >> opt.keep_case;
1292 opt.scope = FindAndReplaceOptions::SearchScope(i);
1293 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1294 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1295 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1296 opt.replace = from_utf8(s);