A bit more re-organization.
[lyx.git] / src / lyxfind.cpp
blob8b2c9343592c3ae952978a3de8194c20842810c0
1 /**
2 * \file lyxfind.cpp
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
7 * \author John Levon
8 * \author Jürgen Vigna
9 * \author Alfredo Braunstein
10 * \author Tommaso Cucinotta
12 * Full author contact details are available in file CREDITS.
15 #include <config.h>
17 #include "lyxfind.h"
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
23 #include "Changes.h"
24 #include "Cursor.h"
25 #include "CutAndPaste.h"
26 #include "FuncRequest.h"
27 #include "OutputParams.h"
28 #include "output_latex.h"
29 #include "Paragraph.h"
30 #include "ParIterator.h"
31 #include "TexRow.h"
32 #include "Text.h"
33 #include "FuncRequest.h"
34 #include "LyXFunc.h"
36 #include "mathed/InsetMath.h"
37 #include "mathed/InsetMathGrid.h"
38 #include "mathed/InsetMathHull.h"
39 #include "mathed/MathStream.h"
41 #include "frontends/alert.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/docstream.h"
46 #include "support/gettext.h"
47 #include "support/lstrings.h"
48 #include "support/lassert.h"
50 #include <boost/regex.hpp>
51 #include <boost/next_prior.hpp>
53 using namespace std;
54 using namespace lyx::support;
56 namespace lyx {
58 namespace {
60 bool parse_bool(docstring & howto)
62 if (howto.empty())
63 return false;
64 docstring var;
65 howto = split(howto, var, ' ');
66 return var == "1";
70 class MatchString : public binary_function<Paragraph, pos_type, bool>
72 public:
73 MatchString(docstring const & str, bool cs, bool mw)
74 : str(str), cs(cs), mw(mw)
77 // returns true if the specified string is at the specified position
78 // del specifies whether deleted strings in ct mode will be considered
79 bool operator()(Paragraph const & par, pos_type pos, bool del = true) const
81 return par.find(str, cs, mw, pos, del);
84 private:
85 // search string
86 docstring str;
87 // case sensitive
88 bool cs;
89 // match whole words only
90 bool mw;
94 bool findForward(DocIterator & cur, MatchString const & match,
95 bool find_del = true)
97 for (; cur; cur.forwardChar())
98 if (cur.inTexted() &&
99 match(cur.paragraph(), cur.pos(), find_del))
100 return true;
101 return false;
105 bool findBackwards(DocIterator & cur, MatchString const & match,
106 bool find_del = true)
108 while (cur) {
109 cur.backwardChar();
110 if (cur.inTexted() &&
111 match(cur.paragraph(), cur.pos(), find_del))
112 return true;
114 return false;
118 bool findChange(DocIterator & cur, bool next)
120 if (!next)
121 cur.backwardPos();
122 for (; cur; next ? cur.forwardPos() : cur.backwardPos())
123 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos())) {
124 if (!next)
125 // if we search backwards, take a step forward
126 // to correctly set the anchor
127 cur.forwardPos();
128 return true;
131 return false;
135 bool searchAllowed(BufferView * /*bv*/, docstring const & str)
137 if (str.empty()) {
138 frontend::Alert::error(_("Search error"), _("Search string is empty"));
139 return false;
141 return true;
145 bool find(BufferView * bv, docstring const & searchstr,
146 bool cs, bool mw, bool fw, bool find_del = true)
148 if (!searchAllowed(bv, searchstr))
149 return false;
151 DocIterator cur = bv->cursor();
153 MatchString const match(searchstr, cs, mw);
155 bool found = fw ? findForward(cur, match, find_del) :
156 findBackwards(cur, match, find_del);
158 if (found)
159 bv->putSelectionAt(cur, searchstr.length(), !fw);
161 return found;
165 int replaceAll(BufferView * bv,
166 docstring const & searchstr, docstring const & replacestr,
167 bool cs, bool mw)
169 Buffer & buf = bv->buffer();
171 if (!searchAllowed(bv, searchstr) || buf.isReadonly())
172 return 0;
174 MatchString const match(searchstr, cs, mw);
175 int num = 0;
177 int const rsize = replacestr.size();
178 int const ssize = searchstr.size();
180 Cursor cur(*bv);
181 cur.setCursor(doc_iterator_begin(&buf));
182 while (findForward(cur, match, false)) {
183 // Backup current cursor position and font.
184 pos_type const pos = cur.pos();
185 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
186 cur.recordUndo();
187 int striked = ssize - cur.paragraph().eraseChars(pos, pos + ssize,
188 buf.params().trackChanges);
189 cur.paragraph().insert(pos, replacestr, font,
190 Change(buf.params().trackChanges ?
191 Change::INSERTED : Change::UNCHANGED));
192 for (int i = 0; i < rsize + striked; ++i)
193 cur.forwardChar();
194 ++num;
197 buf.updateLabels();
198 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
199 if (num)
200 buf.markDirty();
201 return num;
205 bool stringSelected(BufferView * bv, docstring & searchstr,
206 bool cs, bool mw, bool fw)
208 // if nothing selected and searched string is empty, this
209 // means that we want to search current word at cursor position.
210 if (!bv->cursor().selection() && searchstr.empty()) {
211 bv->cursor().innerText()->selectWord(bv->cursor(), WHOLE_WORD);
212 searchstr = bv->cursor().selectionAsString(false);
213 return true;
216 // if nothing selected or selection does not equal search
217 // string search and select next occurance and return
218 docstring const & str1 = searchstr;
219 docstring const str2 = bv->cursor().selectionAsString(false);
220 if ((cs && str1 != str2) || compare_no_case(str1, str2) != 0) {
221 find(bv, searchstr, cs, mw, fw);
222 return false;
225 return true;
229 int replace(BufferView * bv, docstring & searchstr,
230 docstring const & replacestr, bool cs, bool mw, bool fw)
232 if (!stringSelected(bv, searchstr, cs, mw, fw))
233 return 0;
235 if (!searchAllowed(bv, searchstr) || bv->buffer().isReadonly())
236 return 0;
238 Cursor & cur = bv->cursor();
239 cap::replaceSelectionWithString(cur, replacestr, fw);
240 bv->buffer().markDirty();
241 find(bv, searchstr, cs, mw, fw, false);
242 bv->buffer().updateMacros();
243 bv->processUpdateFlags(Update::Force | Update::FitCursor);
245 return 1;
248 } // namespace anon
251 docstring const find2string(docstring const & search,
252 bool casesensitive, bool matchword, bool forward)
254 odocstringstream ss;
255 ss << search << '\n'
256 << int(casesensitive) << ' '
257 << int(matchword) << ' '
258 << int(forward);
259 return ss.str();
263 docstring const replace2string(docstring const & replace,
264 docstring const & search, bool casesensitive, bool matchword,
265 bool all, bool forward)
267 odocstringstream ss;
268 ss << replace << '\n'
269 << search << '\n'
270 << int(casesensitive) << ' '
271 << int(matchword) << ' '
272 << int(all) << ' '
273 << int(forward);
274 return ss.str();
278 bool find(BufferView * bv, FuncRequest const & ev)
280 if (!bv || ev.action != LFUN_WORD_FIND)
281 return false;
283 //lyxerr << "find called, cmd: " << ev << endl;
285 // data is of the form
286 // "<search>
287 // <casesensitive> <matchword> <forward>"
288 docstring search;
289 docstring howto = split(ev.argument(), search, '\n');
291 bool casesensitive = parse_bool(howto);
292 bool matchword = parse_bool(howto);
293 bool forward = parse_bool(howto);
295 return find(bv, search, casesensitive, matchword, forward);
299 void replace(BufferView * bv, FuncRequest const & ev, bool has_deleted)
301 if (!bv || ev.action != LFUN_WORD_REPLACE)
302 return;
304 // data is of the form
305 // "<search>
306 // <replace>
307 // <casesensitive> <matchword> <all> <forward>"
308 docstring search;
309 docstring rplc;
310 docstring howto = split(ev.argument(), rplc, '\n');
311 howto = split(howto, search, '\n');
313 bool casesensitive = parse_bool(howto);
314 bool matchword = parse_bool(howto);
315 bool all = parse_bool(howto);
316 bool forward = parse_bool(howto);
318 if (!has_deleted) {
319 int const replace_count = all
320 ? replaceAll(bv, search, rplc, casesensitive, matchword)
321 : replace(bv, search, rplc, casesensitive, matchword, forward);
323 Buffer & buf = bv->buffer();
324 if (replace_count == 0) {
325 // emit message signal.
326 buf.message(_("String not found!"));
327 } else {
328 if (replace_count == 1) {
329 // emit message signal.
330 buf.message(_("String has been replaced."));
331 } else {
332 docstring str = convert<docstring>(replace_count);
333 str += _(" strings have been replaced.");
334 // emit message signal.
335 buf.message(str);
338 } else {
339 // if we have deleted characters, we do not replace at all, but
340 // rather search for the next occurence
341 if (find(bv, search, casesensitive, matchword, forward))
342 bv->showCursor();
343 else
344 bv->message(_("String not found!"));
349 bool findNextChange(BufferView * bv)
351 return findChange(bv, true);
355 bool findPreviousChange(BufferView * bv)
357 return findChange(bv, false);
361 bool findChange(BufferView * bv, bool next)
363 if (bv->cursor().selection()) {
364 // set the cursor at the beginning or at the end of the selection
365 // before searching. Otherwise, the current change will be found.
366 if (next != (bv->cursor().top() > bv->cursor().anchor()))
367 bv->cursor().setCursorToAnchor();
370 DocIterator cur = bv->cursor();
372 // Are we within a change ? Then first search forward (backward),
373 // clear the selection and search the other way around (see the end
374 // of this function). This will avoid changes to be selected half.
375 bool search_both_sides = false;
376 if (cur.pos() > 1) {
377 Change change_next_pos
378 = cur.paragraph().lookupChange(cur.pos());
379 Change change_prev_pos
380 = cur.paragraph().lookupChange(cur.pos() - 1);
381 if (change_next_pos.isSimilarTo(change_prev_pos))
382 search_both_sides = true;
385 if (!findChange(cur, next))
386 return false;
388 bv->cursor().setCursor(cur);
389 bv->cursor().resetAnchor();
391 if (!next)
392 // take a step into the change
393 cur.backwardPos();
395 Change orig_change = cur.paragraph().lookupChange(cur.pos());
397 CursorSlice & tip = cur.top();
398 if (next) {
399 for (; !tip.at_end(); tip.forwardPos()) {
400 Change change = tip.paragraph().lookupChange(tip.pos());
401 if (change != orig_change)
402 break;
404 } else {
405 for (; !tip.at_begin();) {
406 tip.backwardPos();
407 Change change = tip.paragraph().lookupChange(tip.pos());
408 if (change != orig_change) {
409 // take a step forward to correctly set the selection
410 tip.forwardPos();
411 break;
416 // Now put cursor to end of selection:
417 bv->cursor().setCursor(cur);
418 bv->cursor().setSelection();
420 if (search_both_sides) {
421 bv->cursor().setSelection(false);
422 findChange(bv, !next);
425 return true;
428 namespace {
430 typedef vector<pair<string, string> > Escapes;
432 /// A map of symbols and their escaped equivalent needed within a regex.
433 Escapes const & get_regexp_escapes()
435 static Escapes escape_map;
436 if (escape_map.empty()) {
437 escape_map.push_back(pair<string, string>("\\", "\\\\"));
438 escape_map.push_back(pair<string, string>("^", "\\^"));
439 escape_map.push_back(pair<string, string>("$", "\\$"));
440 escape_map.push_back(pair<string, string>("{", "\\{"));
441 escape_map.push_back(pair<string, string>("}", "\\}"));
442 escape_map.push_back(pair<string, string>("[", "\\["));
443 escape_map.push_back(pair<string, string>("]", "\\]"));
444 escape_map.push_back(pair<string, string>("(", "\\("));
445 escape_map.push_back(pair<string, string>(")", "\\)"));
446 escape_map.push_back(pair<string, string>("+", "\\+"));
447 escape_map.push_back(pair<string, string>("*", "\\*"));
448 escape_map.push_back(pair<string, string>(".", "\\."));
450 return escape_map;
453 /// A map of lyx escaped strings and their unescaped equivalent.
454 Escapes const & get_lyx_unescapes() {
455 static Escapes escape_map;
456 if (escape_map.empty()) {
457 escape_map.push_back(pair<string, string>("{*}", "*"));
458 escape_map.push_back(pair<string, string>("{[}", "["));
459 escape_map.push_back(pair<string, string>("\\$", "$"));
460 escape_map.push_back(pair<string, string>("\\backslash{}", "\\"));
461 escape_map.push_back(pair<string, string>("\\backslash", "\\"));
462 escape_map.push_back(pair<string, string>("\\sim ", "~"));
463 escape_map.push_back(pair<string, string>("\\^", "^"));
465 return escape_map;
468 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
469 ** the found occurrence were escaped.
471 string apply_escapes(string s, Escapes const & escape_map)
473 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
474 Escapes::const_iterator it;
475 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
476 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
477 unsigned int pos = 0;
478 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
479 s.replace(pos, it->first.length(), it->second);
480 // LYXERR(Debug::FIND, "After escape: " << s);
481 pos += it->second.length();
482 // LYXERR(Debug::FIND, "pos: " << pos);
485 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
486 return s;
489 /** Return the position of the closing brace matching the open one at s[pos],
490 ** or s.size() if not found.
492 size_t find_matching_brace(string const & s, size_t pos)
494 LASSERT(s[pos] == '{', /* */);
495 int open_braces = 1;
496 for (++pos; pos < s.size(); ++pos) {
497 if (s[pos] == '\\')
498 ++pos;
499 else if (s[pos] == '{')
500 ++open_braces;
501 else if (s[pos] == '}') {
502 --open_braces;
503 if (open_braces == 0)
504 return pos;
507 return s.size();
510 /// Within \regexp{} apply get_regex_escapes(), while outside apply get_lyx_unescapes().
511 string escape_for_regex(string s)
513 size_t pos = 0;
514 while (pos < s.size()) {
515 size_t new_pos = s.find("\\regexp{", pos);
516 if (new_pos == string::npos)
517 new_pos = s.size();
518 LYXERR(Debug::FIND, "new_pos: " << new_pos);
519 string t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
520 LYXERR(Debug::FIND, "t : " << t);
521 t = apply_escapes(t, get_regexp_escapes());
522 s.replace(pos, new_pos - pos, t);
523 new_pos = pos + t.size();
524 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
525 LYXERR(Debug::FIND, "new_pos: " << new_pos);
526 if (new_pos == s.size())
527 break;
528 size_t end_pos = find_matching_brace(s, new_pos + 7);
529 LYXERR(Debug::FIND, "end_pos: " << end_pos);
530 t = apply_escapes(s.substr(new_pos + 8, end_pos - (new_pos + 8)), get_lyx_unescapes());
531 LYXERR(Debug::FIND, "t : " << t);
532 if (end_pos == s.size()) {
533 s.replace(new_pos, end_pos - new_pos, t);
534 pos = s.size();
535 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
536 break;
538 s.replace(new_pos, end_pos + 1 - new_pos, t);
539 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
540 pos = new_pos + t.size();
541 LYXERR(Debug::FIND, "pos: " << pos);
543 return s;
546 /// Wrapper for boost::regex_replace with simpler interface
547 bool regex_replace(string const & s, string & t, string const & searchstr,
548 string const & replacestr)
550 boost::regex e(searchstr);
551 ostringstream oss;
552 ostream_iterator<char, char> it(oss);
553 boost::regex_replace(it, s.begin(), s.end(), e, replacestr);
554 // tolerate t and s be references to the same variable
555 bool rv = (s != oss.str());
556 t = oss.str();
557 return rv;
560 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
562 ** Verify that closed braces exactly match open braces. This avoids that, for example,
563 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
565 ** @param unmatched
566 ** Number of open braces that must remain open at the end for the verification to succeed.
568 bool braces_match(string::const_iterator const & beg,
569 string::const_iterator const & end, int unmatched = 0)
571 int open_pars = 0;
572 string::const_iterator it = beg;
573 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
574 for (; it != end; ++it) {
575 // Skip escaped braces in the count
576 if (*it == '\\') {
577 ++it;
578 if (it == end)
579 break;
580 } else if (*it == '{') {
581 ++open_pars;
582 } else if (*it == '}') {
583 if (open_pars == 0) {
584 LYXERR(Debug::FIND, "Found unmatched closed brace");
585 return false;
586 } else
587 --open_pars;
590 if (open_pars != unmatched) {
591 LYXERR(Debug::FIND, "Found " << open_pars
592 << " instead of " << unmatched
593 << " unmatched open braces at the end of count");
594 return false;
596 LYXERR(Debug::FIND, "Braces match as expected");
597 return true;
600 /** The class performing a match between a position in the document and the FindAdvOptions.
602 class MatchStringAdv {
603 public:
604 MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt);
606 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
607 ** constructor as opt.search, under the opt.* options settings.
609 ** @param at_begin
610 ** If set, then match is searched only against beginning of text starting at cur.
611 ** If unset, then match is searched anywhere in text starting at cur.
613 ** @return
614 ** The length of the matching text, or zero if no match was found.
616 int operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
618 public:
619 /// buffer
620 lyx::Buffer const & buf;
621 /// options
622 FindAndReplaceOptions const & opt;
624 private:
625 /** Normalize a stringified or latexified LyX paragraph.
627 ** Normalize means:
628 ** <ul>
629 ** <li>if search is not casesensitive, then lowercase the string;
630 ** <li>remove any newline at begin or end of the string;
631 ** <li>replace any newline in the middle of the string with a simple space;
632 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
633 ** </ul>
635 ** @todo Normalization should also expand macros, if the corresponding
636 ** search option was checked.
638 string normalize(docstring const & s) const;
639 // normalized string to search
640 string par_as_string;
641 // regular expression to use for searching
642 boost::regex regexp;
643 // same as regexp, but prefixed with a ".*"
644 boost::regex regexp2;
645 // unmatched open braces in the search string/regexp
646 int open_braces;
647 // number of (.*?) subexpressions added at end of search regexp for closing
648 // environments, math mode, styles, etc...
649 int close_wildcards;
653 MatchStringAdv::MatchStringAdv(lyx::Buffer const & buf, FindAndReplaceOptions const & opt)
654 : buf(buf), opt(opt)
656 par_as_string = normalize(opt.search);
657 open_braces = 0;
658 close_wildcards = 0;
660 if (! opt.regexp) {
661 // Remove trailing closure of math, macros and environments, so to catch parts of them.
662 do {
663 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
664 if (regex_replace(par_as_string, par_as_string, "(.*)[[:blank:]]\\'", "$1"))
665 continue;
666 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\$\\'", "$1"))
667 continue;
668 // @todo need to account for open square braces as well ?
669 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\\\]\\'", "$1"))
670 continue;
671 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\\\end\\{[a-zA-Z_]*\\}\\'", "$1"))
672 continue;
673 if (regex_replace(par_as_string, par_as_string, "(.*[^\\\\]) ?\\}\\'", "$1")) {
674 ++open_braces;
675 continue;
677 break;
678 } while (true);
679 LYXERR(Debug::FIND, "Open braces: " << open_braces);
680 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
681 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
682 } else {
683 par_as_string = escape_for_regex(par_as_string);
684 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
685 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
686 if (
687 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
688 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
689 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
690 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
691 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
692 || regex_replace(par_as_string, par_as_string,
693 "(.*[^\\\\])(\\\\\\\\end\\\\\\{[a-zA-Z_]*\\\\\\})\\'", "$1(.*?)$2")
694 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
695 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
697 ++close_wildcards;
699 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
700 LYXERR(Debug::FIND, "Open braces: " << open_braces);
701 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
702 LASSERT(braces_match(par_as_string.begin(), par_as_string.end(), open_braces), /* */);
703 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
704 // If entered regexp must match at begin of searched string buffer
705 regexp = boost::regex(string("\\`") + par_as_string);
706 // If entered regexp may match wherever in searched string buffer
707 regexp2 = boost::regex(string("\\`.*") + par_as_string);
712 int MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
714 docstring docstr = stringifyFromForSearch(opt, cur, len);
715 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
716 string str = normalize(docstr);
717 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
718 if (! opt.regexp) {
719 if (at_begin) {
720 if (str.substr(0, par_as_string.size()) == par_as_string)
721 return par_as_string.size();
722 } else {
723 size_t pos = str.find(par_as_string);
724 if (pos != string::npos)
725 return par_as_string.size();
727 } else {
728 // Try all possible regexp matches,
729 //until one that verifies the braces match test is found
730 boost::regex const *p_regexp = at_begin ? &regexp : &regexp2;
731 boost::sregex_iterator re_it(str.begin(), str.end(), *p_regexp);
732 boost::sregex_iterator re_it_end;
733 for (; re_it != re_it_end; ++re_it) {
734 boost::match_results<string::const_iterator> const & m = *re_it;
735 // Check braces on the segment that matched the entire regexp expression,
736 // plus the last subexpression, if a (.*?) was inserted in the constructor.
737 if (! braces_match(m[0].first, m[0].second, open_braces))
738 return 0;
739 // Check braces on segments that matched all (.*?) subexpressions.
740 for (size_t i = 1; i < m.size(); ++i)
741 if (! braces_match(m[i].first, m[i].second))
742 return false;
743 // Exclude from the returned match length any length
744 // due to close wildcards added at end of regexp
745 if (close_wildcards == 0)
746 return m[0].second - m[0].first;
747 else
748 return m[m.size() - close_wildcards].first - m[0].first;
751 return 0;
755 string MatchStringAdv::normalize(docstring const & s) const
757 string t;
758 if (! opt.casesensitive)
759 t = lyx::to_utf8(lowercase(s));
760 else
761 t = lyx::to_utf8(s);
762 // Remove \n at begin
763 while (t.size() > 0 && t[0] == '\n')
764 t = t.substr(1);
765 // Remove \n at end
766 while (t.size() > 0 && t[t.size() - 1] == '\n')
767 t = t.substr(0, t.size() - 1);
768 size_t pos;
769 // Replace all other \n with spaces
770 while ((pos = t.find("\n")) != string::npos)
771 t.replace(pos, 1, " ");
772 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
773 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
774 while (regex_replace(t, t, "\\\\(emph|textbf|subsubsection|subsection|section|subparagraph|paragraph)(\\{\\})+", ""))
775 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
776 return t;
780 docstring stringifyFromCursor(DocIterator const & cur, int len)
782 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
783 if (cur.inTexted()) {
784 Paragraph const & par = cur.paragraph();
785 // TODO what about searching beyond/across paragraph breaks ?
786 // TODO Try adding a AS_STR_INSERTS as last arg
787 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
788 int(par.size()) : cur.pos() + len;
789 OutputParams runparams(&cur.buffer()->params().encoding());
790 odocstringstream os;
791 runparams.nice = true;
792 runparams.flavor = OutputParams::LATEX;
793 runparams.linelen = 100000; //lyxrc.plaintext_linelen;
794 // No side effect of file copying and image conversion
795 runparams.dryrun = true;
796 LYXERR(Debug::FIND, "Stringifying with cur: "
797 << cur << ", from pos: " << cur.pos() << ", end: " << end);
798 return par.stringify(cur.pos(), end, AS_STR_INSETS, runparams);
799 } else if (cur.inMathed()) {
800 odocstringstream os;
801 CursorSlice cs = cur.top();
802 MathData md = cs.cell();
803 MathData::const_iterator it_end =
804 ( ( len == -1 || cs.pos() + len > int(md.size()) )
805 ? md.end() : md.begin() + cs.pos() + len );
806 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
807 os << *it;
808 return os.str();
810 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
811 return docstring();
815 /** Computes the LaTeX export of buf starting from cur and ending len positions
816 * after cur, if len is positive, or at the paragraph or innermost inset end
817 * if len is -1.
819 docstring latexifyFromCursor(DocIterator const & cur, int len)
821 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
822 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
823 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
824 Buffer const & buf = *cur.buffer();
825 LASSERT(buf.isLatex(), /* */);
827 TexRow texrow;
828 odocstringstream ods;
829 OutputParams runparams(&buf.params().encoding());
830 runparams.nice = false;
831 runparams.flavor = OutputParams::LATEX;
832 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
833 // No side effect of file copying and image conversion
834 runparams.dryrun = true;
836 if (cur.inTexted()) {
837 // @TODO what about searching beyond/across paragraph breaks ?
838 ParagraphList::const_iterator pit = cur.innerText()->paragraphs().begin();
839 for (int i = 0; i < cur.pit(); ++i)
840 ++pit;
841 // ParagraphList::const_iterator pit_end = pit;
842 // ++pit_end;
843 // lyx::latexParagraphs(buf, cur.innerText()->paragraphs(), ods, texrow, runparams, string(), pit, pit_end);
844 pos_type const endpos = (len == -1 || cur.pos() + len > int(pit->size()))
845 ? pit->size() : cur.pos() + len;
846 TeXOnePar(buf, *cur.innerText(), pit, ods, texrow, runparams, string(),
847 cur.pos(), endpos);
848 LYXERR(Debug::FIND, "Latexified text: '" << lyx::to_utf8(ods.str()) << "'");
849 } else if (cur.inMathed()) {
850 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
851 for (int s = cur.depth() - 1; s >= 0; --s) {
852 CursorSlice const & cs = cur[s];
853 if (cs.asInsetMath() && cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
854 WriteStream ws(ods);
855 cs.asInsetMath()->asHullInset()->header_write(ws);
856 break;
860 CursorSlice const & cs = cur.top();
861 MathData md = cs.cell();
862 MathData::const_iterator it_end = ( ( len == -1 || cs.pos() + len > int(md.size()) )
863 ? md.end() : md.begin() + cs.pos() + len );
864 for (MathData::const_iterator it = md.begin() + cs.pos(); it != it_end; ++it)
865 ods << *it;
867 // MathData md = cur.cell();
868 // MathData::const_iterator it_end = ( ( len == -1 || cur.pos() + len > int(md.size()) ) ? md.end() : md.begin() + cur.pos() + len );
869 // for (MathData::const_iterator it = md.begin() + cur.pos(); it != it_end; ++it) {
870 // MathAtom const & ma = *it;
871 // ma.nucleus()->latex(buf, ods, runparams);
872 // }
874 // Retrieve the math environment type, and add '$' or '$]'
875 // or others (\end{equation}) accordingly
876 for (int s = cur.depth() - 1; s >= 0; --s) {
877 CursorSlice const & cs = cur[s];
878 InsetMath * inset = cs.asInsetMath();
879 if (inset && inset->asHullInset()) {
880 WriteStream ws(ods);
881 inset->asHullInset()->footer_write(ws);
882 break;
885 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
886 } else {
887 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
889 return ods.str();
892 /** Finalize an advanced find operation, advancing the cursor to the innermost
893 ** position that matches, plus computing the length of the matching text to
894 ** be selected
896 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
898 // Search the foremost position that matches (avoids find of entire math
899 // inset when match at start of it)
900 size_t d;
901 DocIterator old_cur(cur.buffer());
902 do {
903 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
904 d = cur.depth();
905 old_cur = cur;
906 cur.forwardPos();
907 } while (cur && cur.depth() > d && match(cur) > 0);
908 cur = old_cur;
909 LASSERT(match(cur) > 0, /* */);
910 LYXERR(Debug::FIND, "Ok");
912 // Compute the match length
913 int len = 1;
914 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
915 while (cur.pos() + len <= cur.lastpos() && match(cur, len) == 0) {
916 ++len;
917 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
919 // Length of matched text (different from len param)
920 int old_len = match(cur, len);
921 int new_len;
922 // Greedy behaviour while matching regexps
923 while ((new_len = match(cur, len + 1)) > old_len) {
924 ++len;
925 old_len = new_len;
926 LYXERR(Debug::FIND, "verifying match with len = " << len);
928 return len;
932 /// Finds forward
933 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
935 if (!cur)
936 return 0;
937 int wrap_answer;
938 do {
939 while (cur && !match(cur, -1, false)) {
940 if (cur.pit() < cur.lastpit())
941 cur.forwardPar();
942 else {
943 cur.forwardPos();
946 for (; cur; cur.forwardPos()) {
947 if (match(cur))
948 return findAdvFinalize(cur, match);
950 wrap_answer = frontend::Alert::prompt(
951 _("Wrap search?"),
952 _("End of document reached while searching forward.\n"
953 "\n"
954 "Continue searching from beginning?"),
955 0, 1, _("&Yes"), _("&No"));
956 cur.clear();
957 cur.push_back(CursorSlice(match.buf.inset()));
958 } while (wrap_answer == 0);
959 return 0;
962 /// Find the most backward consecutive match within same paragraph while searching backwards.
963 void findMostBackwards(DocIterator & cur, MatchStringAdv const & match, int & len) {
964 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
965 len = findAdvFinalize(cur, match);
966 if (cur != cur_begin) {
967 Inset & inset = cur.inset();
968 int old_len;
969 DocIterator old_cur;
970 DocIterator dit2;
971 do {
972 old_cur = cur;
973 old_len = len;
974 cur.backwardPos();
975 LYXERR(Debug::FIND, "findMostBackwards(): old_cur="
976 << old_cur << ", old_len=" << len << ", cur=" << cur);
977 dit2 = cur;
978 } while (cur != cur_begin && &cur.inset() == &inset && match(cur)
979 && (len = findAdvFinalize(dit2, match)) > old_len);
980 cur = old_cur;
981 len = old_len;
983 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
986 /// Finds backwards
987 int findBackwardsAdv(DocIterator & cur, MatchStringAdv const & match) {
988 if (! cur)
989 return 0;
990 DocIterator cur_orig(cur);
991 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
992 /* if (match(cur_orig)) */
993 /* findAdvFinalize(cur_orig, match); */
994 int wrap_answer = 0;
995 bool found_match;
996 do {
997 bool pit_changed = false;
998 found_match = false;
999 // Search in current par occurs from start to end,
1000 // but in next loop match is discarded if pos > original pos
1001 cur.pos() = 0;
1002 found_match = match(cur, -1, false);
1003 LYXERR(Debug::FIND, "findBackAdv0: found_match=" << found_match << ", cur: " << cur);
1004 while (cur != cur_begin) {
1005 if (found_match)
1006 break;
1007 if (cur.pit() > 0)
1008 --cur.pit();
1009 else
1010 cur.backwardPos();
1011 pit_changed = true;
1012 // Search in previous pars occurs from start to end
1013 cur.pos() = 0;
1014 found_match = match(cur, -1, false);
1015 LYXERR(Debug::FIND, "findBackAdv1: found_match="
1016 << found_match << ", cur: " << cur);
1018 if (pit_changed)
1019 cur.pos() = cur.lastpos();
1020 else
1021 cur.pos() = cur_orig.pos();
1022 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
1023 if (found_match) {
1024 while (true) {
1025 found_match=match(cur);
1026 LYXERR(Debug::FIND, "findBackAdv3: found_match="
1027 << found_match << ", cur: " << cur);
1028 if (found_match) {
1029 int len;
1030 findMostBackwards(cur, match, len);
1031 if (&cur.inset() != &cur_orig.inset()
1032 || !(cur.pit()==cur_orig.pit())
1033 || cur.pos() < cur_orig.pos())
1034 return len;
1036 if (cur == cur_begin)
1037 break;
1038 cur.backwardPos();
1041 wrap_answer = frontend::Alert::prompt(
1042 _("Wrap search?"),
1043 _("Beginning of document reached while searching backwards\n"
1044 "\n"
1045 "Continue searching from end?"),
1046 0, 1, _("&Yes"), _("&No"));
1047 cur = doc_iterator_end(&match.buf);
1048 cur.backwardPos();
1049 } while (wrap_answer == 0);
1050 cur = cur_orig;
1051 return 0;
1054 } // anonym namespace
1057 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
1058 DocIterator const & cur, int len)
1060 if (!opt.ignoreformat)
1061 return latexifyFromCursor(cur, len);
1062 else
1063 return stringifyFromCursor(cur, len);
1067 FindAndReplaceOptions::FindAndReplaceOptions(docstring const & search, bool casesensitive,
1068 bool matchword, bool forward, bool expandmacros, bool ignoreformat,
1069 bool regexp, docstring const & replace, bool keep_case)
1070 : search(search), casesensitive(casesensitive), matchword(matchword),
1071 forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
1072 regexp(regexp), replace(replace), keep_case(keep_case)
1077 /** Checks if the supplied character is lower-case */
1078 static bool isLowerCase(char_type ch) {
1079 return lowercase(ch) == ch;
1083 /** Checks if the supplied character is upper-case */
1084 static bool isUpperCase(char_type ch) {
1085 return uppercase(ch) == ch;
1089 /** Check if 'len' letters following cursor are all non-lowercase */
1090 static bool allNonLowercase(DocIterator const & cur, int len) {
1091 pos_type end_pos = cur.pos() + len;
1092 for (pos_type pos = cur.pos(); pos != end_pos; ++pos)
1093 if (isLowerCase(cur.paragraph().getChar(pos)))
1094 return false;
1095 return true;
1099 /** Check if first letter is upper case and second one is lower case */
1100 static bool firstUppercase(DocIterator const & cur) {
1101 char_type ch1, ch2;
1102 if (cur.pos() >= cur.lastpos() - 1) {
1103 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
1104 return false;
1106 ch1 = cur.paragraph().getChar(cur.pos());
1107 ch2 = cur.paragraph().getChar(cur.pos()+1);
1108 bool result = isUpperCase(ch1) && isLowerCase(ch2);
1109 LYXERR(Debug::FIND, "firstUppercase(): "
1110 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
1111 << ch2 << "(" << char(ch2) << ")"
1112 << ", result=" << result << ", cur=" << cur);
1113 return result;
1117 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
1119 ** \fixme What to do with possible further paragraphs in replace buffer ?
1121 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case) {
1122 ParagraphList::iterator pit = buffer.paragraphs().begin();
1123 pos_type right = pos_type(1);
1124 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
1125 right = pit->size() + 1;
1126 pit->changeCase(buffer.params(), right, right, others_case);
1130 /// Perform a FindAdv operation.
1131 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
1133 DocIterator cur = bv->cursor();
1134 int match_len = 0;
1136 if (opt.search.empty()) {
1137 bv->message(_("Search text is empty!"));
1138 return false;
1140 // if (! bv->buffer()) {
1141 // bv->message(_("No open document !"));
1142 // return false;
1143 // }
1145 try {
1146 MatchStringAdv const matchAdv(bv->buffer(), opt);
1147 if (opt.forward)
1148 match_len = findForwardAdv(cur, matchAdv);
1149 else
1150 match_len = findBackwardsAdv(cur, matchAdv);
1151 } catch (...) {
1152 // This may only be raised by boost::regex()
1153 bv->message(_("Invalid regular expression!"));
1154 return false;
1157 if (match_len == 0) {
1158 bv->message(_("Match not found!"));
1159 return false;
1162 LYXERR(Debug::FIND, "Putting selection at " << cur << " with len: " << match_len);
1163 bv->putSelectionAt(cur, match_len, ! opt.forward);
1164 if (opt.replace == docstring(from_utf8(LYX_FR_NULL_STRING))) {
1165 bv->message(_("Match found !"));
1166 } else {
1167 string lyx = to_utf8(opt.replace);
1168 // FIXME: Seems so stupid to me to rebuild a buffer here,
1169 // when we already have one (replace_work_area_.buffer())
1170 Buffer repl_buffer("", false);
1171 repl_buffer.setUnnamed(true);
1172 if (repl_buffer.readString(lyx)) {
1173 if (opt.keep_case && match_len >= 2) {
1174 if (cur.inTexted()) {
1175 if (firstUppercase(cur))
1176 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
1177 else if (allNonLowercase(cur, match_len))
1178 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
1181 cap::cutSelection(bv->cursor(), false, false);
1182 if (! cur.inMathed()) {
1183 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
1184 cap::pasteParagraphList(bv->cursor(), repl_buffer.paragraphs(),
1185 repl_buffer.params().documentClassPtr(),
1186 bv->buffer().errorList("Paste"));
1187 } else {
1188 odocstringstream ods;
1189 OutputParams runparams(&repl_buffer.params().encoding());
1190 runparams.nice = false;
1191 runparams.flavor = OutputParams::LATEX;
1192 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
1193 runparams.dryrun = true;
1194 TexRow texrow;
1195 TeXOnePar(repl_buffer, repl_buffer.text(),
1196 repl_buffer.paragraphs().begin(), ods, texrow, runparams);
1197 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
1198 docstring repl_latex = ods.str();
1199 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
1200 string s;
1201 regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
1202 regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
1203 repl_latex = from_utf8(s);
1204 LYXERR(Debug::FIND, "Replacing by niceInsert()ing latex: '" << repl_latex << "'");
1205 bv->cursor().niceInsert(repl_latex);
1207 bv->putSelectionAt(cur, repl_buffer.paragraphs().begin()->size(), ! opt.forward);
1208 bv->message(_("Match found and replaced !"));
1209 } else
1210 LASSERT(false, /**/);
1211 // dispatch(FuncRequest(LFUN_SELF_INSERT, opt.replace));
1214 return true;
1218 void findAdv(BufferView * bv, FuncRequest const & ev)
1220 if (!bv || ev.action != LFUN_WORD_FINDADV)
1221 return;
1223 FindAndReplaceOptions opt;
1224 istringstream iss(to_utf8(ev.argument()));
1225 iss >> opt;
1226 findAdv(bv, opt);
1230 ostringstream & operator<<(ostringstream & os, lyx::FindAndReplaceOptions const & opt)
1232 os << to_utf8(opt.search) << "\nEOSS\n"
1233 << opt.casesensitive << ' '
1234 << opt.matchword << ' '
1235 << opt.forward << ' '
1236 << opt.expandmacros << ' '
1237 << opt.ignoreformat << ' '
1238 << opt.regexp << ' '
1239 << to_utf8(opt.replace) << "\nEOSS\n"
1240 << opt.keep_case;
1242 LYXERR(Debug::FIND, "built: " << os.str());
1244 return os;
1247 istringstream & operator>>(istringstream & is, lyx::FindAndReplaceOptions & opt)
1249 LYXERR(Debug::FIND, "parsing");
1250 string s;
1251 string line;
1252 getline(is, line);
1253 while (line != "EOSS") {
1254 if (! s.empty())
1255 s = s + "\n";
1256 s = s + line;
1257 if (is.eof()) // Tolerate malformed request
1258 break;
1259 getline(is, line);
1261 LYXERR(Debug::FIND, "searching for: '" << s << "'");
1262 opt.search = from_utf8(s);
1263 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.regexp;
1264 is.get(); // Waste space before replace string
1265 s = "";
1266 getline(is, line);
1267 while (line != "EOSS") {
1268 if (! s.empty())
1269 s = s + "\n";
1270 s = s + line;
1271 if (is.eof()) // Tolerate malformed request
1272 break;
1273 getline(is, line);
1275 is >> opt.keep_case;
1276 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
1277 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.regexp << ' ' << opt.keep_case);
1278 LYXERR(Debug::FIND, "replacing with: '" << s << "'");
1279 opt.replace = from_utf8(s);
1280 return is;
1283 } // lyx namespace