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/Application.h"
37 #include "frontends/alert.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathGrid.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathStream.h"
43 #include "mathed/MathSupport.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
52 #include "support/regex.h"
53 #include <boost/next_prior.hpp>
56 using namespace lyx::support;
62 bool parse_bool(docstring & howto)
67 howto = split(howto, var, ' ');
72 class MatchString : public binary_function<Paragraph, pos_type, int>
75 MatchString(docstring const & str, bool cs, bool mw)
76 : str(str), case_sens(cs), whole_words(mw)
79 // returns true if the specified string is at the specified position
80 // del specifies whether deleted strings in ct mode will be considered
81 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
83 return par.find(str, case_sens, whole_words, pos, del);
91 // match whole words only
96 int findForward(DocIterator & cur, MatchString const & match,
99 for (; cur; cur.forwardChar())
100 if (cur.inTexted()) {
101 int len = match(cur.paragraph(), cur.pos(), find_del);
109 int findBackwards(DocIterator & cur, MatchString const & match,
110 bool find_del = true)
114 if (cur.inTexted()) {
115 int len = match(cur.paragraph(), cur.pos(), find_del);
124 bool findChange(DocIterator & cur, bool next)
128 for (; cur; next ? cur.forwardPos() : cur.backwardPos())
129 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
131 // if we search backwards, take a step forward
132 // to correctly set the anchor
141 bool searchAllowed(docstring const & str)
144 frontend::Alert::error(_("Search error"), _("Search string is empty"));
151 bool findOne(BufferView * bv, docstring const & searchstr,
152 bool case_sens, bool whole, bool forward, bool find_del = true)
154 if (!searchAllowed(searchstr))
157 DocIterator cur = bv->cursor();
159 MatchString const match(searchstr, case_sens, whole);
161 int match_len = forward
162 ? findForward(cur, match, find_del)
163 : findBackwards(cur, match, find_del);
166 bv->putSelectionAt(cur, match_len, !forward);
168 return match_len > 0;
172 int replaceAll(BufferView * bv,
173 docstring const & searchstr, docstring const & replacestr,
174 bool case_sens, bool whole)
176 Buffer & buf = bv->buffer();
178 if (!searchAllowed(searchstr) || buf.isReadonly())
181 DocIterator cur_orig(bv->cursor());
183 MatchString const match(searchstr, case_sens, whole);
186 int const rsize = replacestr.size();
187 int const ssize = searchstr.size();
190 cur.setCursor(doc_iterator_begin(&buf));
191 int match_len = findForward(cur, match, false);
192 while (match_len > 0) {
193 // Backup current cursor position and font.
194 pos_type const pos = cur.pos();
195 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
197 int striked = ssize -
198 cur.paragraph().eraseChars(pos, pos + match_len,
199 buf.params().trackChanges);
200 cur.paragraph().insert(pos, replacestr, font,
201 Change(buf.params().trackChanges
203 : Change::UNCHANGED));
204 for (int i = 0; i < rsize + striked; ++i)
207 match_len = findForward(cur, match, false);
210 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
212 cur_orig.fixIfBroken();
213 bv->setCursor(cur_orig);
219 // the idea here is that we are going to replace the string that
220 // is selected IF it is the search string.
221 // if there is a selection, but it is not the search string, then
222 // we basically ignore it. (FIXME We ought to replace only within
224 // if there is no selection, then:
225 // (i) if some search string has been provided, then we find it.
226 // (think of how the dialog works when you hit "replace" the
228 // (ii) if no search string has been provided, then we treat the
229 // word the cursor is in as the search string. (why? i have no
230 // idea.) but this only works in text?
232 // returns the number of replacements made (one, if any) and
233 // whether anything at all was done.
234 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
235 docstring const & replacestr, bool case_sens,
236 bool whole, bool forward, bool findnext)
238 Cursor & cur = bv->cursor();
239 if (!cur.selection()) {
240 // no selection, non-empty search string: find it
241 if (!searchstr.empty()) {
242 findOne(bv, searchstr, case_sens, whole, forward);
243 return make_pair(true, 0);
245 // empty search string
248 return make_pair(false, 0);
249 // select current word and treat it as the search string
250 cur.innerText()->selectWord(cur, WHOLE_WORD);
251 searchstr = cur.selectionAsString(false);
254 // if we still don't have a search string, report the error
256 if (!searchAllowed(searchstr))
257 return make_pair(false, 0);
259 bool have_selection = cur.selection();
260 docstring const selected = cur.selectionAsString(false);
263 ? searchstr == selected
264 : compare_no_case(searchstr, selected) == 0;
266 // no selection or current selection is not search word:
267 // just find the search word
268 if (!have_selection || !match) {
269 findOne(bv, searchstr, case_sens, whole, forward);
270 return make_pair(true, 0);
273 // we're now actually ready to replace. if the buffer is
274 // read-only, we can't, though.
275 if (bv->buffer().isReadonly())
276 return make_pair(false, 0);
278 cap::replaceSelectionWithString(cur, replacestr);
280 cur.pos() += replacestr.length();
281 LASSERT(cur.pos() <= cur.lastpos(), /* */);
284 findOne(bv, searchstr, case_sens, whole, forward, false);
286 return make_pair(true, 1);
292 docstring const find2string(docstring const & search,
293 bool casesensitive, bool matchword, bool forward)
297 << int(casesensitive) << ' '
298 << int(matchword) << ' '
304 docstring const replace2string(docstring const & replace,
305 docstring const & search,
306 bool casesensitive, bool matchword,
307 bool all, bool forward, bool findnext)
310 ss << replace << '\n'
312 << int(casesensitive) << ' '
313 << int(matchword) << ' '
315 << int(forward) << ' '
321 bool lyxfind(BufferView * bv, FuncRequest const & ev)
323 if (!bv || ev.action() != LFUN_WORD_FIND)
326 //lyxerr << "find called, cmd: " << ev << endl;
328 // data is of the form
330 // <casesensitive> <matchword> <forward>"
332 docstring howto = split(ev.argument(), search, '\n');
334 bool casesensitive = parse_bool(howto);
335 bool matchword = parse_bool(howto);
336 bool forward = parse_bool(howto);
338 return findOne(bv, search, casesensitive, matchword, forward);
342 bool lyxreplace(BufferView * bv,
343 FuncRequest const & ev, bool has_deleted)
345 if (!bv || ev.action() != LFUN_WORD_REPLACE)
348 // data is of the form
351 // <casesensitive> <matchword> <all> <forward> <findnext>"
354 docstring howto = split(ev.argument(), rplc, '\n');
355 howto = split(howto, search, '\n');
357 bool casesensitive = parse_bool(howto);
358 bool matchword = parse_bool(howto);
359 bool all = parse_bool(howto);
360 bool forward = parse_bool(howto);
361 bool findnext = howto.empty() ? true : parse_bool(howto);
363 int replace_count = 0;
368 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
369 update = replace_count > 0;
372 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
374 replace_count = rv.second;
377 Buffer const & buf = bv->buffer();
379 // emit message signal.
380 buf.message(_("String not found!"));
382 if (replace_count == 0) {
383 buf.message(_("String found."));
384 } else if (replace_count == 1) {
385 buf.message(_("String has been replaced."));
387 docstring const str =
388 bformat(_("%1$d strings have been replaced."), replace_count);
392 } else if (findnext) {
393 // if we have deleted characters, we do not replace at all, but
394 // rather search for the next occurence
395 if (findOne(bv, search, casesensitive, matchword, forward))
398 bv->message(_("String not found!"));
404 bool findNextChange(BufferView * bv)
406 return findChange(bv, true);
410 bool findPreviousChange(BufferView * bv)
412 return findChange(bv, false);
416 bool findChange(BufferView * bv, bool next)
418 if (bv->cursor().selection()) {
419 // set the cursor at the beginning or at the end of the selection
420 // before searching. Otherwise, the current change will be found.
421 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
422 bv->cursor().setCursorToAnchor();
425 DocIterator cur = bv->cursor();
427 // Are we within a change ? Then first search forward (backward),
428 // clear the selection and search the other way around (see the end
429 // of this function). This will avoid changes to be selected half.
430 bool search_both_sides = false;
431 DocIterator tmpcur = cur;
433 while (tmpcur.inMathed())
435 Change change_next_pos
436 = tmpcur.paragraph().lookupChange(tmpcur.pos());
437 if (change_next_pos.changed() && cur.inMathed()) {
439 search_both_sides = true;
440 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
441 Change change_prev_pos
442 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
443 if (change_next_pos.isSimilarTo(change_prev_pos))
444 search_both_sides = true;
447 if (!findChange(cur, next))
450 bv->cursor().setCursor(cur);
451 bv->cursor().resetAnchor();
454 // take a step into the change
457 Change orig_change = cur.paragraph().lookupChange(cur.pos());
459 CursorSlice & tip = cur.top();
461 for (; !tip.at_end(); tip.forwardPos()) {
462 Change change = tip.paragraph().lookupChange(tip.pos());
463 if (!change.isSimilarTo(orig_change))
467 for (; !tip.at_begin();) {
469 Change change = tip.paragraph().lookupChange(tip.pos());
470 if (!change.isSimilarTo(orig_change)) {
471 // take a step forward to correctly set the selection
478 // Now put cursor to end of selection:
479 bv->cursor().setCursor(cur);
480 bv->cursor().setSelection();
482 if (search_both_sides) {
483 bv->cursor().setSelection(false);
484 findChange(bv, !next);
492 typedef vector<pair<string, string> > Escapes;
494 /// A map of symbols and their escaped equivalent needed within a regex.
495 /// @note Beware of order
496 Escapes const & get_regexp_escapes()
498 typedef std::pair<std::string, std::string> P;
500 static Escapes escape_map;
501 if (escape_map.empty()) {
502 escape_map.push_back(P("$", "_x_$"));
503 escape_map.push_back(P("{", "_x_{"));
504 escape_map.push_back(P("}", "_x_}"));
505 escape_map.push_back(P("[", "_x_["));
506 escape_map.push_back(P("]", "_x_]"));
507 escape_map.push_back(P("(", "_x_("));
508 escape_map.push_back(P(")", "_x_)"));
509 escape_map.push_back(P("+", "_x_+"));
510 escape_map.push_back(P("*", "_x_*"));
511 escape_map.push_back(P(".", "_x_."));
512 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
513 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
514 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
515 escape_map.push_back(P("_x_", "\\"));
520 /// A map of lyx escaped strings and their unescaped equivalent.
521 Escapes const & get_lyx_unescapes()
523 typedef std::pair<std::string, std::string> P;
525 static Escapes escape_map;
526 if (escape_map.empty()) {
527 escape_map.push_back(P("\\%", "%"));
528 escape_map.push_back(P("\\mathcircumflex ", "^"));
529 escape_map.push_back(P("\\mathcircumflex", "^"));
530 escape_map.push_back(P("\\backslash ", "\\"));
531 escape_map.push_back(P("\\backslash", "\\"));
532 escape_map.push_back(P("\\\\{", "_x_<"));
533 escape_map.push_back(P("\\\\}", "_x_>"));
534 escape_map.push_back(P("\\sim ", "~"));
535 escape_map.push_back(P("\\sim", "~"));
540 /// A map of escapes turning a regexp matching text to one matching latex.
541 Escapes const & get_regexp_latex_escapes()
543 typedef std::pair<std::string, std::string> P;
545 static Escapes escape_map;
546 if (escape_map.empty()) {
547 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
548 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
549 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
550 escape_map.push_back(P("\\[", "\\{\\[\\}"));
551 escape_map.push_back(P("\\]", "\\{\\]\\}"));
552 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
553 escape_map.push_back(P("%", "\\\\\\%"));
558 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
559 ** the found occurrence were escaped.
561 string apply_escapes(string s, Escapes const & escape_map)
563 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
564 Escapes::const_iterator it;
565 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
566 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
567 unsigned int pos = 0;
568 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
569 s.replace(pos, it->first.length(), it->second);
570 LYXERR(Debug::FIND, "After escape: " << s);
571 pos += it->second.length();
572 // LYXERR(Debug::FIND, "pos: " << pos);
575 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
580 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
581 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
582 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
583 string escape_for_regex(string s, bool match_latex)
586 while (pos < s.size()) {
587 size_t new_pos = s.find("\\regexp{", pos);
588 if (new_pos == string::npos)
590 LYXERR(Debug::FIND, "new_pos: " << new_pos);
591 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
592 LYXERR(Debug::FIND, "t [lyx]: " << t);
593 t = apply_escapes(t, get_regexp_escapes());
594 LYXERR(Debug::FIND, "t [rxp]: " << t);
595 s.replace(pos, new_pos - pos, t);
596 new_pos = pos + t.size();
597 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
598 LYXERR(Debug::FIND, "new_pos: " << new_pos);
599 if (new_pos == s.size())
601 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
602 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
603 LYXERR(Debug::FIND, "end_pos: " << end_pos);
604 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
605 LYXERR(Debug::FIND, "t in regexp : " << t);
606 t = apply_escapes(t, get_lyx_unescapes());
607 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
609 t = apply_escapes(t, get_regexp_latex_escapes());
610 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
612 if (end_pos == s.size()) {
613 s.replace(new_pos, end_pos - new_pos, t);
615 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
618 s.replace(new_pos, end_pos + 13 - new_pos, t);
619 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
620 pos = new_pos + t.size();
621 LYXERR(Debug::FIND, "pos: " << pos);
627 /// Wrapper for lyx::regex_replace with simpler interface
628 bool regex_replace(string const & s, string & t, string const & searchstr,
629 string const & replacestr)
631 lyx::regex e(searchstr);
633 ostream_iterator<char, char> it(oss);
634 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
635 // tolerate t and s be references to the same variable
636 bool rv = (s != oss.str());
642 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
644 ** Verify that closed braces exactly match open braces. This avoids that, for example,
645 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
648 ** Number of open braces that must remain open at the end for the verification to succeed.
650 bool braces_match(string::const_iterator const & beg,
651 string::const_iterator const & end,
655 string::const_iterator it = beg;
656 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
657 for (; it != end; ++it) {
658 // Skip escaped braces in the count
663 } else if (*it == '{') {
665 } else if (*it == '}') {
666 if (open_pars == 0) {
667 LYXERR(Debug::FIND, "Found unmatched closed brace");
673 if (open_pars != unmatched) {
674 LYXERR(Debug::FIND, "Found " << open_pars
675 << " instead of " << unmatched
676 << " unmatched open braces at the end of count");
679 LYXERR(Debug::FIND, "Braces match as expected");
684 /** The class performing a match between a position in the document and the FindAdvOptions.
686 class MatchStringAdv {
688 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
690 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
691 ** constructor as opt.search, under the opt.* options settings.
694 ** If set, then match is searched only against beginning of text starting at cur.
695 ** If unset, then match is searched anywhere in text starting at cur.
698 ** The length of the matching text, or zero if no match was found.
700 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
705 /// first buffer on which search was started
706 lyx::Buffer * const p_first_buf;
708 FindAndReplaceOptions const & opt;
711 /// Auxiliary find method (does not account for opt.matchword)
712 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
714 /** Normalize a stringified or latexified LyX paragraph.
718 ** <li>if search is not casesensitive, then lowercase the string;
719 ** <li>remove any newline at begin or end of the string;
720 ** <li>replace any newline in the middle of the string with a simple space;
721 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
724 ** @todo Normalization should also expand macros, if the corresponding
725 ** search option was checked.
727 string normalize(docstring const & s, bool hack_braces) const;
728 // normalized string to search
729 string par_as_string;
730 // regular expression to use for searching
732 // same as regexp, but prefixed with a ".*"
734 // leading format material as string
735 string lead_as_string;
736 // par_as_string after removal of lead_as_string
737 string par_as_string_nolead;
738 // unmatched open braces in the search string/regexp
740 // number of (.*?) subexpressions added at end of search regexp for closing
741 // environments, math mode, styles, etc...
743 // Are we searching with regular expressions ?
748 static docstring buffer_to_latex(Buffer & buffer)
750 OutputParams runparams(&buffer.params().encoding());
752 odocstringstream ods;
753 otexstream os(ods, texrow);
754 runparams.nice = true;
755 runparams.flavor = OutputParams::LATEX;
756 runparams.linelen = 80; //lyxrc.plaintext_linelen;
757 // No side effect of file copying and image conversion
758 runparams.dryrun = true;
759 pit_type const endpit = buffer.paragraphs().size();
760 for (pit_type pit = 0; pit != endpit; ++pit) {
761 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
762 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
768 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
771 if (!opt.ignoreformat) {
772 str = buffer_to_latex(buffer);
774 OutputParams runparams(&buffer.params().encoding());
775 runparams.nice = true;
776 runparams.flavor = OutputParams::LATEX;
777 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
778 runparams.dryrun = true;
779 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
780 Paragraph const & par = buffer.paragraphs().at(pit);
781 LYXERR(Debug::FIND, "Adding to search string: '"
782 << par.stringify(pos_type(0), par.size(),
783 AS_STR_INSETS, runparams)
785 str += par.stringify(pos_type(0), par.size(),
786 AS_STR_INSETS, runparams);
793 /// Return separation pos between the leading material and the rest
794 static size_t identifyLeading(string const & s)
797 // @TODO Support \item[text]
798 while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
799 || regex_replace(t, t, "^\\$", "")
800 || regex_replace(t, t, "^\\\\\\[ ", "")
801 || regex_replace(t, t, "^\\\\item ", "")
802 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
803 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
808 // Remove trailing closure of math, macros and environments, so to catch parts of them.
809 static int identifyClosing(string & t)
813 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
814 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
816 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
818 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
820 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
830 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
831 : p_buf(&buf), p_first_buf(&buf), opt(opt)
833 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
834 docstring const & ds = stringifySearchBuffer(find_buf, opt);
835 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
836 // When using regexp, braces are hacked already by escape_for_regex()
837 par_as_string = normalize(ds, !use_regexp);
841 size_t lead_size = 0;
842 if (!opt.ignoreformat) {
843 lead_size = identifyLeading(par_as_string);
844 lead_as_string = par_as_string.substr(0, lead_size);
845 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
849 open_braces = identifyClosing(par_as_string);
850 identifyClosing(par_as_string_nolead);
851 LYXERR(Debug::FIND, "Open braces: " << open_braces);
852 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
854 string lead_as_regexp;
856 // @todo No need to search for \regexp{} insets in leading material
857 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
858 par_as_string = par_as_string_nolead;
859 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
860 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
862 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
863 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
864 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
866 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
867 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
868 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
869 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
870 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
871 || regex_replace(par_as_string, par_as_string,
872 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
873 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
874 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
878 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
879 LYXERR(Debug::FIND, "Open braces: " << open_braces);
880 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
881 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
882 // If entered regexp must match at begin of searched string buffer
883 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
884 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
885 regexp = lyx::regex(regexp_str);
887 // If entered regexp may match wherever in searched string buffer
888 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
889 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
890 regexp2 = lyx::regex(regexp2_str);
895 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
897 docstring docstr = stringifyFromForSearch(opt, cur, len);
898 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
899 string str = normalize(docstr, true);
900 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
902 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
903 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
905 LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
906 if (str.substr(0, par_as_string.size()) == par_as_string)
907 return par_as_string.size();
909 size_t pos = str.find(par_as_string_nolead);
910 if (pos != string::npos)
911 return par_as_string.size();
914 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
915 // Try all possible regexp matches,
916 //until one that verifies the braces match test is found
917 regex const *p_regexp = at_begin ? ®exp : ®exp2;
918 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
919 sregex_iterator re_it_end;
920 for (; re_it != re_it_end; ++re_it) {
921 match_results<string::const_iterator> const & m = *re_it;
922 // Check braces on the segment that matched the entire regexp expression,
923 // plus the last subexpression, if a (.*?) was inserted in the constructor.
924 if (!braces_match(m[0].first, m[0].second, open_braces))
926 // Check braces on segments that matched all (.*?) subexpressions,
927 // except the last "padding" one inserted by lyx.
928 for (size_t i = 1; i < m.size() - 1; ++i)
929 if (!braces_match(m[i].first, m[i].second))
931 // Exclude from the returned match length any length
932 // due to close wildcards added at end of regexp
933 if (close_wildcards == 0)
934 return m[0].second - m[0].first;
936 return m[m.size() - close_wildcards].first - m[0].first;
943 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
945 int res = findAux(cur, len, at_begin);
947 "res=" << res << ", at_begin=" << at_begin
948 << ", matchword=" << opt.matchword
949 << ", inTexted=" << cur.inTexted());
950 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
952 Paragraph const & par = cur.paragraph();
953 bool ws_left = (cur.pos() > 0)
954 ? par.isWordSeparator(cur.pos() - 1)
956 bool ws_right = (cur.pos() + res < par.size())
957 ? par.isWordSeparator(cur.pos() + res)
960 "cur.pos()=" << cur.pos() << ", res=" << res
961 << ", separ: " << ws_left << ", " << ws_right
963 if (ws_left && ws_right)
969 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
972 if (! opt.casesensitive)
973 t = lyx::to_utf8(lowercase(s));
976 // Remove \n at begin
977 while (!t.empty() && t[0] == '\n')
980 while (!t.empty() && t[t.size() - 1] == '\n')
981 t = t.substr(0, t.size() - 1);
983 // Replace all other \n with spaces
984 while ((pos = t.find("\n")) != string::npos)
985 t.replace(pos, 1, " ");
986 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
987 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
988 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
989 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
991 // FIXME - check what preceeds the brace
993 if (opt.ignoreformat)
994 while (regex_replace(t, t, "\\{", "_x_<")
995 || regex_replace(t, t, "\\}", "_x_>"))
996 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
998 while (regex_replace(t, t, "\\\\\\{", "_x_<")
999 || regex_replace(t, t, "\\\\\\}", "_x_>"))
1000 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1007 docstring stringifyFromCursor(DocIterator const & cur, int len)
1009 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1010 if (cur.inTexted()) {
1011 Paragraph const & par = cur.paragraph();
1012 // TODO what about searching beyond/across paragraph breaks ?
1013 // TODO Try adding a AS_STR_INSERTS as last arg
1014 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1015 int(par.size()) : cur.pos() + len;
1016 OutputParams runparams(&cur.buffer()->params().encoding());
1017 odocstringstream os;
1018 runparams.nice = true;
1019 runparams.flavor = OutputParams::LATEX;
1020 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1021 // No side effect of file copying and image conversion
1022 runparams.dryrun = true;
1023 LYXERR(Debug::FIND, "Stringifying with cur: "
1024 << cur << ", from pos: " << cur.pos() << ", end: " << end);
1025 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
1026 } else if (cur.inMathed()) {
1028 CursorSlice cs = cur.top();
1029 MathData md = cs.cell();
1030 MathData::const_iterator it_end =
1031 (( len == -1 || cs.pos() + len > int(md.size()))
1033 : md.begin() + cs.pos() + len );
1034 for (MathData::const_iterator it = md.begin() + cs.pos();
1036 s = s + asString(*it);
1037 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1040 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1045 /** Computes the LaTeX export of buf starting from cur and ending len positions
1046 * after cur, if len is positive, or at the paragraph or innermost inset end
1049 docstring latexifyFromCursor(DocIterator const & cur, int len)
1051 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1052 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1053 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1054 Buffer const & buf = *cur.buffer();
1055 LASSERT(buf.params().isLatex(), /* */);
1058 odocstringstream ods;
1059 otexstream os(ods, texrow);
1060 OutputParams runparams(&buf.params().encoding());
1061 runparams.nice = false;
1062 runparams.flavor = OutputParams::LATEX;
1063 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1064 // No side effect of file copying and image conversion
1065 runparams.dryrun = true;
1067 if (cur.inTexted()) {
1068 // @TODO what about searching beyond/across paragraph breaks ?
1069 pos_type endpos = cur.paragraph().size();
1070 if (len != -1 && endpos > cur.pos() + len)
1071 endpos = cur.pos() + len;
1072 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1073 string(), cur.pos(), endpos);
1074 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1075 } else if (cur.inMathed()) {
1076 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1077 for (int s = cur.depth() - 1; s >= 0; --s) {
1078 CursorSlice const & cs = cur[s];
1079 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1080 WriteStream ws(ods);
1081 cs.asInsetMath()->asHullInset()->header_write(ws);
1086 CursorSlice const & cs = cur.top();
1087 MathData md = cs.cell();
1088 MathData::const_iterator it_end =
1089 ((len == -1 || cs.pos() + len > int(md.size()))
1091 : md.begin() + cs.pos() + len);
1092 for (MathData::const_iterator it = md.begin() + cs.pos();
1094 ods << asString(*it);
1096 // Retrieve the math environment type, and add '$' or '$]'
1097 // or others (\end{equation}) accordingly
1098 for (int s = cur.depth() - 1; s >= 0; --s) {
1099 CursorSlice const & cs = cur[s];
1100 InsetMath * inset = cs.asInsetMath();
1101 if (inset && inset->asHullInset()) {
1102 WriteStream ws(ods);
1103 inset->asHullInset()->footer_write(ws);
1107 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1109 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1115 /** Finalize an advanced find operation, advancing the cursor to the innermost
1116 ** position that matches, plus computing the length of the matching text to
1119 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1121 // Search the foremost position that matches (avoids find of entire math
1122 // inset when match at start of it)
1124 DocIterator old_cur(cur.buffer());
1126 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1130 } while (cur && cur.depth() > d && match(cur) > 0);
1132 LASSERT(match(cur) > 0, /* */);
1133 LYXERR(Debug::FIND, "Ok");
1135 // Compute the match length
1137 if (cur.pos() + len > cur.lastpos())
1139 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1140 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1142 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1144 // Length of matched text (different from len param)
1145 int old_len = match(cur, len);
1147 // Greedy behaviour while matching regexps
1148 while ((new_len = match(cur, len + 1)) > old_len) {
1151 LYXERR(Debug::FIND, "verifying match with len = " << len);
1158 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1162 while (!theApp()->longOperationCancelled() && cur) {
1163 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1164 int match_len = match(cur, -1, false);
1165 LYXERR(Debug::FIND, "match_len: " << match_len);
1167 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1168 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1169 int match_len = match(cur);
1170 LYXERR(Debug::FIND, "match_len: " << match_len);
1172 // Sometimes in finalize we understand it wasn't a match
1173 // and we need to continue the outest loop
1174 int len = findAdvFinalize(cur, match);
1182 if (cur.pit() < cur.lastpit()) {
1183 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1186 // This should exit nested insets, if any, or otherwise undefine the currsor.
1187 cur.pos() = cur.lastpos();
1188 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1196 /// Find the most backward consecutive match within same paragraph while searching backwards.
1197 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1199 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1200 DocIterator tmp_cur = cur;
1201 int len = findAdvFinalize(tmp_cur, match);
1202 Inset & inset = cur.inset();
1203 for (; cur != cur_begin; cur.backwardPos()) {
1204 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1205 DocIterator new_cur = cur;
1206 new_cur.backwardPos();
1207 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1209 int new_len = findAdvFinalize(new_cur, match);
1214 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1220 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1224 // Backup of original position
1225 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1226 if (cur == cur_begin)
1229 DocIterator cur_orig(cur);
1231 bool pit_changed = false;
1232 found_match = false;
1235 found_match = match(cur, -1, false);
1239 cur.pos() = cur.lastpos();
1241 cur.pos() = cur_orig.pos();
1242 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1243 DocIterator cur_prev_iter;
1245 found_match = match(cur);
1246 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1247 << found_match << ", cur: " << cur);
1249 return findMostBackwards(cur, match);
1251 // Stop if begin of document reached
1252 if (cur == cur_begin)
1254 cur_prev_iter = cur;
1258 if (cur == cur_begin)
1265 } while (!theApp()->longOperationCancelled());
1270 } // anonym namespace
1273 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1274 DocIterator const & cur, int len)
1276 LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1277 if (!opt.ignoreformat)
1278 return latexifyFromCursor(cur, len);
1280 return stringifyFromCursor(cur, len);
1284 FindAndReplaceOptions::FindAndReplaceOptions(
1285 docstring const & find_buf_name, bool casesensitive,
1286 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1287 docstring const & repl_buf_name, bool keep_case,
1289 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1290 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1291 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1299 /** Check if 'len' letters following cursor are all non-lowercase */
1300 static bool allNonLowercase(DocIterator const & cur, int len)
1302 pos_type end_pos = cur.pos() + len;
1303 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1304 if (isLowerCase(cur.paragraph().getChar(pos)))
1310 /** Check if first letter is upper case and second one is lower case */
1311 static bool firstUppercase(DocIterator const & cur)
1314 if (cur.pos() >= cur.lastpos() - 1) {
1315 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1318 ch1 = cur.paragraph().getChar(cur.pos());
1319 ch2 = cur.paragraph().getChar(cur.pos()+1);
1320 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1321 LYXERR(Debug::FIND, "firstUppercase(): "
1322 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1323 << ch2 << "(" << char(ch2) << ")"
1324 << ", result=" << result << ", cur=" << cur);
1329 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1331 ** \fixme What to do with possible further paragraphs in replace buffer ?
1333 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1335 ParagraphList::iterator pit = buffer.paragraphs().begin();
1336 pos_type right = pos_type(1);
1337 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1338 right = pit->size() + 1;
1339 pit->changeCase(buffer.params(), right, right, others_case);
1345 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1347 Cursor & cur = bv->cursor();
1348 if (opt.repl_buf_name == docstring())
1351 DocIterator sel_beg = cur.selectionBegin();
1352 DocIterator sel_end = cur.selectionEnd();
1353 if (&sel_beg.inset() != &sel_end.inset()
1354 || sel_beg.pit() != sel_end.pit())
1356 int sel_len = sel_end.pos() - sel_beg.pos();
1357 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1358 << ", sel_len: " << sel_len << endl);
1361 LASSERT(sel_len > 0, /**/);
1363 if (!matchAdv(sel_beg, sel_len))
1366 // Build a copy of the replace buffer, adapted to the KeepCase option
1367 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1369 repl_buffer_orig.write(oss);
1370 string lyx = oss.str();
1371 Buffer repl_buffer("", false);
1372 repl_buffer.setUnnamed(true);
1373 LASSERT(repl_buffer.readString(lyx), /**/);
1374 if (opt.keep_case && sel_len >= 2) {
1375 if (cur.inTexted()) {
1376 if (firstUppercase(cur))
1377 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1378 else if (allNonLowercase(cur, sel_len))
1379 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1382 cap::cutSelection(cur, false, false);
1383 if (cur.inTexted()) {
1384 repl_buffer.changeLanguage(
1385 repl_buffer.language(),
1386 cur.getFont().language());
1387 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1388 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1389 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1390 repl_buffer.params().documentClassPtr(),
1391 bv->buffer().errorList("Paste"));
1392 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1393 sel_len = repl_buffer.paragraphs().begin()->size();
1394 } else if (cur.inMathed()) {
1396 odocstringstream ods;
1397 otexstream os(ods, texrow);
1398 OutputParams runparams(&repl_buffer.params().encoding());
1399 runparams.nice = false;
1400 runparams.flavor = OutputParams::LATEX;
1401 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1402 runparams.dryrun = true;
1403 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1404 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1405 docstring repl_latex = ods.str();
1406 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1408 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1409 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1410 repl_latex = from_utf8(s);
1411 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1412 MathData ar(cur.buffer());
1413 asArray(repl_latex, ar, Parse::NORMAL);
1415 sel_len = ar.size();
1416 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1418 if (cur.pos() >= sel_len)
1419 cur.pos() -= sel_len;
1422 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1423 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1424 bv->processUpdateFlags(Update::Force);
1425 bv->buffer().updatePreviews();
1429 /// Perform a FindAdv operation.
1430 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1436 MatchStringAdv matchAdv(bv->buffer(), opt);
1437 findAdvReplace(bv, opt, matchAdv);
1440 match_len = findForwardAdv(cur, matchAdv);
1442 match_len = findBackwardsAdv(cur, matchAdv);
1444 // This may only be raised by lyx::regex()
1445 bv->message(_("Invalid regular expression!"));
1449 if (match_len == 0) {
1450 bv->message(_("Match not found!"));
1454 bv->message(_("Match found!"));
1456 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1457 bv->putSelectionAt(cur, match_len, !opt.forward);
1463 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1465 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1466 << opt.casesensitive << ' '
1467 << opt.matchword << ' '
1468 << opt.forward << ' '
1469 << opt.expandmacros << ' '
1470 << opt.ignoreformat << ' '
1471 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1472 << opt.keep_case << ' '
1475 LYXERR(Debug::FIND, "built: " << os.str());
1481 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1483 LYXERR(Debug::FIND, "parsing");
1487 while (line != "EOSS") {
1491 if (is.eof()) // Tolerate malformed request
1495 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1496 opt.find_buf_name = from_utf8(s);
1497 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1498 is.get(); // Waste space before replace string
1501 while (line != "EOSS") {
1505 if (is.eof()) // Tolerate malformed request
1509 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1510 opt.repl_buf_name = from_utf8(s);
1511 is >> opt.keep_case;
1514 opt.scope = FindAndReplaceOptions::SearchScope(i);
1515 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1516 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);