3 * This file is part of LyX, the document processor.
4 * License details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
12 * Full author contact details are available in file CREDITS.
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "CutAndPaste.h"
27 #include "FuncRequest.h"
29 #include "output_latex.h"
30 #include "OutputParams.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
36 #include "frontends/alert.h"
38 #include "mathed/InsetMath.h"
39 #include "mathed/InsetMathGrid.h"
40 #include "mathed/InsetMathHull.h"
41 #include "mathed/MathStream.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
50 #include "support/regex.h"
51 #include <boost/next_prior.hpp>
54 using namespace lyx::support;
60 bool parse_bool(docstring & howto)
65 howto = split(howto, var, ' ');
70 class MatchString : public binary_function<Paragraph, pos_type, int>
73 MatchString(docstring const & str, bool cs, bool mw)
74 : str(str), case_sens(cs), whole_words(mw)
77 // returns true if the specified string is at the specified position
78 // del specifies whether deleted strings in ct mode will be considered
79 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
81 return par.find(str, case_sens, whole_words, pos, del);
89 // match whole words only
94 int findForward(DocIterator & cur, MatchString const & match,
97 for (; cur; cur.forwardChar())
99 int len = match(cur.paragraph(), cur.pos(), find_del);
107 int findBackwards(DocIterator & cur, MatchString const & match,
108 bool find_del = true)
112 if (cur.inTexted()) {
113 int len = match(cur.paragraph(), cur.pos(), find_del);
122 bool findChange(DocIterator & cur, bool next)
126 for (; cur; next ? cur.forwardPos() : cur.backwardPos())
127 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
129 // if we search backwards, take a step forward
130 // to correctly set the anchor
139 bool searchAllowed(docstring const & str)
142 frontend::Alert::error(_("Search error"), _("Search string is empty"));
149 bool findOne(BufferView * bv, docstring const & searchstr,
150 bool case_sens, bool whole, bool forward, bool find_del = true)
152 if (!searchAllowed(searchstr))
155 DocIterator cur = bv->cursor();
157 MatchString const match(searchstr, case_sens, whole);
159 int match_len = forward ? findForward(cur, match, find_del) :
160 findBackwards(cur, match, find_del);
163 bv->putSelectionAt(cur, match_len, !forward);
165 return match_len > 0;
169 int replaceAll(BufferView * bv,
170 docstring const & searchstr, docstring const & replacestr,
171 bool case_sens, bool whole)
173 Buffer & buf = bv->buffer();
175 if (!searchAllowed(searchstr) || buf.isReadonly())
178 DocIterator cur_orig(bv->cursor());
180 MatchString const match(searchstr, case_sens, whole);
183 int const rsize = replacestr.size();
184 int const ssize = searchstr.size();
187 cur.setCursor(doc_iterator_begin(&buf));
188 int match_len = findForward(cur, match, false);
189 while (match_len > 0) {
190 // Backup current cursor position and font.
191 pos_type const pos = cur.pos();
192 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
194 int striked = ssize - cur.paragraph().eraseChars(pos, pos + match_len,
195 buf.params().trackChanges);
196 cur.paragraph().insert(pos, replacestr, font,
197 Change(buf.params().trackChanges ?
198 Change::INSERTED : Change::UNCHANGED));
199 for (int i = 0; i < rsize + striked; ++i)
202 match_len = findForward(cur, match, false);
205 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)
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);
275 bv->buffer().markDirty();
276 findOne(bv, searchstr, case_sens, whole, forward, false);
278 return pair<bool, int>(true, 1);
284 docstring const find2string(docstring const & search,
285 bool casesensitive, bool matchword, bool forward)
289 << int(casesensitive) << ' '
290 << int(matchword) << ' '
296 docstring const replace2string(docstring const & replace,
297 docstring const & search, bool casesensitive, bool matchword,
298 bool all, bool forward)
301 ss << replace << '\n'
303 << int(casesensitive) << ' '
304 << int(matchword) << ' '
311 bool lyxfind(BufferView * bv, FuncRequest const & ev)
313 if (!bv || ev.action() != LFUN_WORD_FIND)
316 //lyxerr << "find called, cmd: " << ev << endl;
318 // data is of the form
320 // <casesensitive> <matchword> <forward>"
322 docstring howto = split(ev.argument(), search, '\n');
324 bool casesensitive = parse_bool(howto);
325 bool matchword = parse_bool(howto);
326 bool forward = parse_bool(howto);
328 return findOne(bv, search, casesensitive, matchword, forward);
332 bool lyxreplace(BufferView * bv,
333 FuncRequest const & ev, bool has_deleted)
335 if (!bv || ev.action() != LFUN_WORD_REPLACE)
338 // data is of the form
341 // <casesensitive> <matchword> <all> <forward>"
344 docstring howto = split(ev.argument(), rplc, '\n');
345 howto = split(howto, search, '\n');
347 bool casesensitive = parse_bool(howto);
348 bool matchword = parse_bool(howto);
349 bool all = parse_bool(howto);
350 bool forward = parse_bool(howto);
352 int replace_count = 0;
357 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
358 update = replace_count > 0;
361 replaceOne(bv, search, rplc, casesensitive, matchword, forward);
363 replace_count = rv.second;
366 Buffer const & buf = bv->buffer();
368 // emit message signal.
369 buf.message(_("String not found!"));
371 if (replace_count == 0) {
372 buf.message(_("String found."));
373 } else if (replace_count == 1) {
374 buf.message(_("String has been replaced."));
376 docstring const str =
377 bformat(_("%1$d strings have been replaced."), replace_count);
382 // if we have deleted characters, we do not replace at all, but
383 // rather search for the next occurence
384 if (findOne(bv, search, casesensitive, matchword, forward))
387 bv->message(_("String not found!"));
393 bool findNextChange(BufferView * bv)
395 return findChange(bv, true);
399 bool findPreviousChange(BufferView * bv)
401 return findChange(bv, false);
405 bool findChange(BufferView * bv, bool next)
407 if (bv->cursor().selection()) {
408 // set the cursor at the beginning or at the end of the selection
409 // before searching. Otherwise, the current change will be found.
410 if (next != (bv->cursor().top() > bv->cursor().normalAnchor()))
411 bv->cursor().setCursorToAnchor();
414 DocIterator cur = bv->cursor();
416 // Are we within a change ? Then first search forward (backward),
417 // clear the selection and search the other way around (see the end
418 // of this function). This will avoid changes to be selected half.
419 bool search_both_sides = false;
420 DocIterator tmpcur = cur;
422 while (tmpcur.inMathed())
424 Change change_next_pos
425 = tmpcur.paragraph().lookupChange(tmpcur.pos());
426 if (change_next_pos.changed() && cur.inMathed()) {
428 search_both_sides = true;
429 } else if (tmpcur.pos() > 0 && tmpcur.inTexted()) {
430 Change change_prev_pos
431 = tmpcur.paragraph().lookupChange(tmpcur.pos() - 1);
432 if (change_next_pos.isSimilarTo(change_prev_pos))
433 search_both_sides = true;
436 if (!findChange(cur, next))
439 bv->cursor().setCursor(cur);
440 bv->cursor().resetAnchor();
443 // take a step into the change
446 Change orig_change = cur.paragraph().lookupChange(cur.pos());
448 CursorSlice & tip = cur.top();
450 for (; !tip.at_end(); tip.forwardPos()) {
451 Change change = tip.paragraph().lookupChange(tip.pos());
452 if (!change.isSimilarTo(orig_change))
456 for (; !tip.at_begin();) {
458 Change change = tip.paragraph().lookupChange(tip.pos());
459 if (!change.isSimilarTo(orig_change)) {
460 // take a step forward to correctly set the selection
467 // Now put cursor to end of selection:
468 bv->cursor().setCursor(cur);
469 bv->cursor().setSelection();
471 if (search_both_sides) {
472 bv->cursor().setSelection(false);
473 findChange(bv, !next);
481 typedef vector<pair<string, string> > Escapes;
483 /// A map of symbols and their escaped equivalent needed within a regex.
484 Escapes const & get_regexp_escapes()
486 static Escapes escape_map;
487 if (escape_map.empty()) {
488 escape_map.push_back(pair<string, string>("\\", "\\\\"));
489 escape_map.push_back(pair<string, string>("^", "\\^"));
490 escape_map.push_back(pair<string, string>("$", "\\$"));
491 escape_map.push_back(pair<string, string>("{", "\\{"));
492 escape_map.push_back(pair<string, string>("}", "\\}"));
493 escape_map.push_back(pair<string, string>("[", "\\["));
494 escape_map.push_back(pair<string, string>("]", "\\]"));
495 escape_map.push_back(pair<string, string>("(", "\\("));
496 escape_map.push_back(pair<string, string>(")", "\\)"));
497 escape_map.push_back(pair<string, string>("+", "\\+"));
498 escape_map.push_back(pair<string, string>("*", "\\*"));
499 escape_map.push_back(pair<string, string>(".", "\\."));
504 /// A map of lyx escaped strings and their unescaped equivalent.
505 Escapes const & get_lyx_unescapes() {
506 static Escapes escape_map;
507 if (escape_map.empty()) {
508 escape_map.push_back(pair<string, string>("{*}", "*"));
509 escape_map.push_back(pair<string, string>("{[}", "["));
510 escape_map.push_back(pair<string, string>("\\$", "$"));
511 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
512 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
513 escape_map.push_back(pair<string, string>("\\sim ", "~"));
514 escape_map.push_back(pair<string, string>("\\^", "^"));
519 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
520 ** the found occurrence were escaped.
522 string apply_escapes(string s, Escapes const & escape_map)
524 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
525 Escapes::const_iterator it;
526 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
527 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
528 unsigned int pos = 0;
529 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
530 s.replace(pos, it->first.length(), it->second);
531 // LYXERR(Debug::FIND, "After escape: " << s);
532 pos += it->second.length();
533 // LYXERR(Debug::FIND, "pos: " << pos);
536 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
540 /** Return the position of the closing brace matching the open one at s[pos],
541 ** or s.size() if not found.
543 size_t find_matching_brace(string const & s, size_t pos)
545 LASSERT(s[pos] == '{', /* */);
547 for (++pos; pos < s.size(); ++pos) {
550 else if (s[pos] == '{')
552 else if (s[pos] == '}') {
554 if (open_braces == 0)
561 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
562 string escape_for_regex(string s)
565 while (pos < s.size()) {
566 size_t new_pos = s.find("\\regexp{{{", pos);
567 if (new_pos == string::npos)
569 LYXERR(Debug::FIND, "new_pos: " << new_pos);
570 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
571 LYXERR(Debug::FIND, "t : " << t);
572 t = apply_escapes(t, get_regexp_escapes());
573 LYXERR(Debug::FIND, "t : " << t);
574 s.replace(pos, new_pos - pos, t);
575 new_pos = pos + t.size();
576 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
577 LYXERR(Debug::FIND, "new_pos: " << new_pos);
578 if (new_pos == s.size())
580 size_t end_pos = s.find("}}}", new_pos + 10); // find_matching_brace(s, new_pos + 7);
581 LYXERR(Debug::FIND, "end_pos: " << end_pos);
582 t = apply_escapes(s.substr(new_pos + 10, end_pos - (new_pos + 10)), get_lyx_unescapes());
583 LYXERR(Debug::FIND, "t : " << t);
584 if (end_pos == s.size()) {
585 s.replace(new_pos, end_pos - new_pos, t);
587 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
590 s.replace(new_pos, end_pos + 3 - new_pos, t);
591 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
592 pos = new_pos + t.size();
593 LYXERR(Debug::FIND, "pos: " << pos);
598 /// Wrapper for lyx::regex_replace with simpler interface
599 bool regex_replace(string const & s, string & t, string const & searchstr,
600 string const & replacestr)
602 lyx::regex e(searchstr);
604 ostream_iterator<char, char> it(oss);
605 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
606 // tolerate t and s be references to the same variable
607 bool rv = (s != oss.str());
612 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
614 ** Verify that closed braces exactly match open braces. This avoids that, for example,
615 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
618 ** Number of open braces that must remain open at the end for the verification to succeed.
620 bool braces_match(string::const_iterator const & beg,
621 string::const_iterator const & end,
625 string::const_iterator it = beg;
626 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
627 for (; it != end; ++it) {
628 // Skip escaped braces in the count
633 } else if (*it == '{') {
635 } else if (*it == '}') {
636 if (open_pars == 0) {
637 LYXERR(Debug::FIND, "Found unmatched closed brace");
643 if (open_pars != unmatched) {
644 LYXERR(Debug::FIND, "Found " << open_pars
645 << " instead of " << unmatched
646 << " unmatched open braces at the end of count");
649 LYXERR(Debug::FIND, "Braces match as expected");
653 /** The class performing a match between a position in the document and the FindAdvOptions.
655 class MatchStringAdv {
657 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
659 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
660 ** constructor as opt.search, under the opt.* options settings.
663 ** If set, then match is searched only against beginning of text starting at cur.
664 ** If unset, then match is searched anywhere in text starting at cur.
667 ** The length of the matching text, or zero if no match was found.
669 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
674 /// first buffer on which search was started
675 lyx::Buffer * const p_first_buf;
677 FindAndReplaceOptions const & opt;
680 /// Auxiliary find method (does not account for opt.matchword)
681 int findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
683 /** Normalize a stringified or latexified LyX paragraph.
687 ** <li>if search is not casesensitive, then lowercase the string;
688 ** <li>remove any newline at begin or end of the string;
689 ** <li>replace any newline in the middle of the string with a simple space;
690 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
693 ** @todo Normalization should also expand macros, if the corresponding
694 ** search option was checked.
696 string normalize(docstring const & s) const;
697 // normalized string to search
698 string par_as_string;
699 // regular expression to use for searching
701 // same as regexp, but prefixed with a ".*"
703 // unmatched open braces in the search string/regexp
705 // number of (.*?) subexpressions added at end of search regexp for closing
706 // environments, math mode, styles, etc...
711 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
712 : p_buf(&buf), p_first_buf(&buf), opt(opt)
714 par_as_string = normalize(opt.search);
719 // Remove trailing closure of math, macros and environments, so to catch parts of them.
721 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
722 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
724 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
726 // @todo need to account for open square braces as well ?
727 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
729 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
731 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
737 LYXERR(Debug::FIND, "Open braces: " << open_braces);
738 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
740 par_as_string = escape_for_regex(par_as_string);
741 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
742 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
744 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
745 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
746 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
747 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
748 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
749 || regex_replace(par_as_string, par_as_string,
750 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
751 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
752 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
756 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
757 LYXERR(Debug::FIND, "Open braces: " << open_braces);
758 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
759 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
760 // If entered regexp must match at begin of searched string buffer
761 regexp = lyx::regex(string("\\`") + par_as_string);
762 // If entered regexp may match wherever in searched string buffer
763 regexp2 = lyx::regex(string("\\`.*") + par_as_string);
768 int MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
770 docstring docstr = stringifyFromForSearch(opt, cur, len);
771 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
772 string str = normalize(docstr);
773 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
775 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='" << par_as_string << "', str='" << str << "'");
777 LYXERR(Debug::FIND, "size=" << par_as_string.size() << ", substr='" << str.substr(0, par_as_string.size()) << "'");
778 if (str.substr(0, par_as_string.size()) == par_as_string)
779 return par_as_string.size();
781 string t = par_as_string;
782 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)\\{", "")
783 || regex_replace(t, t, "^\\$", "")
784 || regex_replace(t, t, "^\\\\\\[ ", ""))
785 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: " << t);
786 size_t pos = str.find(t);
787 if (pos != string::npos)
788 return par_as_string.size();
791 LYXERR(Debug::FIND, "Searching in regexp mode");
792 // Try all possible regexp matches,
793 //until one that verifies the braces match test is found
794 regex const *p_regexp = at_begin ? ®exp : ®exp2;
795 sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
796 sregex_iterator re_it_end;
797 for (; re_it != re_it_end; ++re_it) {
798 match_results<string::const_iterator> const & m = *re_it;
799 // Check braces on the segment that matched the entire regexp expression,
800 // plus the last subexpression, if a (.*?) was inserted in the constructor.
801 if (!braces_match(m[0].first, m[0].second, open_braces))
803 // Check braces on segments that matched all (.*?) subexpressions.
804 for (size_t i = 1; i < m.size(); ++i)
805 if (!braces_match(m[i].first, m[i].second))
807 // Exclude from the returned match length any length
808 // due to close wildcards added at end of regexp
809 if (close_wildcards == 0)
810 return m[0].second - m[0].first;
812 return m[m.size() - close_wildcards].first - m[0].first;
819 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
821 int res = findAux(cur, len, at_begin);
822 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
824 Paragraph const & par = cur.paragraph();
825 bool ws_left = cur.pos() > 0 ?
826 par.isWordSeparator(cur.pos() - 1) : true;
827 bool ws_right = cur.pos() + res < par.size() ?
828 par.isWordSeparator(cur.pos() + res) : true;
830 "cur.pos()=" << cur.pos() << ", res=" << res
831 << ", separ: " << ws_left << ", " << ws_right
833 if (ws_left && ws_right)
839 string MatchStringAdv::normalize(docstring const & s) const
842 if (! opt.casesensitive)
843 t = lyx::to_utf8(lowercase(s));
846 // Remove \n at begin
847 while (t.size() > 0 && t[0] == '\n')
850 while (t.size() > 0 && t[t.size() - 1] == '\n')
851 t = t.substr(0, t.size() - 1);
853 // Replace all other \n with spaces
854 while ((pos = t.find("\n")) != string::npos)
855 t.replace(pos, 1, " ");
856 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
857 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
858 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph|part)(\\{\\})+", ""))
859 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
864 docstring stringifyFromCursor(DocIterator const & cur, int len)
866 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
867 if (cur.inTexted()) {
868 Paragraph const & par = cur.paragraph();
869 // TODO what about searching beyond/across paragraph breaks ?
870 // TODO Try adding a AS_STR_INSERTS as last arg
871 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
872 int(par.size()) : cur.pos() + len;
873 OutputParams runparams(&cur.buffer()->params().encoding());
875 runparams.nice = true;
876 runparams.flavor = OutputParams::LATEX;
877 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
878 // No side effect of file copying and image conversion
879 runparams.dryrun = true;
880 LYXERR(Debug::FIND, "Stringifying with cur: "
881 << cur << ", from pos: " << cur.pos() << ", end: " << end);
882 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
883 } else if (cur.inMathed()) {
885 CursorSlice cs = cur.top();
886 MathData md = cs.cell();
887 MathData::const_iterator it_end =
888 ( ( len == -1 || cs.pos() + len > int(md.size()) )
889 ? md.end() : md.begin() + cs.pos() + len );
890 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
894 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
899 /** Computes the LaTeX export of buf starting from cur and ending len positions
900 * after cur, if len is positive, or at the paragraph or innermost inset end
903 docstring latexifyFromCursor(DocIterator const & cur, int len)
905 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
906 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
907 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
908 Buffer const & buf = *cur.buffer();
909 LASSERT(buf.isLatex(), /* */);
912 odocstringstream ods;
913 OutputParams runparams(&buf.params().encoding());
914 runparams.nice = false;
915 runparams.flavor = OutputParams::LATEX;
916 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
917 // No side effect of file copying and image conversion
918 runparams.dryrun = true;
920 if (cur.inTexted()) {
921 // @TODO what about searching beyond/across paragraph breaks ?
922 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
923 for (int i = 0; i < cur.pit(); ++i)
925 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
926 ? pit->size() : cur.pos() + len;
927 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
929 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
930 } else if (cur.inMathed()) {
931 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
932 for (int s = cur.depth() - 1; s >= 0; --s) {
933 CursorSlice const & cs = cur[s];
934 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
936 cs.asInsetMath()->asHullInset()->header_write(ws);
941 CursorSlice const & cs = cur.top();
942 MathData md = cs.cell();
943 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
944 ? md.end() : md.begin() + cs.pos() + len );
945 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
948 // Retrieve the math environment type, and add '$' or '$]'
949 // or others (\end{equation}) accordingly
950 for (int s = cur.depth() - 1; s >= 0; --s) {
951 CursorSlice const & cs = cur[s];
952 InsetMath * inset = cs.asInsetMath();
953 if (inset && inset->asHullInset()) {
955 inset->asHullInset()->footer_write(ws);
959 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
961 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
967 /** Finalize an advanced find operation, advancing the cursor to the innermost
968 ** position that matches, plus computing the length of the matching text to
971 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
973 // Search the foremost position that matches (avoids find of entire math
974 // inset when match at start of it)
976 DocIterator old_cur(cur.buffer());
978 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
982 } while (cur && cur.depth() > d && match(cur) > 0);
984 LASSERT(match(cur) > 0, /* */);
985 LYXERR(Debug::FIND, "Ok");
987 // Compute the match length
989 if (cur.pos() + len > cur.lastpos())
991 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
992 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
994 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
996 // Length of matched text (different from len param)
997 int old_len = match(cur, len);
999 // Greedy behaviour while matching regexps
1000 while ((new_len = match(cur, len + 1)) > old_len) {
1003 LYXERR(Debug::FIND, "verifying match with len = " << len);
1010 int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
1014 while (cur && !match(cur, -1, false)) {
1015 if (cur.pit() < cur.lastpit())
1021 for (; cur; cur.forwardPos()) {
1023 return findAdvFinalize(cur, match);
1029 /// Find the most backward consecutive match within same paragraph while searching backwards.
1030 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
1032 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1033 DocIterator tmp_cur = cur;
1034 int len = findAdvFinalize(tmp_cur, match);
1035 Inset & inset = cur.inset();
1036 for (; cur != cur_begin; cur.backwardPos()) {
1037 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
1038 DocIterator new_cur = cur;
1039 new_cur.backwardPos();
1040 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur))
1042 int new_len = findAdvFinalize(new_cur, match);
1047 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
1053 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match) {
1056 // Backup of original position
1057 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
1058 if (cur == cur_begin)
1061 DocIterator cur_orig(cur);
1063 bool pit_changed = false;
1064 found_match = false;
1067 found_match = match(cur, -1, false);
1071 cur.pos() = cur.lastpos();
1073 cur.pos() = cur_orig.pos();
1074 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1075 DocIterator cur_prev_iter;
1077 found_match = match(cur);
1078 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1079 << found_match << ", cur: " << cur);
1081 return findMostBackwards(cur, match);
1083 // Stop if begin of document reached
1084 if (cur == cur_begin)
1086 cur_prev_iter = cur;
1090 if (cur == cur_begin)
1102 } // anonym namespace
1105 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1106 DocIterator const & cur, int len)
1108 if (!opt.ignoreformat)
1109 return latexifyFromCursor(cur, len);
1111 return stringifyFromCursor(cur, len);
1115 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1116 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1117 bool regexp, docstring const & replace, bool keep_case,
1119 : search(search), casesensitive(casesensitive), matchword(matchword),
1120 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1121 regexp(regexp), replace(replace), keep_case(keep_case), scope(scope)
1129 /** Check if 'len' letters following cursor are all non-lowercase */
1130 static bool allNonLowercase(DocIterator const & cur, int len) {
1131 pos_type end_pos = cur.pos() + len;
1132 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1133 if (isLowerCase(cur.paragraph().getChar(pos)))
1139 /** Check if first letter is upper case and second one is lower case */
1140 static bool firstUppercase(DocIterator const & cur) {
1142 if (cur.pos() >= cur.lastpos() - 1) {
1143 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1146 ch1 = cur.paragraph().getChar(cur.pos());
1147 ch2 = cur.paragraph().getChar(cur.pos()+1);
1148 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1149 LYXERR(Debug::FIND, "firstUppercase(): "
1150 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1151 << ch2 << "(" << char(ch2) << ")"
1152 << ", result=" << result << ", cur=" << cur);
1157 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1159 ** \fixme What to do with possible further paragraphs in replace buffer ?
1161 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1162 ParagraphList::iterator pit = buffer.paragraphs().begin();
1163 pos_type right = pos_type(1);
1164 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1165 right = pit->size() + 1;
1166 pit->changeCase(buffer.params(), right, right, others_case);
1171 static void findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
1173 Cursor & cur = bv->cursor();
1174 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING)))
1176 DocIterator sel_beg = cur.selectionBegin();
1177 DocIterator sel_end = cur.selectionEnd();
1178 if (&sel_beg.inset() != &sel_end.inset()
1179 || sel_beg.pit() != sel_end.pit())
1181 int sel_len = sel_end.pos() - sel_beg.pos();
1182 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
1183 << ", sel_len: " << sel_len << endl);
1186 LASSERT(sel_len > 0, /**/);
1188 if (!matchAdv(sel_beg, sel_len))
1191 string lyx = to_utf8(opt.replace);
1192 // FIXME: Seems so stupid to me to rebuild a buffer here,
1193 // when we already have one (replace_work_area_.buffer())
1194 Buffer repl_buffer("", false);
1195 repl_buffer.setUnnamed(true);
1196 LASSERT(repl_buffer.readString(lyx), /**/);
1197 repl_buffer.changeLanguage(
1198 repl_buffer.language(),
1199 cur.getFont().language());
1200 if (opt.keep_case && sel_len >= 2) {
1201 if (cur.inTexted()) {
1202 if (firstUppercase(cur))
1203 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1204 else if (allNonLowercase(cur, sel_len))
1205 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1208 cap::cutSelection(cur, false, false);
1209 if (!cur.inMathed()) {
1210 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1211 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
1212 repl_buffer.params().documentClassPtr(),
1213 bv->buffer().errorList("Paste"));
1215 odocstringstream ods;
1216 OutputParams runparams(&repl_buffer.params().encoding());
1217 runparams.nice = false;
1218 runparams.flavor = OutputParams::LATEX;
1219 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1220 runparams.dryrun = true;
1222 TeXOnePar(repl_buffer, repl_buffer.text(),
1223 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1224 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1225 docstring repl_latex = ods.str();
1226 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1228 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1229 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1230 repl_latex = from_utf8(s);
1231 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1232 cur.niceInsert(repl_latex);
1234 bv->buffer().markDirty();
1235 cur.pos() -= repl_buffer.paragraphs().begin()->size();
1236 bv->putSelectionAt(DocIterator(cur), repl_buffer.paragraphs().begin()->size(), !opt.forward);
1237 bv->processUpdateFlags(Update::Force);
1241 /// Perform a FindAdv operation.
1242 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1247 if (opt.search.empty()) {
1248 bv->message(_("Search text is empty!"));
1253 MatchStringAdv matchAdv(bv->buffer(), opt);
1254 findAdvReplace(bv, opt, matchAdv);
1257 match_len = findForwardAdv(cur, matchAdv);
1259 match_len = findBackwardsAdv(cur, matchAdv);
1261 // This may only be raised by lyx::regex()
1262 bv->message(_("Invalid regular expression!"));
1266 if (match_len == 0) {
1267 bv->message(_("Match not found!"));
1271 bv->message(_("Match found!"));
1273 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
1274 bv->putSelectionAt(cur, match_len, !opt.forward);
1280 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
1282 os << to_utf8(opt.search) << "\nEOSS\n"
1283 << opt.casesensitive << ' '
1284 << opt.matchword << ' '
1285 << opt.forward << ' '
1286 << opt.expandmacros << ' '
1287 << opt.ignoreformat << ' '
1288 << opt.regexp << ' '
1289 << to_utf8(opt.replace) << "\nEOSS\n"
1290 << opt.keep_case << ' '
1293 LYXERR(Debug::FIND, "built: " << os.str());
1298 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
1300 LYXERR(Debug::FIND, "parsing");
1304 while (line != "EOSS") {
1308 if (is.eof()) // Tolerate malformed request
1312 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1313 opt.search = from_utf8(s);
1314 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1315 is.get(); // Waste space before replace string
1318 while (line != "EOSS") {
1322 if (is.eof()) // Tolerate malformed request
1326 is >> opt.keep_case;
1329 opt.scope = FindAndReplaceOptions::SearchScope(i);
1330 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1331 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1332 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1333 opt.replace = from_utf8(s);