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 findOne(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 string
224 // then search and select next occurence and return
225 docstring const str2 = bv->cursor().selectionAsString(false);
226 if ((cs && searchstr != str2) || compare_no_case(searchstr, str2) != 0) {
227 findOne(bv, searchstr, cs, mw, fw);
235 int replaceOne(BufferView * bv, docstring & searchstr,
236 docstring const & replacestr, bool cs, bool mw, bool fw)
238 if (!stringSelected(bv, searchstr, cs, mw, fw))
241 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
244 Cursor & cur = bv->cursor();
245 cap::replaceSelectionWithString(cur, replacestr, fw);
246 bv->buffer().markDirty();
247 findOne(bv, searchstr, cs, mw, fw, false);
248 bv->buffer().updateMacros();
249 bv->processUpdateFlags(Update::Force | Update::FitCursor);
257 docstring const find2string(docstring const & search,
258 bool casesensitive, bool matchword, bool forward)
262 << int(casesensitive) << ' '
263 << int(matchword) << ' '
269 docstring const replace2string(docstring const & replace,
270 docstring const & search, bool casesensitive, bool matchword,
271 bool all, bool forward)
274 ss << replace << '\n'
276 << int(casesensitive) << ' '
277 << int(matchword) << ' '
284 bool find(BufferView * bv, FuncRequest const & ev)
286 if (!bv || ev.action() != LFUN_WORD_FIND)
289 //lyxerr << "find called, cmd: " << ev << endl;
291 // data is of the form
293 // <casesensitive> <matchword> <forward>"
295 docstring howto = split(ev.argument(), search, '\n');
297 bool casesensitive = parse_bool(howto);
298 bool matchword = parse_bool(howto);
299 bool forward = parse_bool(howto);
301 return findOne(bv, search, casesensitive, matchword, forward);
305 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
307 if (!bv || ev.action() != LFUN_WORD_REPLACE)
310 // data is of the form
313 // <casesensitive> <matchword> <all> <forward>"
316 docstring howto = split(ev.argument(), rplc, '\n');
317 howto = split(howto, search, '\n');
319 bool casesensitive = parse_bool(howto);
320 bool matchword = parse_bool(howto);
321 bool all = parse_bool(howto);
322 bool forward = parse_bool(howto);
325 int const replace_count = all
326 ? replaceAll(bv, search, rplc, casesensitive, matchword)
327 : replaceOne(bv, search, rplc, casesensitive, matchword, forward);
329 Buffer & buf = bv->buffer();
330 if (replace_count == 0) {
331 // emit message signal.
332 buf.message(_("String not found!"));
334 if (replace_count == 1) {
335 // emit message signal.
336 buf.message(_("String has been replaced."));
338 docstring str = convert<docstring>(replace_count);
339 str += _(" strings have been replaced.");
340 // emit message signal.
345 // if we have deleted characters, we do not replace at all, but
346 // rather search for the next occurence
347 if (findOne(bv, search, casesensitive, matchword, forward))
350 bv->message(_("String not found!"));
355 bool findNextChange(BufferView * bv)
357 return findChange(bv, true);
361 bool findPreviousChange(BufferView * bv)
363 return findChange(bv, false);
367 bool findChange(BufferView * bv, bool next)
369 if (bv->cursor().selection()) {
370 // set the cursor at the beginning or at the end of the selection
371 // before searching. Otherwise, the current change will be found.
372 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
373 bv->cursor().setCursorToAnchor();
376 DocIterator cur = bv->cursor();
378 // Are we within a change ? Then first search forward (backward),
379 // clear the selection and search the other way around (see the end
380 // of this function). This will avoid changes to be selected half.
381 bool search_both_sides = false;
382 DocIterator tmpcur = cur;
384 while (tmpcur.inMathed())
386 Change change_next_pos
387 = tmpcur.paragraph().lookupChange(tmpcur.pos());
388 if (change_next_pos.changed() && cur.inMathed()) {
390 search_both_sides = true;
391 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
392 Change change_prev_pos
393 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
394 if (change_next_pos.isSimilarTo(change_prev_pos))
395 search_both_sides = true;
398 if (!findChange(cur, next))
401 bv->cursor().setCursor(cur);
402 bv->cursor().resetAnchor();
405 // take a step into the change
408 Change orig_change = cur.paragraph().lookupChange(cur.pos());
410 CursorSlice & tip = cur.top();
412 for (; !tip.at_end(); tip.forwardPos()) {
413 Change change = tip.paragraph().lookupChange(tip.pos());
414 if (!change.isSimilarTo(orig_change))
418 for (; !tip.at_begin();) {
420 Change change = tip.paragraph().lookupChange(tip.pos());
421 if (!change.isSimilarTo(orig_change)) {
422 // take a step forward to correctly set the selection
429 // Now put cursor to end of selection:
430 bv->cursor().setCursor(cur);
431 bv->cursor().setSelection();
433 if (search_both_sides) {
434 bv->cursor().setSelection(false);
435 findChange(bv, !next);
443 typedef vector<pair<string, string> > Escapes;
445 /// A map of symbols and their escaped equivalent needed within a regex.
446 Escapes const & get_regexp_escapes()
448 static Escapes escape_map;
449 if (escape_map.empty()) {
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>("[", "\\["));
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>(".", "\\."));
466 /// A map of lyx escaped strings and their unescaped equivalent.
467 Escapes const & get_lyx_unescapes() {
468 static Escapes escape_map;
469 if (escape_map.empty()) {
470 escape_map.push_back(pair<string, string>("{*}", "*"));
471 escape_map.push_back(pair<string, string>("{[}", "["));
472 escape_map.push_back(pair<string, string>("\\$", "$"));
473 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
474 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
475 escape_map.push_back(pair<string, string>("\\sim ", "~"));
476 escape_map.push_back(pair<string, string>("\\^", "^"));
481 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
482 ** the found occurrence were escaped.
484 string apply_escapes(string s, Escapes const & escape_map)
486 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
487 Escapes::const_iterator it;
488 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
489 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
490 unsigned int pos = 0;
491 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
492 s.replace(pos, it->first.length(), it->second);
493 // LYXERR(Debug::FIND, "After escape: " << s);
494 pos += it->second.length();
495 // LYXERR(Debug::FIND, "pos: " << pos);
498 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
502 /** Return the position of the closing brace matching the open one at s[pos],
503 ** or s.size() if not found.
505 size_t find_matching_brace(string const & s, size_t pos)
507 LASSERT(s[pos] == '{', /* */);
509 for (++pos; pos < s.size(); ++pos) {
512 else if (s[pos] == '{')
514 else if (s[pos] == '}') {
516 if (open_braces == 0)
523 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
524 string escape_for_regex(string s)
527 while (pos < s.size()) {
528 size_t new_pos = s.find("\\regexp{{{", pos);
529 if (new_pos == string::npos)
531 LYXERR(Debug::FIND, "new_pos: " << new_pos);
532 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
533 LYXERR(Debug::FIND, "t : " << t);
534 t = apply_escapes(t, get_regexp_escapes());
535 LYXERR(Debug::FIND, "t : " << t);
536 s.replace(pos, new_pos - pos, t);
537 new_pos = pos + t.size();
538 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
539 LYXERR(Debug::FIND, "new_pos: " << new_pos);
540 if (new_pos == s.size())
542 size_t end_pos = s.find("}}}", new_pos + 10); // find_matching_brace(s, new_pos + 7);
543 LYXERR(Debug::FIND, "end_pos: " << end_pos);
544 t = apply_escapes(s.substr(new_pos + 10, end_pos - (new_pos + 10)), get_lyx_unescapes());
545 LYXERR(Debug::FIND, "t : " << t);
546 if (end_pos == s.size()) {
547 s.replace(new_pos, end_pos - new_pos, t);
549 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
552 s.replace(new_pos, end_pos + 3 - new_pos, t);
553 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
554 pos = new_pos + t.size();
555 LYXERR(Debug::FIND, "pos: " << pos);
560 /// Wrapper for lyx::regex_replace with simpler interface
561 bool regex_replace(string const & s, string & t, string const & searchstr,
562 string const & replacestr)
564 lyx::regex e(searchstr);
566 ostream_iterator<char, char> it(oss);
567 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
568 // tolerate t and s be references to the same variable
569 bool rv = (s != oss.str());
574 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
576 ** Verify that closed braces exactly match open braces. This avoids that, for example,
577 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
580 ** Number of open braces that must remain open at the end for the verification to succeed.
582 bool braces_match(string::const_iterator const & beg,
583 string::const_iterator const & end,
587 string::const_iterator it = beg;
588 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
589 for (; it != end; ++it) {
590 // Skip escaped braces in the count
595 } else if (*it == '{') {
597 } else if (*it == '}') {
598 if (open_pars == 0) {
599 LYXERR(Debug::FIND, "Found unmatched closed brace");
605 if (open_pars != unmatched) {
606 LYXERR(Debug::FIND, "Found " << open_pars
607 << " instead of " << unmatched
608 << " unmatched open braces at the end of count");
611 LYXERR(Debug::FIND, "Braces match as expected");
615 /** The class performing a match between a position in the document and the FindAdvOptions.
617 class MatchStringAdv {
619 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
621 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
622 ** constructor as opt.search, under the opt.* options settings.
625 ** If set, then match is searched only against beginning of text starting at cur.
626 ** If unset, then match is searched anywhere in text starting at cur.
629 ** The length of the matching text, or zero if no match was found.
631 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
636 /// first buffer on which search was started
637 lyx::Buffer * const p_first_buf;
639 FindAndReplaceOptions const & opt;
642 /// Auxiliary find method (does not account for opt.matchword)
643 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
645 /** Normalize a stringified or latexified LyX paragraph.
649 ** <li>if search is not casesensitive, then lowercase the string;
650 ** <li>remove any newline at begin or end of the string;
651 ** <li>replace any newline in the middle of the string with a simple space;
652 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
655 ** @todo Normalization should also expand macros, if the corresponding
656 ** search option was checked.
658 string normalize(docstring const & s) const;
659 // normalized string to search
660 string par_as_string;
661 // regular expression to use for searching
663 // same as regexp, but prefixed with a ".*"
665 // unmatched open braces in the search string/regexp
667 // number of (.*?) subexpressions added at end of search regexp for closing
668 // environments, math mode, styles, etc...
673 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
674 : p_buf(&buf), p_first_buf(&buf), opt(opt)
676 par_as_string = normalize(opt.search);
681 // Remove trailing closure of math, macros and environments, so to catch parts of them.
683 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
684 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
686 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
688 // @todo need to account for open square braces as well ?
689 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
691 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
693 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
699 LYXERR(Debug::FIND, "Open braces: " << open_braces);
700 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
702 par_as_string = escape_for_regex(par_as_string);
703 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
704 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
706 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
707 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
708 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
709 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
710 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
711 || regex_replace(par_as_string, par_as_string,
712 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
713 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
714 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
718 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
719 LYXERR(Debug::FIND, "Open braces: " << open_braces);
720 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
721 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
722 // If entered regexp must match at begin of searched string buffer
723 regexp = lyx::regex(string("\\`") + par_as_string);
724 // If entered regexp may match wherever in searched string buffer
725 regexp2 = lyx::regex(string("\\`.*") + par_as_string);
730 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
732 docstring docstr = stringifyFromForSearch(opt, cur, len);
733 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
734 string str = normalize(docstr);
735 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
738 if (str.substr(0, par_as_string.size()) == par_as_string)
739 return par_as_string.size();
741 size_t pos = str.find(par_as_string);
742 if (pos != string::npos)
743 return par_as_string.size();
746 // Try all possible regexp matches,
747 //until one that verifies the braces match test is found
748 regex const *p_regexp = at_begin ? ®exp : ®exp2;
749 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
750 sregex_iterator re_it_end;
751 for (; re_it != re_it_end; ++re_it) {
752 match_results<string::const_iterator> const & m = *re_it;
753 // Check braces on the segment that matched the entire regexp expression,
754 // plus the last subexpression, if a (.*?) was inserted in the constructor.
755 if (! braces_match(m[0].first, m[0].second, open_braces))
757 // Check braces on segments that matched all (.*?) subexpressions.
758 for (size_t i = 1; i < m.size(); ++i)
759 if (! braces_match(m[i].first, m[i].second))
761 // Exclude from the returned match length any length
762 // due to close wildcards added at end of regexp
763 if (close_wildcards == 0)
764 return m[0].second - m[0].first;
766 return m[m.size() - close_wildcards].first - m[0].first;
773 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
775 int res = findAux(cur, len, at_begin);
776 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
778 Paragraph const & par = cur.paragraph();
779 bool ws_left = cur.pos() > 0 ?
780 par.isWordSeparator(cur.pos() - 1) : true;
781 bool ws_right = cur.pos() + res < par.size() ?
782 par.isWordSeparator(cur.pos() + res) : true;
784 "cur.pos()=" << cur.pos() << ", res=" << res
785 << ", separ: " << ws_left << ", " << ws_right
787 if (ws_left && ws_right)
793 string MatchStringAdv::normalize(docstring const & s) const
796 if (! opt.casesensitive)
797 t = lyx::to_utf8(lowercase(s));
800 // Remove \n at begin
801 while (t.size() > 0 && t[0] == '\n')
804 while (t.size() > 0 && t[t.size() - 1] == '\n')
805 t = t.substr(0, t.size() - 1);
807 // Replace all other \n with spaces
808 while ((pos = t.find("\n")) != string::npos)
809 t.replace(pos, 1, " ");
810 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
811 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
812 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
813 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
818 docstring stringifyFromCursor(DocIterator const & cur, int len)
820 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
821 if (cur.inTexted()) {
822 Paragraph const & par = cur.paragraph();
823 // TODO what about searching beyond/across paragraph breaks ?
824 // TODO Try adding a AS_STR_INSERTS as last arg
825 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
826 int(par.size()) : cur.pos() + len;
827 OutputParams runparams(&cur.buffer()->params().encoding());
829 runparams.nice = true;
830 runparams.flavor = OutputParams::LATEX;
831 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
832 // No side effect of file copying and image conversion
833 runparams.dryrun = true;
834 LYXERR(Debug::FIND, "Stringifying with cur: "
835 << cur << ", from pos: " << cur.pos() << ", end: " << end);
836 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
837 } else if (cur.inMathed()) {
839 CursorSlice cs = cur.top();
840 MathData md = cs.cell();
841 MathData::const_iterator it_end =
842 ( ( len == -1 || cs.pos() + len > int(md.size()) )
843 ? md.end() : md.begin() + cs.pos() + len );
844 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
848 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
853 /** Computes the LaTeX export of buf starting from cur and ending len positions
854 * after cur, if len is positive, or at the paragraph or innermost inset end
857 docstring latexifyFromCursor(DocIterator const & cur, int len)
859 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
860 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
861 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
862 Buffer const & buf = *cur.buffer();
863 LASSERT(buf.isLatex(), /* */);
866 odocstringstream ods;
867 OutputParams runparams(&buf.params().encoding());
868 runparams.nice = false;
869 runparams.flavor = OutputParams::LATEX;
870 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
871 // No side effect of file copying and image conversion
872 runparams.dryrun = true;
874 if (cur.inTexted()) {
875 // @TODO what about searching beyond/across paragraph breaks ?
876 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
877 for (int i = 0; i < cur.pit(); ++i)
879 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
880 ? pit->size() : cur.pos() + len;
881 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
883 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
884 } else if (cur.inMathed()) {
885 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
886 for (int s = cur.depth() - 1; s >= 0; --s) {
887 CursorSlice const & cs = cur[s];
888 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
890 cs.asInsetMath()->asHullInset()->header_write(ws);
895 CursorSlice const & cs = cur.top();
896 MathData md = cs.cell();
897 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
898 ? md.end() : md.begin() + cs.pos() + len );
899 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
902 // Retrieve the math environment type, and add '$' or '$]'
903 // or others (\end{equation}) accordingly
904 for (int s = cur.depth() - 1; s >= 0; --s) {
905 CursorSlice const & cs = cur[s];
906 InsetMath * inset = cs.asInsetMath();
907 if (inset && inset->asHullInset()) {
909 inset->asHullInset()->footer_write(ws);
913 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
915 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
921 /** Finalize an advanced find operation, advancing the cursor to the innermost
922 ** position that matches, plus computing the length of the matching text to
925 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
927 // Search the foremost position that matches (avoids find of entire math
928 // inset when match at start of it)
930 DocIterator old_cur(cur.buffer());
932 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
936 } while (cur && cur.depth() > d && match(cur) > 0);
938 LASSERT(match(cur) > 0, /* */);
939 LYXERR(Debug::FIND, "Ok");
941 // Compute the match length
943 if (cur.pos() + len > cur.lastpos())
945 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
946 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
948 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
950 // Length of matched text (different from len param)
951 int old_len = match(cur, len);
953 // Greedy behaviour while matching regexps
954 while ((new_len = match(cur, len + 1)) > old_len) {
957 LYXERR(Debug::FIND, "verifying match with len = " << len);
964 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
968 while (cur && !match(cur, -1, false)) {
969 if (cur.pit() < cur.lastpit())
975 for (; cur; cur.forwardPos()) {
977 return findAdvFinalize(cur, match);
983 /// Find the most backward consecutive match within same paragraph while searching backwards.
984 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
986 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
987 DocIterator tmp_cur = cur;
988 int len = findAdvFinalize(tmp_cur, match);
989 Inset & inset = cur.inset();
990 for (; cur != cur_begin; cur.backwardPos()) {
991 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
992 DocIterator new_cur = cur;
993 new_cur.backwardPos();
994 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
996 int new_len = findAdvFinalize(new_cur, match);
1001 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1007 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1010 // Backup of original position
1011 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1012 if (cur == cur_begin)
1015 DocIterator cur_orig(cur);
1017 bool pit_changed = false;
1018 found_match = false;
1021 found_match = match(cur, -1, false);
1025 cur.pos() = cur.lastpos();
1027 cur.pos() = cur_orig.pos();
1028 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1029 DocIterator cur_prev_iter;
1031 found_match = match(cur);
1032 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1033 << found_match << ", cur: " << cur);
1035 return findMostBackwards(cur, match);
1037 // Stop if begin of document reached
1038 if (cur == cur_begin)
1040 cur_prev_iter = cur;
1044 if (cur == cur_begin)
1056 } // anonym namespace
1059 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1060 DocIterator const & cur, int len)
1062 if (!opt.ignoreformat)
1063 return latexifyFromCursor(cur, len);
1065 return stringifyFromCursor(cur, len);
1069 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1070 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1071 bool regexp, docstring const & replace, bool keep_case,
1073 : search(search), casesensitive(casesensitive), matchword(matchword),
1074 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1075 regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1080 /** Checks if the supplied character is lower-case */
1081 static bool isLowerCase(char_type ch) {
1082 return lowercase(ch) == ch;
1086 /** Checks if the supplied character is upper-case */
1087 static bool isUpperCase(char_type ch) {
1088 return uppercase(ch) == ch;
1092 /** Check if 'len' letters following cursor are all non-lowercase */
1093 static bool allNonLowercase(DocIterator const & cur, int len) {
1094 pos_type end_pos = cur.pos() + len;
1095 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1096 if (isLowerCase(cur.paragraph().getChar(pos)))
1102 /** Check if first letter is upper case and second one is lower case */
1103 static bool firstUppercase(DocIterator const & cur) {
1105 if (cur.pos() >= cur.lastpos() - 1) {
1106 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1109 ch1 = cur.paragraph().getChar(cur.pos());
1110 ch2 = cur.paragraph().getChar(cur.pos()+1);
1111 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1112 LYXERR(Debug::FIND, "firstUppercase(): "
1113 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1114 << ch2 << "(" << char(ch2) << ")"
1115 << ", result=" << result << ", cur=" << cur);
1120 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1122 ** \fixme What to do with possible further paragraphs in replace buffer ?
1124 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1125 ParagraphList::iterator pit = buffer.paragraphs().begin();
1126 pos_type right = pos_type(1);
1127 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1128 right = pit->size() + 1;
1129 pit->changeCase(buffer.params(), right, right, others_case);
1134 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1136 Cursor & cur = bv->cursor();
1137 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING)))
1139 DocIterator sel_beg = cur.selectionBegin();
1140 DocIterator sel_end = cur.selectionEnd();
1141 if (&sel_beg.inset() != &sel_end.inset()
1142 || sel_beg.pit() != sel_end.pit())
1144 int sel_len = sel_end.pos() - sel_beg.pos();
1145 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1146 << ", sel_len: " << sel_len << endl);
1149 LASSERT(sel_len > 0, /**/);
1151 if (!matchAdv(sel_beg, sel_len))
1154 string lyx = to_utf8(opt.replace);
1155 // FIXME: Seems so stupid to me to rebuild a buffer here,
1156 // when we already have one (replace_work_area_.buffer())
1157 Buffer repl_buffer("", false);
1158 repl_buffer.setUnnamed(true);
1159 LASSERT(repl_buffer.readString(lyx), /**/);
1160 repl_buffer.changeLanguage(
1161 repl_buffer.language(),
1162 cur.getFont().language());
1163 if (opt.keep_case && sel_len >= 2) {
1164 if (cur.inTexted()) {
1165 if (firstUppercase(cur))
1166 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1167 else if (allNonLowercase(cur, sel_len))
1168 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1171 cap::cutSelection(cur, false, false);
1172 if (!cur.inMathed()) {
1173 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1174 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1175 repl_buffer.params().documentClassPtr(),
1176 bv->buffer().errorList("Paste"));
1178 odocstringstream ods;
1179 OutputParams runparams(&repl_buffer.params().encoding());
1180 runparams.nice = false;
1181 runparams.flavor = OutputParams::LATEX;
1182 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1183 runparams.dryrun = true;
1185 TeXOnePar(repl_buffer, repl_buffer.text(),
1186 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1187 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1188 docstring repl_latex = ods.str();
1189 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1191 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1192 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1193 repl_latex = from_utf8(s);
1194 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1195 cur.niceInsert(repl_latex);
1197 bv->buffer().markDirty();
1198 cur.pos() -= repl_buffer.paragraphs().begin()->size();
1199 bv->putSelectionAt(DocIterator(cur), repl_buffer.paragraphs().begin()->size(), !opt.forward);
1203 /// Perform a FindAdv operation.
1204 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1209 if (opt.search.empty()) {
1210 bv->message(_("Search text is empty!"));
1215 MatchStringAdv matchAdv(bv->buffer(), opt);
1216 findAdvReplace(bv, opt, matchAdv);
1219 match_len = findForwardAdv(cur, matchAdv);
1221 match_len = findBackwardsAdv(cur, matchAdv);
1223 // This may only be raised by lyx::regex()
1224 bv->message(_("Invalid regular expression!"));
1228 if (match_len == 0) {
1229 bv->message(_("Match not found!"));
1233 bv->message(_("Match found!"));
1235 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1236 bv->putSelectionAt(cur, match_len, !opt.forward);
1242 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1244 os << to_utf8(opt.search) << "\nEOSS\n"
1245 << opt.casesensitive << ' '
1246 << opt.matchword << ' '
1247 << opt.forward << ' '
1248 << opt.expandmacros << ' '
1249 << opt.ignoreformat << ' '
1250 << opt.regexp << ' '
1251 << to_utf8(opt.replace) << "\nEOSS\n"
1252 << opt.keep_case << ' '
1255 LYXERR(Debug::FIND, "built: " << os.str());
1260 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1262 LYXERR(Debug::FIND, "parsing");
1266 while (line != "EOSS") {
1270 if (is.eof()) // Tolerate malformed request
1274 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1275 opt.search = from_utf8(s);
1276 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1277 is.get(); // Waste space before replace string
1280 while (line != "EOSS") {
1284 if (is.eof()) // Tolerate malformed request
1288 is >> opt.keep_case;
1291 opt.scope = FindAndReplaceOptions::SearchScope(i);
1292 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1293 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1294 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1295 opt.replace = from_utf8(s);