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 ? findForward(cur, match, find_del) :
162 findBackwards(cur, match, find_del);
165 bv->putSelectionAt(cur, match_len, !forward);
167 return match_len > 0;
171 int replaceAll(BufferView * bv,
172 docstring const & searchstr, docstring const & replacestr,
173 bool case_sens, bool whole)
175 Buffer & buf = bv->buffer();
177 if (!searchAllowed(searchstr) || buf.isReadonly())
180 DocIterator cur_orig(bv->cursor());
182 MatchString const match(searchstr, case_sens, whole);
185 int const rsize = replacestr.size();
186 int const ssize = searchstr.size();
189 cur.setCursor(doc_iterator_begin(&buf));
190 int match_len = findForward(cur, match, false);
191 while (match_len > 0) {
192 // Backup current cursor position and font.
193 pos_type const pos = cur.pos();
194 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
196 int striked = ssize - cur.paragraph().eraseChars(pos, pos + match_len,
197 buf.params().trackChanges);
198 cur.paragraph().insert(pos, replacestr, font,
199 Change(buf.params().trackChanges ?
200 Change::INSERTED : Change::UNCHANGED));
201 for (int i = 0; i < rsize + striked; ++i)
204 match_len = findForward(cur, match, false);
207 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
209 cur_orig.fixIfBroken();
210 bv->setCursor(cur_orig);
216 // the idea here is that we are going to replace the string that
217 // is selected IF it is the search string.
218 // if there is a selection, but it is not the search string, then
219 // we basically ignore it. (FIXME We ought to replace only within
221 // if there is no selection, then:
222 // (i) if some search string has been provided, then we find it.
223 // (think of how the dialog works when you hit "replace" the
225 // (ii) if no search string has been provided, then we treat the
226 // word the cursor is in as the search string. (why? i have no
227 // idea.) but this only works in text?
229 // returns the number of replacements made (one, if any) and
230 // whether anything at all was done.
231 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
232 docstring const & replacestr, bool case_sens,
233 bool whole, bool forward, bool findnext)
235 Cursor & cur = bv->cursor();
236 if (!cur.selection()) {
237 // no selection, non-empty search string: find it
238 if (!searchstr.empty()) {
239 findOne(bv, searchstr, case_sens, whole, forward);
240 return pair<bool, int>(true, 0);
242 // empty search string
245 return pair<bool, int>(false, 0);
246 // select current word and treat it as the search string
247 cur.innerText()->selectWord(cur, WHOLE_WORD);
248 searchstr = cur.selectionAsString(false);
251 // if we still don't have a search string, report the error
253 if (!searchAllowed(searchstr))
254 return pair<bool, int>(false, 0);
256 bool have_selection = cur.selection();
257 docstring const selected = cur.selectionAsString(false);
259 case_sens ? searchstr == selected
260 : compare_no_case(searchstr, selected) == 0;
262 // no selection or current selection is not search word:
263 // just find the search word
264 if (!have_selection || !match) {
265 findOne(bv, searchstr, case_sens, whole, forward);
266 return pair<bool, int>(true, 0);
269 // we're now actually ready to replace. if the buffer is
270 // read-only, we can't, though.
271 if (bv->buffer().isReadonly())
272 return pair<bool, int>(false, 0);
274 cap::replaceSelectionWithString(cur, replacestr, forward);
276 cur.pos() += replacestr.length();
277 LASSERT(cur.pos() <= cur.lastpos(), /* */);
279 cur.pos() -= replacestr.length();
280 LASSERT(cur.pos() >= 0, /* */);
283 findOne(bv, searchstr, case_sens, whole, forward, false);
285 return pair<bool, int>(true, 1);
291 docstring const find2string(docstring const & search,
292 bool casesensitive, bool matchword, bool forward)
296 << int(casesensitive) << ' '
297 << int(matchword) << ' '
303 docstring const replace2string(docstring const & replace,
304 docstring const & search, bool casesensitive, bool matchword,
305 bool all, bool forward, bool findnext)
308 ss << replace << '\n'
310 << int(casesensitive) << ' '
311 << int(matchword) << ' '
313 << int(forward) << ' '
319 bool lyxfind(BufferView * bv, FuncRequest const & ev)
321 if (!bv || ev.action() != LFUN_WORD_FIND)
324 //lyxerr << "find called, cmd: " << ev << endl;
326 // data is of the form
328 // <casesensitive> <matchword> <forward>"
330 docstring howto = split(ev.argument(), search, '\n');
332 bool casesensitive = parse_bool(howto);
333 bool matchword = parse_bool(howto);
334 bool forward = parse_bool(howto);
336 return findOne(bv, search, casesensitive, matchword, forward);
340 bool lyxreplace(BufferView * bv,
341 FuncRequest const & ev, bool has_deleted)
343 if (!bv || ev.action() != LFUN_WORD_REPLACE)
346 // data is of the form
349 // <casesensitive> <matchword> <all> <forward> <findnext>"
352 docstring howto = split(ev.argument(), rplc, '\n');
353 howto = split(howto, search, '\n');
355 bool casesensitive = parse_bool(howto);
356 bool matchword = parse_bool(howto);
357 bool all = parse_bool(howto);
358 bool forward = parse_bool(howto);
359 bool findnext = howto.empty() ? true : parse_bool(howto);
361 int replace_count = 0;
366 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
367 update = replace_count > 0;
370 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
372 replace_count = rv.second;
375 Buffer const & buf = bv->buffer();
377 // emit message signal.
378 buf.message(_("String not found!"));
380 if (replace_count == 0) {
381 buf.message(_("String found."));
382 } else if (replace_count == 1) {
383 buf.message(_("String has been replaced."));
385 docstring const str =
386 bformat(_("%1$d strings have been replaced."), replace_count);
390 } else if (findnext) {
391 // if we have deleted characters, we do not replace at all, but
392 // rather search for the next occurence
393 if (findOne(bv, search, casesensitive, matchword, forward))
396 bv->message(_("String not found!"));
402 bool findNextChange(BufferView * bv)
404 return findChange(bv, true);
408 bool findPreviousChange(BufferView * bv)
410 return findChange(bv, false);
414 bool findChange(BufferView * bv, bool next)
416 if (bv->cursor().selection()) {
417 // set the cursor at the beginning or at the end of the selection
418 // before searching. Otherwise, the current change will be found.
419 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
420 bv->cursor().setCursorToAnchor();
423 DocIterator cur = bv->cursor();
425 // Are we within a change ? Then first search forward (backward),
426 // clear the selection and search the other way around (see the end
427 // of this function). This will avoid changes to be selected half.
428 bool search_both_sides = false;
429 DocIterator tmpcur = cur;
431 while (tmpcur.inMathed())
433 Change change_next_pos
434 = tmpcur.paragraph().lookupChange(tmpcur.pos());
435 if (change_next_pos.changed() && cur.inMathed()) {
437 search_both_sides = true;
438 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
439 Change change_prev_pos
440 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
441 if (change_next_pos.isSimilarTo(change_prev_pos))
442 search_both_sides = true;
445 if (!findChange(cur, next))
448 bv->cursor().setCursor(cur);
449 bv->cursor().resetAnchor();
452 // take a step into the change
455 Change orig_change = cur.paragraph().lookupChange(cur.pos());
457 CursorSlice & tip = cur.top();
459 for (; !tip.at_end(); tip.forwardPos()) {
460 Change change = tip.paragraph().lookupChange(tip.pos());
461 if (!change.isSimilarTo(orig_change))
465 for (; !tip.at_begin();) {
467 Change change = tip.paragraph().lookupChange(tip.pos());
468 if (!change.isSimilarTo(orig_change)) {
469 // take a step forward to correctly set the selection
476 // Now put cursor to end of selection:
477 bv->cursor().setCursor(cur);
478 bv->cursor().setSelection();
480 if (search_both_sides) {
481 bv->cursor().setSelection(false);
482 findChange(bv, !next);
490 typedef vector<pair<string, string> > Escapes;
492 /// A map of symbols and their escaped equivalent needed within a regex.
493 Escapes const & get_regexp_escapes()
495 static Escapes escape_map;
496 if (escape_map.empty()) {
497 escape_map.push_back(pair<string, string>("\\", "\\\\"));
498 escape_map.push_back(pair<string, string>("^", "\\^"));
499 escape_map.push_back(pair<string, string>("$", "\\$"));
500 escape_map.push_back(pair<string, string>("{", "\\{"));
501 escape_map.push_back(pair<string, string>("}", "\\}"));
502 escape_map.push_back(pair<string, string>("[", "\\["));
503 escape_map.push_back(pair<string, string>("]", "\\]"));
504 escape_map.push_back(pair<string, string>("(", "\\("));
505 escape_map.push_back(pair<string, string>(")", "\\)"));
506 escape_map.push_back(pair<string, string>("+", "\\+"));
507 escape_map.push_back(pair<string, string>("*", "\\*"));
508 escape_map.push_back(pair<string, string>(".", "\\."));
513 /// A map of lyx escaped strings and their unescaped equivalent.
514 Escapes const & get_lyx_unescapes() {
515 static Escapes escape_map;
516 if (escape_map.empty()) {
517 escape_map.push_back(pair<string, string>("{*}", "*"));
518 escape_map.push_back(pair<string, string>("{[}", "["));
519 escape_map.push_back(pair<string, string>("\\$", "$"));
520 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
521 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
522 escape_map.push_back(pair<string, string>("\\sim ", "~"));
523 escape_map.push_back(pair<string, string>("\\^", "^"));
528 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
529 ** the found occurrence were escaped.
531 string apply_escapes(string s, Escapes const & escape_map)
533 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
534 Escapes::const_iterator it;
535 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
536 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
537 unsigned int pos = 0;
538 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
539 s.replace(pos, it->first.length(), it->second);
540 // LYXERR(Debug::FIND, "After escape: " << s);
541 pos += it->second.length();
542 // LYXERR(Debug::FIND, "pos: " << pos);
545 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
549 /** Return the position of the closing brace matching the open one at s[pos],
550 ** or s.size() if not found.
552 size_t find_matching_brace(string const & s, size_t pos)
554 LASSERT(s[pos] == '{', /* */);
556 for (++pos; pos < s.size(); ++pos) {
559 else if (s[pos] == '{')
561 else if (s[pos] == '}') {
563 if (open_braces == 0)
570 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
571 string escape_for_regex(string s)
574 while (pos < s.size()) {
575 size_t new_pos = s.find("\\regexp{{{", pos);
576 if (new_pos == string::npos)
578 LYXERR(Debug::FIND, "new_pos: " << new_pos);
579 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
580 LYXERR(Debug::FIND, "t : " << t);
581 t = apply_escapes(t, get_regexp_escapes());
582 LYXERR(Debug::FIND, "t : " << t);
583 s.replace(pos, new_pos - pos, t);
584 new_pos = pos + t.size();
585 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
586 LYXERR(Debug::FIND, "new_pos: " << new_pos);
587 if (new_pos == s.size())
589 size_t end_pos = s.find("}}}", new_pos + 10); // find_matching_brace(s, new_pos + 7);
590 LYXERR(Debug::FIND, "end_pos: " << end_pos);
591 t = apply_escapes(s.substr(new_pos + 10, end_pos - (new_pos + 10)), get_lyx_unescapes());
592 LYXERR(Debug::FIND, "t : " << t);
593 if (end_pos == s.size()) {
594 s.replace(new_pos, end_pos - new_pos, t);
596 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
599 s.replace(new_pos, end_pos + 3 - new_pos, t);
600 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
601 pos = new_pos + t.size();
602 LYXERR(Debug::FIND, "pos: " << pos);
607 /// Wrapper for lyx::regex_replace with simpler interface
608 bool regex_replace(string const & s, string & t, string const & searchstr,
609 string const & replacestr)
611 lyx::regex e(searchstr);
613 ostream_iterator<char, char> it(oss);
614 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
615 // tolerate t and s be references to the same variable
616 bool rv = (s != oss.str());
621 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
623 ** Verify that closed braces exactly match open braces. This avoids that, for example,
624 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
627 ** Number of open braces that must remain open at the end for the verification to succeed.
629 bool braces_match(string::const_iterator const & beg,
630 string::const_iterator const & end,
634 string::const_iterator it = beg;
635 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
636 for (; it != end; ++it) {
637 // Skip escaped braces in the count
642 } else if (*it == '{') {
644 } else if (*it == '}') {
645 if (open_pars == 0) {
646 LYXERR(Debug::FIND, "Found unmatched closed brace");
652 if (open_pars != unmatched) {
653 LYXERR(Debug::FIND, "Found " << open_pars
654 << " instead of " << unmatched
655 << " unmatched open braces at the end of count");
658 LYXERR(Debug::FIND, "Braces match as expected");
662 /** The class performing a match between a position in the document and the FindAdvOptions.
664 class MatchStringAdv {
666 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
668 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
669 ** constructor as opt.search, under the opt.* options settings.
672 ** If set, then match is searched only against beginning of text starting at cur.
673 ** If unset, then match is searched anywhere in text starting at cur.
676 ** The length of the matching text, or zero if no match was found.
678 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
683 /// first buffer on which search was started
684 lyx::Buffer * const p_first_buf;
686 FindAndReplaceOptions const & opt;
689 /// Auxiliary find method (does not account for opt.matchword)
690 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
692 /** Normalize a stringified or latexified LyX paragraph.
696 ** <li>if search is not casesensitive, then lowercase the string;
697 ** <li>remove any newline at begin or end of the string;
698 ** <li>replace any newline in the middle of the string with a simple space;
699 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
702 ** @todo Normalization should also expand macros, if the corresponding
703 ** search option was checked.
705 string normalize(docstring const & s) const;
706 // normalized string to search
707 string par_as_string;
708 // regular expression to use for searching
710 // same as regexp, but prefixed with a ".*"
712 // unmatched open braces in the search string/regexp
714 // number of (.*?) subexpressions added at end of search regexp for closing
715 // environments, math mode, styles, etc...
717 // Are we searching with regular expressions ?
722 static docstring buffer_to_latex(Buffer & buffer)
724 OutputParams runparams(&buffer.params().encoding());
726 odocstringstream ods;
727 otexstream os(ods, texrow);
728 runparams.nice = true;
729 runparams.flavor = OutputParams::LATEX;
730 runparams.linelen = 80; //lyxrc.plaintext_linelen;
731 // No side effect of file copying and image conversion
732 runparams.dryrun = true;
733 pit_type const endpit = buffer.paragraphs().size();
734 for (pit_type pit = 0; pit != endpit; ++pit) {
735 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
736 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
742 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt) {
744 if (!opt.ignoreformat) {
745 str = buffer_to_latex(buffer);
747 OutputParams runparams(&buffer.params().encoding());
748 runparams.nice = true;
749 runparams.flavor = OutputParams::LATEX;
750 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
751 runparams.dryrun = true;
752 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
753 Paragraph const & par = buffer.paragraphs().at(pit);
754 LYXERR(Debug::FIND, "Adding to search string: '"
755 << par.stringify(pos_type(0), par.size(),
756 AS_STR_INSETS, runparams)
758 str += par.stringify(pos_type(0), par.size(),
759 AS_STR_INSETS, runparams);
766 /// Return separation pos between the leading material and the rest
767 static size_t identifyLeading(string const & s) {
769 // @TODO Support \item[text]
770 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\*?\\{", "")
771 || regex_replace(t, t, "^\\$", "")
772 || regex_replace(t, t, "^\\\\\\[ ", "")
773 || regex_replace(t, t, "^\\\\item ", "")
774 || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
775 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
780 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
781 : p_buf(&buf), p_first_buf(&buf), opt(opt)
783 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
784 par_as_string = normalize(stringifySearchBuffer(find_buf, opt));
788 use_regexp = !opt.ignoreformat || par_as_string.find("\\regexp") != std::string::npos;
791 // Remove trailing closure of math, macros and environments, so to catch parts of them.
793 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
794 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\])\\$\\'", "$1"))
796 // @todo need to account for open square braces as well ?
797 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) \\\\\\]\\'", "$1"))
799 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}\\'", "$1"))
801 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\])\\}\\'", "$1")) {
807 LYXERR(Debug::FIND, "Open braces: " << open_braces);
808 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
810 size_t lead_size = identifyLeading(par_as_string);
811 string lead_as_regexp;
813 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size));
814 par_as_string = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
815 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
816 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
818 par_as_string = escape_for_regex(par_as_string);
819 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
820 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
822 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
823 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
824 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
825 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
826 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
827 || regex_replace(par_as_string, par_as_string,
828 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
829 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
830 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
834 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
835 LYXERR(Debug::FIND, "Open braces: " << open_braces);
836 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
837 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
838 // If entered regexp must match at begin of searched string buffer
839 string regexp_str = string("\\`") + lead_as_regexp + par_as_string;
840 LYXERR(Debug::FIND, "Setting regexp to : " << regexp_str << endl);
841 regexp = lyx::regex(regexp_str);
843 // If entered regexp may match wherever in searched string buffer
844 string regexp2_str = string("\\`.*") + lead_as_regexp + ".*" + par_as_string;
845 LYXERR(Debug::FIND, "Setting regexp2 to: " << regexp2_str << endl);
846 regexp2 = lyx::regex(regexp2_str);
851 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
853 docstring docstr = stringifyFromForSearch(opt, cur, len);
854 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
855 string str = normalize(docstr);
856 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
858 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
860 LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
861 if (str.substr(0, par_as_string.size()) == par_as_string)
862 return par_as_string.size();
864 string t = par_as_string;
865 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\{", "")
866 || regex_replace(t, t, "^\\$", "")
867 || regex_replace(t, t, "^\\\\\\[ ", ""))
868 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: " << t);
869 size_t pos = str.find(t);
870 if (pos != string::npos)
871 return par_as_string.size();
874 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
875 // Try all possible regexp matches,
876 //until one that verifies the braces match test is found
877 regex const *p_regexp = at_begin ? ®exp : ®exp2;
878 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
879 sregex_iterator re_it_end;
880 for (; re_it != re_it_end; ++re_it) {
881 match_results<string::const_iterator> const & m = *re_it;
882 // Check braces on the segment that matched the entire regexp expression,
883 // plus the last subexpression, if a (.*?) was inserted in the constructor.
884 if (!braces_match(m[0].first, m[0].second, open_braces))
886 // Check braces on segments that matched all (.*?) subexpressions,
887 // except the last "padding" one inserted by lyx.
888 for (size_t i = 1; i < m.size() - 1; ++i)
889 if (!braces_match(m[i].first, m[i].second))
891 // Exclude from the returned match length any length
892 // due to close wildcards added at end of regexp
893 if (close_wildcards == 0)
894 return m[0].second - m[0].first;
896 return m[m.size() - close_wildcards].first - m[0].first;
903 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
905 int res = findAux(cur, len, at_begin);
907 "res=" << res << ", at_begin=" << at_begin << ", matchword=" << opt.matchword << ", inTexted=" << cur.inTexted());
908 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
910 Paragraph const & par = cur.paragraph();
911 bool ws_left = cur.pos() > 0 ?
912 par.isWordSeparator(cur.pos() - 1) : true;
913 bool ws_right = cur.pos() + res < par.size() ?
914 par.isWordSeparator(cur.pos() + res) : true;
916 "cur.pos()=" << cur.pos() << ", res=" << res
917 << ", separ: " << ws_left << ", " << ws_right
919 if (ws_left && ws_right)
925 string MatchStringAdv::normalize(docstring const & s) const
928 if (! opt.casesensitive)
929 t = lyx::to_utf8(lowercase(s));
932 // Remove \n at begin
933 while (t.size() > 0 && t[0] == '\n')
936 while (t.size() > 0 && t[t.size() - 1] == '\n')
937 t = t.substr(0, t.size() - 1);
939 // Replace all other \n with spaces
940 while ((pos = t.find("\n")) != string::npos)
941 t.replace(pos, 1, " ");
942 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
943 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
944 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
945 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
950 docstring stringifyFromCursor(DocIterator const & cur, int len)
952 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
953 if (cur.inTexted()) {
954 Paragraph const & par = cur.paragraph();
955 // TODO what about searching beyond/across paragraph breaks ?
956 // TODO Try adding a AS_STR_INSERTS as last arg
957 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
958 int(par.size()) : cur.pos() + len;
959 OutputParams runparams(&cur.buffer()->params().encoding());
961 runparams.nice = true;
962 runparams.flavor = OutputParams::LATEX;
963 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
964 // No side effect of file copying and image conversion
965 runparams.dryrun = true;
966 LYXERR(Debug::FIND, "Stringifying with cur: "
967 << cur << ", from pos: " << cur.pos() << ", end: " << end);
968 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
969 } else if (cur.inMathed()) {
971 CursorSlice cs = cur.top();
972 MathData md = cs.cell();
973 MathData::const_iterator it_end =
974 ( ( len == -1 || cs.pos() + len > int(md.size()) )
975 ? md.end() : md.begin() + cs.pos() + len );
976 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
977 s = s + asString(*it);
978 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
981 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
986 /** Computes the LaTeX export of buf starting from cur and ending len positions
987 * after cur, if len is positive, or at the paragraph or innermost inset end
990 docstring latexifyFromCursor(DocIterator const & cur, int len)
992 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
993 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
994 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
995 Buffer const & buf = *cur.buffer();
996 LASSERT(buf.params().isLatex(), /* */);
999 odocstringstream ods;
1000 otexstream os(ods, texrow);
1001 OutputParams runparams(&buf.params().encoding());
1002 runparams.nice = false;
1003 runparams.flavor = OutputParams::LATEX;
1004 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1005 // No side effect of file copying and image conversion
1006 runparams.dryrun = true;
1008 if (cur.inTexted()) {
1009 // @TODO what about searching beyond/across paragraph breaks ?
1010 pos_type endpos = cur.paragraph().size();
1011 if (len != -1 && endpos > cur.pos() + len)
1012 endpos = cur.pos() + len;
1013 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
1014 string(), cur.pos(), endpos);
1015 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
1016 } else if (cur.inMathed()) {
1017 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
1018 for (int s = cur.depth() - 1; s >= 0; --s) {
1019 CursorSlice const & cs = cur[s];
1020 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
1021 WriteStream ws(ods);
1022 cs.asInsetMath()->asHullInset()->header_write(ws);
1027 CursorSlice const & cs = cur.top();
1028 MathData md = cs.cell();
1029 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
1030 ? md.end() : md.begin() + cs.pos() + len );
1031 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
1032 ods << asString(*it);
1034 // Retrieve the math environment type, and add '$' or '$]'
1035 // or others (\end{equation}) accordingly
1036 for (int s = cur.depth() - 1; s >= 0; --s) {
1037 CursorSlice const & cs = cur[s];
1038 InsetMath * inset = cs.asInsetMath();
1039 if (inset && inset->asHullInset()) {
1040 WriteStream ws(ods);
1041 inset->asHullInset()->footer_write(ws);
1045 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
1047 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
1053 /** Finalize an advanced find operation, advancing the cursor to the innermost
1054 ** position that matches, plus computing the length of the matching text to
1057 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
1059 // Search the foremost position that matches (avoids find of entire math
1060 // inset when match at start of it)
1062 DocIterator old_cur(cur.buffer());
1064 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
1068 } while (cur && cur.depth() > d && match(cur) > 0);
1070 LASSERT(match(cur) > 0, /* */);
1071 LYXERR(Debug::FIND, "Ok");
1073 // Compute the match length
1075 if (cur.pos() + len > cur.lastpos())
1077 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1078 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
1080 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
1082 // Length of matched text (different from len param)
1083 int old_len = match(cur, len);
1085 // Greedy behaviour while matching regexps
1086 while ((new_len = match(cur, len + 1)) > old_len) {
1089 LYXERR(Debug::FIND, "verifying match with len = " << len);
1096 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1101 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
1102 int match_len = match(cur, -1, false);
1103 LYXERR(Debug::FIND, "match_len: " << match_len);
1105 for (; cur; cur.forwardPos()) {
1106 LYXERR(Debug::FIND, "Advancing cur: " << cur);
1107 int match_len = match(cur);
1108 LYXERR(Debug::FIND, "match_len: " << match_len);
1110 // Sometimes in finalize we understand it wasn't a match
1111 // and we need to continue the outest loop
1112 int len = findAdvFinalize(cur, match);
1120 if (cur.pit() < cur.lastpit()) {
1121 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
1124 // This should exit nested insets, if any, or otherwise undefine the currsor.
1125 cur.pos() = cur.lastpos();
1126 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
1134 /// Find the most backward consecutive match within same paragraph while searching backwards.
1135 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1137 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1138 DocIterator tmp_cur = cur;
1139 int len = findAdvFinalize(tmp_cur, match);
1140 Inset & inset = cur.inset();
1141 for (; cur != cur_begin; cur.backwardPos()) {
1142 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1143 DocIterator new_cur = cur;
1144 new_cur.backwardPos();
1145 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1147 int new_len = findAdvFinalize(new_cur, match);
1152 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1158 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1161 // Backup of original position
1162 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1163 if (cur == cur_begin)
1166 DocIterator cur_orig(cur);
1168 bool pit_changed = false;
1169 found_match = false;
1172 found_match = match(cur, -1, false);
1176 cur.pos() = cur.lastpos();
1178 cur.pos() = cur_orig.pos();
1179 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1180 DocIterator cur_prev_iter;
1182 found_match = match(cur);
1183 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1184 << found_match << ", cur: " << cur);
1186 return findMostBackwards(cur, match);
1188 // Stop if begin of document reached
1189 if (cur == cur_begin)
1191 cur_prev_iter = cur;
1195 if (cur == cur_begin)
1207 } // anonym namespace
1210 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1211 DocIterator const & cur, int len)
1213 LASSERT(cur.pos() >= 0 && cur.pos() <= cur.lastpos(), /* */);
1214 if (!opt.ignoreformat)
1215 return latexifyFromCursor(cur, len);
1217 return stringifyFromCursor(cur, len);
1221 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & find_buf_name, bool casesensitive,
1222 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1223 docstring const & repl_buf_name, bool keep_case,
1225 : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
1226 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1227 repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope)
1235 /** Check if 'len' letters following cursor are all non-lowercase */
1236 static bool allNonLowercase(DocIterator const & cur, int len) {
1237 pos_type end_pos = cur.pos() + len;
1238 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1239 if (isLowerCase(cur.paragraph().getChar(pos)))
1245 /** Check if first letter is upper case and second one is lower case */
1246 static bool firstUppercase(DocIterator const & cur) {
1248 if (cur.pos() >= cur.lastpos() - 1) {
1249 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1252 ch1 = cur.paragraph().getChar(cur.pos());
1253 ch2 = cur.paragraph().getChar(cur.pos()+1);
1254 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1255 LYXERR(Debug::FIND, "firstUppercase(): "
1256 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1257 << ch2 << "(" << char(ch2) << ")"
1258 << ", result=" << result << ", cur=" << cur);
1263 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1265 ** \fixme What to do with possible further paragraphs in replace buffer ?
1267 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1268 ParagraphList::iterator pit = buffer.paragraphs().begin();
1269 pos_type right = pos_type(1);
1270 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1271 right = pit->size() + 1;
1272 pit->changeCase(buffer.params(), right, right, others_case);
1277 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1279 Cursor & cur = bv->cursor();
1280 if (opt.repl_buf_name == docstring())
1283 DocIterator sel_beg = cur.selectionBegin();
1284 DocIterator sel_end = cur.selectionEnd();
1285 if (&sel_beg.inset() != &sel_end.inset()
1286 || sel_beg.pit() != sel_end.pit())
1288 int sel_len = sel_end.pos() - sel_beg.pos();
1289 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1290 << ", sel_len: " << sel_len << endl);
1293 LASSERT(sel_len > 0, /**/);
1295 if (!matchAdv(sel_beg, sel_len))
1298 // Build a copy of the replace buffer, adapted to the KeepCase option
1299 Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
1301 repl_buffer_orig.write(oss);
1302 string lyx = oss.str();
1303 Buffer repl_buffer("", false);
1304 repl_buffer.setUnnamed(true);
1305 LASSERT(repl_buffer.readString(lyx), /**/);
1306 if (opt.keep_case && sel_len >= 2) {
1307 if (cur.inTexted()) {
1308 if (firstUppercase(cur))
1309 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1310 else if (allNonLowercase(cur, sel_len))
1311 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1314 cap::cutSelection(cur, false, false);
1315 if (!cur.inMathed()) {
1316 repl_buffer.changeLanguage(
1317 repl_buffer.language(),
1318 cur.getFont().language());
1319 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1320 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
1321 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1322 repl_buffer.params().documentClassPtr(),
1323 bv->buffer().errorList("Paste"));
1324 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
1325 sel_len = repl_buffer.paragraphs().begin()->size();
1328 odocstringstream ods;
1329 otexstream os(ods, texrow);
1330 OutputParams runparams(&repl_buffer.params().encoding());
1331 runparams.nice = false;
1332 runparams.flavor = OutputParams::LATEX;
1333 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1334 runparams.dryrun = true;
1335 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
1336 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1337 docstring repl_latex = ods.str();
1338 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1340 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1341 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1342 repl_latex = from_utf8(s);
1343 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1344 sel_len = cur.niceInsert(repl_latex);
1346 if (cur.pos() >= sel_len)
1347 cur.pos() -= sel_len;
1350 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << sel_len);
1351 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
1352 bv->processUpdateFlags(Update::Force);
1353 bv->buffer().updatePreviews();
1357 /// Perform a FindAdv operation.
1358 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1364 MatchStringAdv matchAdv(bv->buffer(), opt);
1365 findAdvReplace(bv, opt, matchAdv);
1368 match_len = findForwardAdv(cur, matchAdv);
1370 match_len = findBackwardsAdv(cur, matchAdv);
1372 // This may only be raised by lyx::regex()
1373 bv->message(_("Invalid regular expression!"));
1377 if (match_len == 0) {
1378 bv->message(_("Match not found!"));
1382 bv->message(_("Match found!"));
1384 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1385 bv->putSelectionAt(cur, match_len, !opt.forward);
1391 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1393 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
1394 << opt.casesensitive << ' '
1395 << opt.matchword << ' '
1396 << opt.forward << ' '
1397 << opt.expandmacros << ' '
1398 << opt.ignoreformat << ' '
1399 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
1400 << opt.keep_case << ' '
1403 LYXERR(Debug::FIND, "built: " << os.str());
1409 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1411 LYXERR(Debug::FIND, "parsing");
1415 while (line != "EOSS") {
1419 if (is.eof()) // Tolerate malformed request
1423 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
1424 opt.find_buf_name = from_utf8(s);
1425 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat;
1426 is.get(); // Waste space before replace string
1429 while (line != "EOSS") {
1433 if (is.eof()) // Tolerate malformed request
1437 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
1438 opt.repl_buf_name = from_utf8(s);
1439 is >> opt.keep_case;
1442 opt.scope = FindAndReplaceOptions::SearchScope(i);
1443 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1444 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case);