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 = forward
158 ? bv->cursor().selectionEnd()
159 : bv->cursor().selectionBegin();
161 MatchString const match(searchstr, case_sens, whole);
163 int match_len = forward
164 ? findForward(cur, match, find_del)
165 : findBackwards(cur, match, find_del);
168 bv->putSelectionAt(cur, match_len, !forward);
170 return match_len > 0;
174 int replaceAll(BufferView * bv,
175 docstring const & searchstr, docstring const & replacestr,
176 bool case_sens, bool whole)
178 Buffer & buf = bv->buffer();
180 if (!searchAllowed(searchstr) || buf.isReadonly())
183 DocIterator cur_orig(bv->cursor());
185 MatchString const match(searchstr, case_sens, whole);
188 int const rsize = replacestr.size();
189 int const ssize = searchstr.size();
192 cur.setCursor(doc_iterator_begin(&buf));
193 int match_len = findForward(cur, match, false);
194 while (match_len > 0) {
195 // Backup current cursor position and font.
196 pos_type const pos = cur.pos();
197 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
199 int striked = ssize -
200 cur.paragraph().eraseChars(pos, pos + match_len,
201 buf.params().trackChanges);
202 cur.paragraph().insert(pos, replacestr, font,
203 Change(buf.params().trackChanges
205 : Change::UNCHANGED));
206 for (int i = 0; i < rsize + striked; ++i)
209 match_len = findForward(cur, match, false);
212 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
214 cur_orig.fixIfBroken();
215 bv->setCursor(cur_orig);
221 // the idea here is that we are going to replace the string that
222 // is selected IF it is the search string.
223 // if there is a selection, but it is not the search string, then
224 // we basically ignore it. (FIXME We ought to replace only within
226 // if there is no selection, then:
227 // (i) if some search string has been provided, then we find it.
228 // (think of how the dialog works when you hit "replace" the
230 // (ii) if no search string has been provided, then we treat the
231 // word the cursor is in as the search string. (why? i have no
232 // idea.) but this only works in text?
234 // returns the number of replacements made (one, if any) and
235 // whether anything at all was done.
236 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
237 docstring const & replacestr, bool case_sens,
238 bool whole, bool forward, bool findnext)
240 Cursor & cur = bv->cursor();
241 if (!cur.selection()) {
242 // no selection, non-empty search string: find it
243 if (!searchstr.empty()) {
244 findOne(bv, searchstr, case_sens, whole, forward);
245 return make_pair(true, 0);
247 // empty search string
250 return make_pair(false, 0);
251 // select current word and treat it as the search string
252 cur.innerText()->selectWord(cur, WHOLE_WORD);
253 searchstr = cur.selectionAsString(false);
256 // if we still don't have a search string, report the error
258 if (!searchAllowed(searchstr))
259 return make_pair(false, 0);
261 bool have_selection = cur.selection();
262 docstring const selected = cur.selectionAsString(false);
265 ? searchstr == selected
266 : compare_no_case(searchstr, selected) == 0;
268 // no selection or current selection is not search word:
269 // just find the search word
270 if (!have_selection || !match) {
271 findOne(bv, searchstr, case_sens, whole, forward);
272 return make_pair(true, 0);
275 // we're now actually ready to replace. if the buffer is
276 // read-only, we can't, though.
277 if (bv->buffer().isReadonly())
278 return make_pair(false, 0);
280 cap::replaceSelectionWithString(cur, replacestr);
282 cur.pos() += replacestr.length();
283 LASSERT(cur.pos() <= cur.lastpos(), /* */);
286 findOne(bv, searchstr, case_sens, whole, forward, false);
288 return make_pair(true, 1);
294 docstring const find2string(docstring const & search,
295 bool casesensitive, bool matchword, bool forward)
299 << int(casesensitive) << ' '
300 << int(matchword) << ' '
306 docstring const replace2string(docstring const & replace,
307 docstring const & search,
308 bool casesensitive, bool matchword,
309 bool all, bool forward, bool findnext)
312 ss << replace << '\n'
314 << int(casesensitive) << ' '
315 << int(matchword) << ' '
317 << int(forward) << ' '
323 bool lyxfind(BufferView * bv, FuncRequest const & ev)
325 if (!bv || ev.action() != LFUN_WORD_FIND)
328 //lyxerr << "find called, cmd: " << ev << endl;
330 // data is of the form
332 // <casesensitive> <matchword> <forward>"
334 docstring howto = split(ev.argument(), search, '\n');
336 bool casesensitive = parse_bool(howto);
337 bool matchword = parse_bool(howto);
338 bool forward = parse_bool(howto);
340 return findOne(bv, search, casesensitive, matchword, forward);
344 bool lyxreplace(BufferView * bv,
345 FuncRequest const & ev, bool has_deleted)
347 if (!bv || ev.action() != LFUN_WORD_REPLACE)
350 // data is of the form
353 // <casesensitive> <matchword> <all> <forward> <findnext>"
356 docstring howto = split(ev.argument(), rplc, '\n');
357 howto = split(howto, search, '\n');
359 bool casesensitive = parse_bool(howto);
360 bool matchword = parse_bool(howto);
361 bool all = parse_bool(howto);
362 bool forward = parse_bool(howto);
363 bool findnext = howto.empty() ? true : parse_bool(howto);
365 int replace_count = 0;
370 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
371 update = replace_count > 0;
374 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
376 replace_count = rv.second;
379 Buffer const & buf = bv->buffer();
381 // emit message signal.
382 buf.message(_("String not found!"));
384 if (replace_count == 0) {
385 buf.message(_("String found."));
386 } else if (replace_count == 1) {
387 buf.message(_("String has been replaced."));
389 docstring const str =
390 bformat(_("%1$d strings have been replaced."), replace_count);
394 } else if (findnext) {
395 // if we have deleted characters, we do not replace at all, but
396 // rather search for the next occurence
397 if (findOne(bv, search, casesensitive, matchword, forward))
400 bv->message(_("String not found!"));
406 bool findNextChange(BufferView * bv)
408 return findChange(bv, true);
412 bool findPreviousChange(BufferView * bv)
414 return findChange(bv, false);
418 bool findChange(BufferView * bv, bool next)
420 if (bv->cursor().selection()) {
421 // set the cursor at the beginning or at the end of the selection
422 // before searching. Otherwise, the current change will be found.
423 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
424 bv->cursor().setCursorToAnchor();
427 DocIterator cur = bv->cursor();
429 // Are we within a change ? Then first search forward (backward),
430 // clear the selection and search the other way around (see the end
431 // of this function). This will avoid changes to be selected half.
432 bool search_both_sides = false;
433 DocIterator tmpcur = cur;
435 while (tmpcur.inMathed())
437 Change change_next_pos
438 = tmpcur.paragraph().lookupChange(tmpcur.pos());
439 if (change_next_pos.changed() && cur.inMathed()) {
441 search_both_sides = true;
442 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
443 Change change_prev_pos
444 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
445 if (change_next_pos.isSimilarTo(change_prev_pos))
446 search_both_sides = true;
449 if (!findChange(cur, next))
452 bv->cursor().setCursor(cur);
453 bv->cursor().resetAnchor();
456 // take a step into the change
459 Change orig_change = cur.paragraph().lookupChange(cur.pos());
461 CursorSlice & tip = cur.top();
463 for (; !tip.at_end(); tip.forwardPos()) {
464 Change change = tip.paragraph().lookupChange(tip.pos());
465 if (!change.isSimilarTo(orig_change))
469 for (; !tip.at_begin();) {
471 Change change = tip.paragraph().lookupChange(tip.pos());
472 if (!change.isSimilarTo(orig_change)) {
473 // take a step forward to correctly set the selection
480 // Now put cursor to end of selection:
481 bv->cursor().setCursor(cur);
482 bv->cursor().setSelection();
484 if (search_both_sides) {
485 bv->cursor().setSelection(false);
486 findChange(bv, !next);
494 typedef vector<pair<string, string> > Escapes;
496 /// A map of symbols and their escaped equivalent needed within a regex.
497 /// @note Beware of order
498 Escapes const & get_regexp_escapes()
500 typedef std::pair<std::string, std::string> P;
502 static Escapes escape_map;
503 if (escape_map.empty()) {
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("*", "_x_*"));
513 escape_map.push_back(P(".", "_x_."));
514 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
515 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
516 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
517 escape_map.push_back(P("_x_", "\\"));
522 /// A map of lyx escaped strings and their unescaped equivalent.
523 Escapes const & get_lyx_unescapes()
525 typedef std::pair<std::string, std::string> P;
527 static Escapes escape_map;
528 if (escape_map.empty()) {
529 escape_map.push_back(P("\\%", "%"));
530 escape_map.push_back(P("\\mathcircumflex ", "^"));
531 escape_map.push_back(P("\\mathcircumflex", "^"));
532 escape_map.push_back(P("\\backslash ", "\\"));
533 escape_map.push_back(P("\\backslash", "\\"));
534 escape_map.push_back(P("\\\\{", "_x_<"));
535 escape_map.push_back(P("\\\\}", "_x_>"));
536 escape_map.push_back(P("\\sim ", "~"));
537 escape_map.push_back(P("\\sim", "~"));
542 /// A map of escapes turning a regexp matching text to one matching latex.
543 Escapes const & get_regexp_latex_escapes()
545 typedef std::pair<std::string, std::string> P;
547 static Escapes escape_map;
548 if (escape_map.empty()) {
549 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\})"));
550 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
551 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
552 escape_map.push_back(P("\\[", "\\{\\[\\}"));
553 escape_map.push_back(P("\\]", "\\{\\]\\}"));
554 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\mathcircumflex)"));
555 escape_map.push_back(P("%", "\\\\\\%"));
560 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
561 ** the found occurrence were escaped.
563 string apply_escapes(string s, Escapes const & escape_map)
565 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
566 Escapes::const_iterator it;
567 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
568 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
569 unsigned int pos = 0;
570 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
571 s.replace(pos, it->first.length(), it->second);
572 LYXERR(Debug::FIND, "After escape: " << s);
573 pos += it->second.length();
574 // LYXERR(Debug::FIND, "pos: " << pos);
577 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
582 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
583 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
584 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
585 string escape_for_regex(string s, bool match_latex)
588 while (pos < s.size()) {
589 size_t new_pos = s.find("\\regexp{", pos);
590 if (new_pos == string::npos)
592 LYXERR(Debug::FIND, "new_pos: " << new_pos);
593 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
594 LYXERR(Debug::FIND, "t [lyx]: " << t);
595 t = apply_escapes(t, get_regexp_escapes());
596 LYXERR(Debug::FIND, "t [rxp]: " << t);
597 s.replace(pos, new_pos - pos, t);
598 new_pos = pos + t.size();
599 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
600 LYXERR(Debug::FIND, "new_pos: " << new_pos);
601 if (new_pos == s.size())
603 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
604 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
605 LYXERR(Debug::FIND, "end_pos: " << end_pos);
606 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
607 LYXERR(Debug::FIND, "t in regexp : " << t);
608 t = apply_escapes(t, get_lyx_unescapes());
609 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
611 t = apply_escapes(t, get_regexp_latex_escapes());
612 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
614 if (end_pos == s.size()) {
615 s.replace(new_pos, end_pos - new_pos, t);
617 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
620 s.replace(new_pos, end_pos + 13 - new_pos, t);
621 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
622 pos = new_pos + t.size();
623 LYXERR(Debug::FIND, "pos: " << pos);
629 /// Wrapper for lyx::regex_replace with simpler interface
630 bool regex_replace(string const & s, string & t, string const & searchstr,
631 string const & replacestr)
633 lyx::regex e(searchstr);
635 ostream_iterator<char, char> it(oss);
636 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
637 // tolerate t and s be references to the same variable
638 bool rv = (s != oss.str());
644 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
646 ** Verify that closed braces exactly match open braces. This avoids that, for example,
647 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
650 ** Number of open braces that must remain open at the end for the verification to succeed.
652 bool braces_match(string::const_iterator const & beg,
653 string::const_iterator const & end,
657 string::const_iterator it = beg;
658 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
659 for (; it != end; ++it) {
660 // Skip escaped braces in the count
665 } else if (*it == '{') {
667 } else if (*it == '}') {
668 if (open_pars == 0) {
669 LYXERR(Debug::FIND, "Found unmatched closed brace");
675 if (open_pars != unmatched) {
676 LYXERR(Debug::FIND, "Found " << open_pars
677 << " instead of " << unmatched
678 << " unmatched open braces at the end of count");
681 LYXERR(Debug::FIND, "Braces match as expected");
686 /** The class performing a match between a position in the document and the FindAdvOptions.
688 class MatchStringAdv {
690 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
692 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
693 ** constructor as opt.search, under the opt.* options settings.
696 ** If set, then match is searched only against beginning of text starting at cur.
697 ** If unset, then match is searched anywhere in text starting at cur.
700 ** The length of the matching text, or zero if no match was found.
702 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
707 /// first buffer on which search was started
708 lyx::Buffer * const p_first_buf;
710 FindAndReplaceOptions const & opt;
713 /// Auxiliary find method (does not account for opt.matchword)
714 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
716 /** Normalize a stringified or latexified LyX paragraph.
720 ** <li>if search is not casesensitive, then lowercase the string;
721 ** <li>remove any newline at begin or end of the string;
722 ** <li>replace any newline in the middle of the string with a simple space;
723 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
726 ** @todo Normalization should also expand macros, if the corresponding
727 ** search option was checked.
729 string normalize(docstring const & s, bool hack_braces) const;
730 // normalized string to search
731 string par_as_string;
732 // regular expression to use for searching
734 // same as regexp, but prefixed with a ".*"
736 // leading format material as string
737 string lead_as_string;
738 // par_as_string after removal of lead_as_string
739 string par_as_string_nolead;
740 // unmatched open braces in the search string/regexp
742 // number of (.*?) subexpressions added at end of search regexp for closing
743 // environments, math mode, styles, etc...
745 // Are we searching with regular expressions ?
750 static docstring buffer_to_latex(Buffer & buffer)
752 OutputParams runparams(&buffer.params().encoding());
754 odocstringstream ods;
755 otexstream os(ods, texrow);
756 runparams.nice = true;
757 runparams.flavor = OutputParams::LATEX;
758 runparams.linelen = 80; //lyxrc.plaintext_linelen;
759 // No side effect of file copying and image conversion
760 runparams.dryrun = true;
761 pit_type const endpit = buffer.paragraphs().size();
762 for (pit_type pit = 0; pit != endpit; ++pit) {
763 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
764 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
770 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
773 if (!opt.ignoreformat) {
774 str = buffer_to_latex(buffer);
776 OutputParams runparams(&buffer.params().encoding());
777 runparams.nice = true;
778 runparams.flavor = OutputParams::LATEX;
779 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
780 runparams.dryrun = true;
781 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
782 Paragraph const & par = buffer.paragraphs().at(pit);
783 LYXERR(Debug::FIND, "Adding to search string: '"
784 << par.stringify(pos_type(0), par.size(),
785 AS_STR_INSETS, runparams)
787 str += par.stringify(pos_type(0), par.size(),
788 AS_STR_INSETS, runparams);
795 /// Return separation pos between the leading material and the rest
796 static size_t identifyLeading(string const & s)
799 // @TODO Support \item[text]
800 while (regex_replace(t, t, "^\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
801 || regex_replace(t, t, "^\\$", "")
802 || regex_replace(t, t, "^\\\\\\[ ", "")
803 || regex_replace(t, t, "^\\\\item ", "")
804 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
805 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
810 // Remove trailing closure of math, macros and environments, so to catch parts of them.
811 static int identifyClosing(string & t)
815 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
816 if (regex_replace(t, t, "(.*[^\\\\])\\$\\'", "$1"))
818 if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
820 if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
822 if (regex_replace(t, t, "(.*[^\\\\])\\}\\'", "$1")) {
832 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
833 : p_buf(&buf), p_first_buf(&buf), opt(opt)
835 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
836 docstring const & ds = stringifySearchBuffer(find_buf, opt);
837 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
838 // When using regexp, braces are hacked already by escape_for_regex()
839 par_as_string = normalize(ds, !use_regexp);
843 size_t lead_size = 0;
844 if (!opt.ignoreformat) {
845 lead_size = identifyLeading(par_as_string);
846 lead_as_string = par_as_string.substr(0, lead_size);
847 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
851 open_braces = identifyClosing(par_as_string);
852 identifyClosing(par_as_string_nolead);
853 LYXERR(Debug::FIND, "Open braces: " << open_braces);
854 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
856 string lead_as_regexp;
858 // @todo No need to search for \regexp{} insets in leading material
859 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
860 par_as_string = par_as_string_nolead;
861 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
862 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
864 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
865 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
866 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
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 '\\\]' ('\]' has been escaped by escape_for_regex)
871 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
872 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
873 || regex_replace(par_as_string, par_as_string,
874 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
875 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
876 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
880 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
881 LYXERR(Debug::FIND, "Open braces: " << open_braces);
882 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
883 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
884 // If entered regexp must match at begin of searched string buffer
885 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
886 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
887 regexp = lyx::regex(regexp_str);
889 // If entered regexp may match wherever in searched string buffer
890 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
891 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
892 regexp2 = lyx::regex(regexp2_str);
897 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
899 docstring docstr = stringifyFromForSearch(opt, cur, len);
900 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
901 string str = normalize(docstr, true);
902 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
904 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
905 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='" << lead_as_string << "', par_as_string_nolead='" << par_as_string_nolead << "'");
907 LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
908 if (str.substr(0, par_as_string.size()) == par_as_string)
909 return par_as_string.size();
911 size_t pos = str.find(par_as_string_nolead);
912 if (pos != string::npos)
913 return par_as_string.size();
916 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
917 // Try all possible regexp matches,
918 //until one that verifies the braces match test is found
919 regex const *p_regexp = at_begin ? ®exp : ®exp2;
920 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
921 sregex_iterator re_it_end;
922 for (; re_it != re_it_end; ++re_it) {
923 match_results<string::const_iterator> const & m = *re_it;
924 // Check braces on the segment that matched the entire regexp expression,
925 // plus the last subexpression, if a (.*?) was inserted in the constructor.
926 if (!braces_match(m[0].first, m[0].second, open_braces))
928 // Check braces on segments that matched all (.*?) subexpressions,
929 // except the last "padding" one inserted by lyx.
930 for (size_t i = 1; i < m.size() - 1; ++i)
931 if (!braces_match(m[i].first, m[i].second))
933 // Exclude from the returned match length any length
934 // due to close wildcards added at end of regexp
935 if (close_wildcards == 0)
936 return m[0].second - m[0].first;
938 return m[m.size() - close_wildcards].first - m[0].first;
945 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
947 int res = findAux(cur, len, at_begin);
949 "res=" << res << ", at_begin=" << at_begin
950 << ", matchword=" << opt.matchword
951 << ", inTexted=" << cur.inTexted());
952 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
954 Paragraph const & par = cur.paragraph();
955 bool ws_left = (cur.pos() > 0)
956 ? par.isWordSeparator(cur.pos() - 1)
958 bool ws_right = (cur.pos() + res < par.size())
959 ? par.isWordSeparator(cur.pos() + res)
962 "cur.pos()=" << cur.pos() << ", res=" << res
963 << ", separ: " << ws_left << ", " << ws_right
965 if (ws_left && ws_right)
971 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
974 if (! opt.casesensitive)
975 t = lyx::to_utf8(lowercase(s));
978 // Remove \n at begin
979 while (!t.empty() && t[0] == '\n')
982 while (!t.empty() && t[t.size() - 1] == '\n')
983 t = t.substr(0, t.size() - 1);
985 // Replace all other \n with spaces
986 while ((pos = t.find("\n")) != string::npos)
987 t.replace(pos, 1, " ");
988 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
989 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
990 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
991 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
993 // FIXME - check what preceeds the brace
995 if (opt.ignoreformat)
996 while (regex_replace(t, t, "\\{", "_x_<")
997 || regex_replace(t, t, "\\}", "_x_>"))
998 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1000 while (regex_replace(t, t, "\\\\\\{", "_x_<")
1001 || regex_replace(t, t, "\\\\\\}", "_x_>"))
1002 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
1009 docstring stringifyFromCursor(DocIterator const & cur, int len)
1011 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
1012 if (cur.inTexted()) {
1013 Paragraph const & par = cur.paragraph();
1014 // TODO what about searching beyond/across paragraph breaks ?
1015 // TODO Try adding a AS_STR_INSERTS as last arg
1016 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
1017 int(par.size()) : cur.pos() + len;
1018 OutputParams runparams(&cur.buffer()->params().encoding());
1019 odocstringstream os;
1020 runparams.nice = true;
1021 runparams.flavor = OutputParams::LATEX;
1022 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
1023 // No side effect of file copying and image conversion
1024 runparams.dryrun = true;
1025 LYXERR(Debug::FIND, "Stringifying with cur: "
1026 << cur << ", from pos: " << cur.pos() << ", end: " << end);
1027 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
1028 } else if (cur.inMathed()) {
1030 CursorSlice cs = cur.top();
1031 MathData md = cs.cell();
1032 MathData::const_iterator it_end =
1033 (( len == -1 || cs.pos() + len > int(md.size()))
1035 : md.begin() + cs.pos() + len );
1036 for (MathData::const_iterator it = md.begin() + cs.pos();
1038 s = s + asString(*it);
1039 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
1042 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1047 /** Computes the LaTeX export of buf starting from cur and ending len positions
1048 * after cur, if len is positive, or at the paragraph or innermost inset end
1051 docstring latexifyFromCursor(DocIterator const & cur, int len)
1053 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
1054 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
1055 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
1056 Buffer const & buf = *cur.buffer();
1057 LASSERT(buf.params().isLatex(), /* */);
1060 odocstringstream ods;
1061 otexstream os(ods, texrow);
1062 OutputParams runparams(&buf.params().encoding());
1063 runparams.nice = false;
1064 runparams.flavor = OutputParams::LATEX;
1065 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1066 // No side effect of file copying and image conversion
1067 runparams.dryrun = true;
1069 if (cur.inTexted()) {
1070 // @TODO what about searching beyond/across paragraph breaks ?
1071 pos_type endpos = cur.paragraph().size();
1072 if (len != -1 && endpos > cur.pos() + len)
1073 endpos = cur.pos() + len;
1074 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1075 string(), cur.pos(), endpos);
1076 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1077 } else if (cur.inMathed()) {
1078 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1079 for (int s = cur.depth() - 1; s >= 0; --s) {
1080 CursorSlice const & cs = cur[s];
1081 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1082 WriteStream ws(ods);
1083 cs.asInsetMath()->asHullInset()->header_write(ws);
1088 CursorSlice const & cs = cur.top();
1089 MathData md = cs.cell();
1090 MathData::const_iterator it_end =
1091 ((len == -1 || cs.pos() + len > int(md.size()))
1093 : md.begin() + cs.pos() + len);
1094 for (MathData::const_iterator it = md.begin() + cs.pos();
1096 ods << asString(*it);
1098 // Retrieve the math environment type, and add '$' or '$]'
1099 // or others (\end{equation}) accordingly
1100 for (int s = cur.depth() - 1; s >= 0; --s) {
1101 CursorSlice const & cs = cur[s];
1102 InsetMath * inset = cs.asInsetMath();
1103 if (inset && inset->asHullInset()) {
1104 WriteStream ws(ods);
1105 inset->asHullInset()->footer_write(ws);
1109 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1111 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1117 /** Finalize an advanced find operation, advancing the cursor to the innermost
1118 ** position that matches, plus computing the length of the matching text to
1121 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1123 // Search the foremost position that matches (avoids find of entire math
1124 // inset when match at start of it)
1126 DocIterator old_cur(cur.buffer());
1128 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1132 } while (cur && cur.depth() > d && match(cur) > 0);
1134 LASSERT(match(cur) > 0, /* */);
1135 LYXERR(Debug::FIND, "Ok");
1137 // Compute the match length
1139 if (cur.pos() + len > cur.lastpos())
1141 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1142 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1144 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1146 // Length of matched text (different from len param)
1147 int old_len = match(cur, len);
1149 // Greedy behaviour while matching regexps
1150 while ((new_len = match(cur, len + 1)) > old_len) {
1153 LYXERR(Debug::FIND, "verifying match with len = " << len);
1160 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1164 while (!theApp()->longOperationCancelled() && cur) {
1165 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1166 int match_len = match(cur, -1, false);
1167 LYXERR(Debug::FIND, "match_len: " << match_len);
1169 for (; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
1170 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1171 int match_len = match(cur);
1172 LYXERR(Debug::FIND, "match_len: " << match_len);
1174 // Sometimes in finalize we understand it wasn't a match
1175 // and we need to continue the outest loop
1176 int len = findAdvFinalize(cur, match);
1184 if (cur.pit() < cur.lastpit()) {
1185 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1188 // This should exit nested insets, if any, or otherwise undefine the currsor.
1189 cur.pos() = cur.lastpos();
1190 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1198 /// Find the most backward consecutive match within same paragraph while searching backwards.
1199 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1201 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1202 DocIterator tmp_cur = cur;
1203 int len = findAdvFinalize(tmp_cur, match);
1204 Inset & inset = cur.inset();
1205 for (; cur != cur_begin; cur.backwardPos()) {
1206 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1207 DocIterator new_cur = cur;
1208 new_cur.backwardPos();
1209 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1211 int new_len = findAdvFinalize(new_cur, match);
1216 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1222 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
1226 // Backup of original position
1227 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1228 if (cur == cur_begin)
1231 DocIterator cur_orig(cur);
1233 bool pit_changed = false;
1234 found_match = false;
1237 found_match = match(cur, -1, false);
1241 cur.pos() = cur.lastpos();
1243 cur.pos() = cur_orig.pos();
1244 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1245 DocIterator cur_prev_iter;
1247 found_match = match(cur);
1248 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1249 << found_match << ", cur: " << cur);
1251 return findMostBackwards(cur, match);
1253 // Stop if begin of document reached
1254 if (cur == cur_begin)
1256 cur_prev_iter = cur;
1260 if (cur == cur_begin)
1267 } while (!theApp()->longOperationCancelled());
1272 } // anonym namespace
1275 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1276 DocIterator const & cur, int len)
1278 LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1279 if (!opt.ignoreformat)
1280 return latexifyFromCursor(cur, len);
1282 return stringifyFromCursor(cur, len);
1286 FindAndReplaceOptions::FindAndReplaceOptions(
1287 docstring const & find_buf_name, bool casesensitive,
1288 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1289 docstring const & repl_buf_name, bool keep_case,
1291 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1292 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1293 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1301 /** Check if 'len' letters following cursor are all non-lowercase */
1302 static bool allNonLowercase(DocIterator const & cur, int len)
1304 pos_type end_pos = cur.pos() + len;
1305 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1306 if (isLowerCase(cur.paragraph().getChar(pos)))
1312 /** Check if first letter is upper case and second one is lower case */
1313 static bool firstUppercase(DocIterator const & cur)
1316 if (cur.pos() >= cur.lastpos() - 1) {
1317 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1320 ch1 = cur.paragraph().getChar(cur.pos());
1321 ch2 = cur.paragraph().getChar(cur.pos()+1);
1322 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1323 LYXERR(Debug::FIND, "firstUppercase(): "
1324 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1325 << ch2 << "(" << char(ch2) << ")"
1326 << ", result=" << result << ", cur=" << cur);
1331 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1333 ** \fixme What to do with possible further paragraphs in replace buffer ?
1335 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
1337 ParagraphList::iterator pit = buffer.paragraphs().begin();
1338 pos_type right = pos_type(1);
1339 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1340 right = pit->size() + 1;
1341 pit->changeCase(buffer.params(), right, right, others_case);
1347 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1349 Cursor & cur = bv->cursor();
1350 if (opt.repl_buf_name == docstring())
1353 DocIterator sel_beg = cur.selectionBegin();
1354 DocIterator sel_end = cur.selectionEnd();
1355 if (&sel_beg.inset() != &sel_end.inset()
1356 || sel_beg.pit() != sel_end.pit())
1358 int sel_len = sel_end.pos() - sel_beg.pos();
1359 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1360 << ", sel_len: " << sel_len << endl);
1363 LASSERT(sel_len > 0, /**/);
1365 if (!matchAdv(sel_beg, sel_len))
1368 // Build a copy of the replace buffer, adapted to the KeepCase option
1369 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1371 repl_buffer_orig.write(oss);
1372 string lyx = oss.str();
1373 Buffer repl_buffer("", false);
1374 repl_buffer.setUnnamed(true);
1375 LASSERT(repl_buffer.readString(lyx), /**/);
1376 if (opt.keep_case && sel_len >= 2) {
1377 if (cur.inTexted()) {
1378 if (firstUppercase(cur))
1379 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1380 else if (allNonLowercase(cur, sel_len))
1381 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1384 cap::cutSelection(cur, false, false);
1385 if (cur.inTexted()) {
1386 repl_buffer.changeLanguage(
1387 repl_buffer.language(),
1388 cur.getFont().language());
1389 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1390 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1391 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1392 repl_buffer.params().documentClassPtr(),
1393 bv->buffer().errorList("Paste"));
1394 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1395 sel_len = repl_buffer.paragraphs().begin()->size();
1396 } else if (cur.inMathed()) {
1398 odocstringstream ods;
1399 otexstream os(ods, texrow);
1400 OutputParams runparams(&repl_buffer.params().encoding());
1401 runparams.nice = false;
1402 runparams.flavor = OutputParams::LATEX;
1403 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1404 runparams.dryrun = true;
1405 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1406 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1407 docstring repl_latex = ods.str();
1408 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1410 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1411 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1412 repl_latex = from_utf8(s);
1413 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
1414 MathData ar(cur.buffer());
1415 asArray(repl_latex, ar, Parse::NORMAL);
1417 sel_len = ar.size();
1418 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1420 if (cur.pos() >= sel_len)
1421 cur.pos() -= sel_len;
1424 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
1425 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1426 bv->processUpdateFlags(Update::Force);
1427 bv->buffer().updatePreviews();
1431 /// Perform a FindAdv operation.
1432 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1438 MatchStringAdv matchAdv(bv->buffer(), opt);
1439 findAdvReplace(bv, opt, matchAdv);
1442 match_len = findForwardAdv(cur, matchAdv);
1444 match_len = findBackwardsAdv(cur, matchAdv);
1446 // This may only be raised by lyx::regex()
1447 bv->message(_("Invalid regular expression!"));
1451 if (match_len == 0) {
1452 bv->message(_("Match not found!"));
1456 bv->message(_("Match found!"));
1458 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1459 bv->putSelectionAt(cur, match_len, !opt.forward);
1465 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1467 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1468 << opt.casesensitive << ' '
1469 << opt.matchword << ' '
1470 << opt.forward << ' '
1471 << opt.expandmacros << ' '
1472 << opt.ignoreformat << ' '
1473 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1474 << opt.keep_case << ' '
1477 LYXERR(Debug::FIND, "built: " << os.str());
1483 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1485 LYXERR(Debug::FIND, "parsing");
1489 while (line != "EOSS") {
1493 if (is.eof()) // Tolerate malformed request
1497 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1498 opt.find_buf_name = from_utf8(s);
1499 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1500 is.get(); // Waste space before replace string
1503 while (line != "EOSS") {
1507 if (is.eof()) // Tolerate malformed request
1511 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1512 opt.repl_buf_name = from_utf8(s);
1513 is >> opt.keep_case;
1516 opt.scope = FindAndReplaceOptions::SearchScope(i);
1517 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1518 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);