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"
37 #include "frontends/Application.h"
38 #include "frontends/alert.h"
40 #include "mathed/InsetMath.h"
41 #include "mathed/InsetMathHull.h"
42 #include "mathed/MathData.h"
43 #include "mathed/MathStream.h"
44 #include "mathed/MathSupport.h"
46 #include "support/debug.h"
47 #include "support/docstream.h"
48 #include "support/FileName.h"
49 #include "support/gettext.h"
50 #include "support/lassert.h"
51 #include "support/lstrings.h"
53 #include "support/regex.h"
54 #include "support/textutils.h"
58 using namespace lyx::support;
63 // Helper class for deciding what should be ignored
68 : ignoreFamily_(false), ignoreSeries_(false),
69 ignoreShape_(false), ignoreUnderline_(false),
70 ignoreMarkUp_(false), ignoreStrikeOut_(false),
71 ignoreSectioning_(false), ignoreFrontMatter_(false),
72 ignoreColor_(false), ignoreLanguage_(false) {}
74 bool getFamily() { return ignoreFamily_; }
76 bool getSeries() { return ignoreSeries_; }
78 bool getShape() { return ignoreShape_; }
80 bool getUnderline() { return ignoreUnderline_; }
82 bool getMarkUp() { return ignoreMarkUp_; }
84 bool getStrikeOut() { return ignoreStrikeOut_; }
86 bool getSectioning() { return ignoreSectioning_; }
88 bool getFrontMatter() { return ignoreFrontMatter_; }
90 bool getColor() { return ignoreColor_; }
92 bool getLanguage() { return ignoreLanguage_; }
94 void setIgnoreFormat(string const & type, bool value);
104 bool ignoreUnderline_;
108 bool ignoreStrikeOut_;
110 bool ignoreSectioning_;
112 bool ignoreFrontMatter_;
116 bool ignoreLanguage_;
120 void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
122 if (type == "color") {
123 ignoreColor_ = value;
125 else if (type == "language") {
126 ignoreLanguage_ = value;
128 else if (type == "sectioning") {
129 ignoreSectioning_ = value;
130 ignoreFrontMatter_ = value;
132 else if (type == "font") {
133 ignoreSeries_ = value;
134 ignoreShape_ = value;
135 ignoreFamily_ = value;
137 else if (type == "series") {
138 ignoreSeries_ = value;
140 else if (type == "shape") {
141 ignoreShape_ = value;
143 else if (type == "family") {
144 ignoreFamily_ = value;
146 else if (type == "markup") {
147 ignoreMarkUp_ = value;
149 else if (type == "underline") {
150 ignoreUnderline_ = value;
152 else if (type == "strike") {
153 ignoreStrikeOut_ = value;
157 // The global variable that can be changed from outside
158 IgnoreFormats ignoreFormats;
161 void setIgnoreFormat(string const & type, bool value)
163 ignoreFormats.setIgnoreFormat(type, value);
169 bool parse_bool(docstring & howto)
174 howto = split(howto, var, ' ');
182 MatchString(docstring const & s, bool cs, bool mw)
183 : str(s), case_sens(cs), whole_words(mw)
186 // returns true if the specified string is at the specified position
187 // del specifies whether deleted strings in ct mode will be considered
188 int operator()(Paragraph const & par, pos_type pos, bool del = true) const
190 return par.find(str, case_sens, whole_words, pos, del);
198 // match whole words only
203 int findForward(DocIterator & cur, MatchString const & match,
204 bool find_del = true)
206 for (; cur; cur.forwardChar())
207 if (cur.inTexted()) {
208 int len = match(cur.paragraph(), cur.pos(), find_del);
216 int findBackwards(DocIterator & cur, MatchString const & match,
217 bool find_del = true)
221 if (cur.inTexted()) {
222 int len = match(cur.paragraph(), cur.pos(), find_del);
231 bool searchAllowed(docstring const & str)
234 frontend::Alert::error(_("Search error"), _("Search string is empty"));
241 bool findOne(BufferView * bv, docstring const & searchstr,
242 bool case_sens, bool whole, bool forward,
243 bool find_del = true, bool check_wrap = false)
245 if (!searchAllowed(searchstr))
248 DocIterator cur = forward
249 ? bv->cursor().selectionEnd()
250 : bv->cursor().selectionBegin();
252 MatchString const match(searchstr, case_sens, whole);
254 int match_len = forward
255 ? findForward(cur, match, find_del)
256 : findBackwards(cur, match, find_del);
259 bv->putSelectionAt(cur, match_len, !forward);
260 else if (check_wrap) {
261 DocIterator cur_orig(bv->cursor());
264 q = _("End of file reached while searching forward.\n"
265 "Continue searching from the beginning?");
267 q = _("Beginning of file reached while searching backward.\n"
268 "Continue searching from the end?");
269 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
270 q, 0, 1, _("&Yes"), _("&No"));
271 if (wrap_answer == 0) {
273 bv->cursor().clear();
274 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
276 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
277 bv->cursor().backwardPos();
279 bv->clearSelection();
280 if (findOne(bv, searchstr, case_sens, whole, forward, find_del, false))
283 bv->cursor().setCursor(cur_orig);
287 return match_len > 0;
291 int replaceAll(BufferView * bv,
292 docstring const & searchstr, docstring const & replacestr,
293 bool case_sens, bool whole)
295 Buffer & buf = bv->buffer();
297 if (!searchAllowed(searchstr) || buf.isReadonly())
300 DocIterator cur_orig(bv->cursor());
302 MatchString const match(searchstr, case_sens, whole);
305 int const rsize = replacestr.size();
306 int const ssize = searchstr.size();
309 cur.setCursor(doc_iterator_begin(&buf));
310 int match_len = findForward(cur, match, false);
311 while (match_len > 0) {
312 // Backup current cursor position and font.
313 pos_type const pos = cur.pos();
314 Font const font = cur.paragraph().getFontSettings(buf.params(), pos);
316 int striked = ssize -
317 cur.paragraph().eraseChars(pos, pos + match_len,
318 buf.params().track_changes);
319 cur.paragraph().insert(pos, replacestr, font,
320 Change(buf.params().track_changes
322 : Change::UNCHANGED));
323 for (int i = 0; i < rsize + striked; ++i)
326 match_len = findForward(cur, match, false);
329 bv->putSelectionAt(doc_iterator_begin(&buf), 0, false);
331 cur_orig.fixIfBroken();
332 bv->setCursor(cur_orig);
338 // the idea here is that we are going to replace the string that
339 // is selected IF it is the search string.
340 // if there is a selection, but it is not the search string, then
341 // we basically ignore it. (FIXME We ought to replace only within
343 // if there is no selection, then:
344 // (i) if some search string has been provided, then we find it.
345 // (think of how the dialog works when you hit "replace" the
347 // (ii) if no search string has been provided, then we treat the
348 // word the cursor is in as the search string. (why? i have no
349 // idea.) but this only works in text?
351 // returns the number of replacements made (one, if any) and
352 // whether anything at all was done.
353 pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
354 docstring const & replacestr, bool case_sens,
355 bool whole, bool forward, bool findnext)
357 Cursor & cur = bv->cursor();
358 if (!cur.selection()) {
359 // no selection, non-empty search string: find it
360 if (!searchstr.empty()) {
361 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
362 return make_pair(found, 0);
364 // empty search string
367 return make_pair(false, 0);
368 // select current word and treat it as the search string.
369 // This causes a minor bug as undo will restore this selection,
370 // which the user did not create (#8986).
371 cur.innerText()->selectWord(cur, WHOLE_WORD);
372 searchstr = cur.selectionAsString(false);
375 // if we still don't have a search string, report the error
377 if (!searchAllowed(searchstr))
378 return make_pair(false, 0);
380 bool have_selection = cur.selection();
381 docstring const selected = cur.selectionAsString(false);
384 ? searchstr == selected
385 : compare_no_case(searchstr, selected) == 0;
387 // no selection or current selection is not search word:
388 // just find the search word
389 if (!have_selection || !match) {
390 bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
391 return make_pair(found, 0);
394 // we're now actually ready to replace. if the buffer is
395 // read-only, we can't, though.
396 if (bv->buffer().isReadonly())
397 return make_pair(false, 0);
399 cap::replaceSelectionWithString(cur, replacestr);
401 cur.pos() += replacestr.length();
402 LASSERT(cur.pos() <= cur.lastpos(),
403 cur.pos() = cur.lastpos());
406 findOne(bv, searchstr, case_sens, whole, forward, false, findnext);
408 return make_pair(true, 1);
414 docstring const find2string(docstring const & search,
415 bool casesensitive, bool matchword, bool forward)
419 << int(casesensitive) << ' '
420 << int(matchword) << ' '
426 docstring const replace2string(docstring const & replace,
427 docstring const & search,
428 bool casesensitive, bool matchword,
429 bool all, bool forward, bool findnext)
432 ss << replace << '\n'
434 << int(casesensitive) << ' '
435 << int(matchword) << ' '
437 << int(forward) << ' '
443 bool lyxfind(BufferView * bv, FuncRequest const & ev)
445 if (!bv || ev.action() != LFUN_WORD_FIND)
448 //lyxerr << "find called, cmd: " << ev << endl;
450 // data is of the form
452 // <casesensitive> <matchword> <forward>"
454 docstring howto = split(ev.argument(), search, '\n');
456 bool casesensitive = parse_bool(howto);
457 bool matchword = parse_bool(howto);
458 bool forward = parse_bool(howto);
460 return findOne(bv, search, casesensitive, matchword, forward, true, true);
464 bool lyxreplace(BufferView * bv,
465 FuncRequest const & ev, bool has_deleted)
467 if (!bv || ev.action() != LFUN_WORD_REPLACE)
470 // data is of the form
473 // <casesensitive> <matchword> <all> <forward> <findnext>"
476 docstring howto = split(ev.argument(), rplc, '\n');
477 howto = split(howto, search, '\n');
479 bool casesensitive = parse_bool(howto);
480 bool matchword = parse_bool(howto);
481 bool all = parse_bool(howto);
482 bool forward = parse_bool(howto);
483 bool findnext = howto.empty() ? true : parse_bool(howto);
488 int replace_count = 0;
490 replace_count = replaceAll(bv, search, rplc, casesensitive, matchword);
491 update = replace_count > 0;
494 replaceOne(bv, search, rplc, casesensitive, matchword, forward, findnext);
496 replace_count = rv.second;
499 Buffer const & buf = bv->buffer();
501 // emit message signal.
502 buf.message(_("String not found."));
504 if (replace_count == 0) {
505 buf.message(_("String found."));
506 } else if (replace_count == 1) {
507 buf.message(_("String has been replaced."));
509 docstring const str =
510 bformat(_("%1$d strings have been replaced."), replace_count);
514 } else if (findnext) {
515 // if we have deleted characters, we do not replace at all, but
516 // rather search for the next occurence
517 if (findOne(bv, search, casesensitive, matchword, forward, true, findnext))
520 bv->message(_("String not found."));
526 bool findNextChange(BufferView * bv, Cursor & cur, bool const check_wrap)
528 for (; cur; cur.forwardPos())
529 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
533 DocIterator cur_orig(bv->cursor());
534 docstring q = _("End of file reached while searching forward.\n"
535 "Continue searching from the beginning?");
536 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
537 q, 0, 1, _("&Yes"), _("&No"));
538 if (wrap_answer == 0) {
539 bv->cursor().clear();
540 bv->cursor().push_back(CursorSlice(bv->buffer().inset()));
541 bv->clearSelection();
542 cur.setCursor(bv->cursor().selectionBegin());
543 if (findNextChange(bv, cur, false))
546 bv->cursor().setCursor(cur_orig);
553 bool findPreviousChange(BufferView * bv, Cursor & cur, bool const check_wrap)
555 for (cur.backwardPos(); cur; cur.backwardPos()) {
556 if (cur.inTexted() && cur.paragraph().isChanged(cur.pos()))
561 DocIterator cur_orig(bv->cursor());
562 docstring q = _("Beginning of file reached while searching backward.\n"
563 "Continue searching from the end?");
564 int wrap_answer = frontend::Alert::prompt(_("Wrap search?"),
565 q, 0, 1, _("&Yes"), _("&No"));
566 if (wrap_answer == 0) {
567 bv->cursor().setCursor(doc_iterator_end(&bv->buffer()));
568 bv->cursor().backwardPos();
569 bv->clearSelection();
570 cur.setCursor(bv->cursor().selectionBegin());
571 if (findPreviousChange(bv, cur, false))
574 bv->cursor().setCursor(cur_orig);
581 bool selectChange(Cursor & cur, bool forward)
583 if (!cur.inTexted() || !cur.paragraph().isChanged(cur.pos()))
585 Change ch = cur.paragraph().lookupChange(cur.pos());
587 CursorSlice tip1 = cur.top();
588 for (; tip1.pit() < tip1.lastpit() || tip1.pos() < tip1.lastpos(); tip1.forwardPos()) {
589 Change ch2 = tip1.paragraph().lookupChange(tip1.pos());
590 if (!ch2.isSimilarTo(ch))
593 CursorSlice tip2 = cur.top();
594 for (; tip2.pit() > 0 || tip2.pos() > 0;) {
596 Change ch2 = tip2.paragraph().lookupChange(tip2.pos());
597 if (!ch2.isSimilarTo(ch)) {
598 // take a step forward to correctly set the selection
606 cur.bv().mouseSetCursor(cur, false);
608 cur.bv().mouseSetCursor(cur, true);
616 bool findChange(BufferView * bv, bool forward)
619 cur.setCursor(forward ? bv->cursor().selectionEnd()
620 : bv->cursor().selectionBegin());
621 forward ? findNextChange(bv, cur, true) : findPreviousChange(bv, cur, true);
622 return selectChange(cur, forward);
627 bool findNextChange(BufferView * bv)
629 return findChange(bv, true);
633 bool findPreviousChange(BufferView * bv)
635 return findChange(bv, false);
642 typedef vector<pair<string, string> > Escapes;
644 /// A map of symbols and their escaped equivalent needed within a regex.
645 /// @note Beware of order
646 Escapes const & get_regexp_escapes()
648 typedef std::pair<std::string, std::string> P;
650 static Escapes escape_map;
651 if (escape_map.empty()) {
652 escape_map.push_back(P("$", "_x_$"));
653 escape_map.push_back(P("{", "_x_{"));
654 escape_map.push_back(P("}", "_x_}"));
655 escape_map.push_back(P("[", "_x_["));
656 escape_map.push_back(P("]", "_x_]"));
657 escape_map.push_back(P("(", "_x_("));
658 escape_map.push_back(P(")", "_x_)"));
659 escape_map.push_back(P("+", "_x_+"));
660 escape_map.push_back(P("*", "_x_*"));
661 escape_map.push_back(P(".", "_x_."));
662 escape_map.push_back(P("\\", "(?:\\\\|\\\\backslash)"));
663 escape_map.push_back(P("~", "(?:\\\\textasciitilde|\\\\sim)"));
664 escape_map.push_back(P("^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
665 escape_map.push_back(P("_x_", "\\"));
670 /// A map of lyx escaped strings and their unescaped equivalent.
671 Escapes const & get_lyx_unescapes()
673 typedef std::pair<std::string, std::string> P;
675 static Escapes escape_map;
676 if (escape_map.empty()) {
677 escape_map.push_back(P("\\%", "%"));
678 escape_map.push_back(P("\\mathcircumflex ", "^"));
679 escape_map.push_back(P("\\mathcircumflex", "^"));
680 escape_map.push_back(P("\\backslash ", "\\"));
681 escape_map.push_back(P("\\backslash", "\\"));
682 escape_map.push_back(P("\\\\{", "_x_<"));
683 escape_map.push_back(P("\\\\}", "_x_>"));
684 escape_map.push_back(P("\\sim ", "~"));
685 escape_map.push_back(P("\\sim", "~"));
690 /// A map of escapes turning a regexp matching text to one matching latex.
691 Escapes const & get_regexp_latex_escapes()
693 typedef std::pair<std::string, std::string> P;
695 static Escapes escape_map;
696 if (escape_map.empty()) {
697 escape_map.push_back(P("\\\\", "(?:\\\\\\\\|\\\\backslash|\\\\textbackslash\\{\\}|\\\\textbackslash)"));
698 escape_map.push_back(P("(<?!\\\\\\\\textbackslash)\\{", "\\\\\\{"));
699 escape_map.push_back(P("(<?!\\\\\\\\textbackslash\\\\\\{)\\}", "\\\\\\}"));
700 escape_map.push_back(P("\\[", "\\{\\[\\}"));
701 escape_map.push_back(P("\\]", "\\{\\]\\}"));
702 escape_map.push_back(P("\\^", "(?:\\^|\\\\textasciicircum\\{\\}|\\\\textasciicircum|\\\\mathcircumflex)"));
703 escape_map.push_back(P("%", "\\\\\\%"));
704 escape_map.push_back(P("#", "\\\\#"));
709 /** @todo Probably the maps need to be migrated to regexps, in order to distinguish if
710 ** the found occurrence were escaped.
712 string apply_escapes(string s, Escapes const & escape_map)
714 LYXERR(Debug::FIND, "Escaping: '" << s << "'");
715 Escapes::const_iterator it;
716 for (it = escape_map.begin(); it != escape_map.end(); ++it) {
717 // LYXERR(Debug::FIND, "Escaping " << it->first << " as " << it->second);
718 unsigned int pos = 0;
719 while (pos < s.length() && (pos = s.find(it->first, pos)) < s.length()) {
720 s.replace(pos, it->first.length(), it->second);
721 LYXERR(Debug::FIND, "After escape: " << s);
722 pos += it->second.length();
723 // LYXERR(Debug::FIND, "pos: " << pos);
726 LYXERR(Debug::FIND, "Escaped : '" << s << "'");
731 /// Within \regexp{} apply get_lyx_unescapes() only (i.e., preserve regexp semantics of the string),
732 /// while outside apply get_lyx_unescapes()+get_regexp_escapes().
733 /// If match_latex is true, then apply regexp_latex_escapes() to \regexp{} contents as well.
734 string escape_for_regex(string s, bool match_latex)
737 while (pos < s.size()) {
738 size_t new_pos = s.find("\\regexp{", pos);
739 if (new_pos == string::npos)
743 LYXERR(Debug::FIND, "new_pos: " << new_pos);
744 t = apply_escapes(s.substr(pos, new_pos - pos), get_lyx_unescapes());
745 LYXERR(Debug::FIND, "t [lyx]: " << t);
746 t = apply_escapes(t, get_regexp_escapes());
747 LYXERR(Debug::FIND, "t [rxp]: " << t);
748 s.replace(pos, new_pos - pos, t);
749 new_pos = pos + t.size();
750 LYXERR(Debug::FIND, "Regexp after escaping: " << s);
751 LYXERR(Debug::FIND, "new_pos: " << new_pos);
752 if (new_pos == s.size())
755 // Might fail if \\endregexp{} is preceeded by unexpected stuff (weird escapes)
756 size_t end_pos = s.find("\\endregexp{}}", new_pos + 8);
757 LYXERR(Debug::FIND, "end_pos: " << end_pos);
758 t = s.substr(new_pos + 8, end_pos - (new_pos + 8));
759 LYXERR(Debug::FIND, "t in regexp : " << t);
760 t = apply_escapes(t, get_lyx_unescapes());
761 LYXERR(Debug::FIND, "t in regexp [lyx]: " << t);
763 t = apply_escapes(t, get_regexp_latex_escapes());
764 LYXERR(Debug::FIND, "t in regexp [ltx]: " << t);
766 if (end_pos == s.size()) {
767 s.replace(new_pos, end_pos - new_pos, t);
768 LYXERR(Debug::FIND, "Regexp after \\regexp{} removal: " << s);
771 s.replace(new_pos, end_pos + 13 - new_pos, t);
772 LYXERR(Debug::FIND, "Regexp after \\regexp{...\\endregexp{}} removal: " << s);
773 pos = new_pos + t.size();
774 LYXERR(Debug::FIND, "pos: " << pos);
780 /// Wrapper for lyx::regex_replace with simpler interface
781 bool regex_replace(string const & s, string & t, string const & searchstr,
782 string const & replacestr)
784 lyx::regex e(searchstr, regex_constants::ECMAScript);
786 ostream_iterator<char, char> it(oss);
787 lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
788 // tolerate t and s be references to the same variable
789 bool rv = (s != oss.str());
795 /** Checks if supplied string segment is well-formed from the standpoint of matching open-closed braces.
797 ** Verify that closed braces exactly match open braces. This avoids that, for example,
798 ** \frac{.*}{x} matches \frac{x+\frac{y}{x}}{z} with .* being 'x+\frac{y'.
801 ** Number of open braces that must remain open at the end for the verification to succeed.
803 bool braces_match(string::const_iterator const & beg,
804 string::const_iterator const & end,
808 string::const_iterator it = beg;
809 LYXERR(Debug::FIND, "Checking " << unmatched << " unmatched braces in '" << string(beg, end) << "'");
810 for (; it != end; ++it) {
811 // Skip escaped braces in the count
816 } else if (*it == '{') {
818 } else if (*it == '}') {
819 if (open_pars == 0) {
820 LYXERR(Debug::FIND, "Found unmatched closed brace");
826 if (open_pars != unmatched) {
827 LYXERR(Debug::FIND, "Found " << open_pars
828 << " instead of " << unmatched
829 << " unmatched open braces at the end of count");
832 LYXERR(Debug::FIND, "Braces match as expected");
842 MatchResult(): match_len(0),match2end(0), pos(0) {};
845 /** The class performing a match between a position in the document and the FindAdvOptions.
847 class MatchStringAdv {
849 MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt);
851 /** Tests if text starting at the supplied position matches with the one provided to the MatchStringAdv
852 ** constructor as opt.search, under the opt.* options settings.
855 ** If set, then match is searched only against beginning of text starting at cur.
856 ** If unset, then match is searched anywhere in text starting at cur.
859 ** The length of the matching text, or zero if no match was found.
861 MatchResult operator()(DocIterator const & cur, int len = -1, bool at_begin = true) const;
866 /// first buffer on which search was started
867 lyx::Buffer * const p_first_buf;
869 FindAndReplaceOptions const & opt;
872 /// Auxiliary find method (does not account for opt.matchword)
873 MatchResult findAux(DocIterator const & cur, int len = -1, bool at_begin = true) const;
875 /** Normalize a stringified or latexified LyX paragraph.
879 ** <li>if search is not casesensitive, then lowercase the string;
880 ** <li>remove any newline at begin or end of the string;
881 ** <li>replace any newline in the middle of the string with a simple space;
882 ** <li>remove stale empty styles and environments, like \emph{} and \textbf{}.
885 ** @todo Normalization should also expand macros, if the corresponding
886 ** search option was checked.
888 string normalize(docstring const & s, bool hack_braces) const;
889 // normalized string to search
890 string par_as_string;
891 // regular expression to use for searching
893 // same as regexp, but prefixed with a ".*?"
895 // leading format material as string
896 string lead_as_string;
897 // par_as_string after removal of lead_as_string
898 string par_as_string_nolead;
899 // unmatched open braces in the search string/regexp
901 // number of (.*?) subexpressions added at end of search regexp for closing
902 // environments, math mode, styles, etc...
904 // Are we searching with regular expressions ?
909 static docstring buffer_to_latex(Buffer & buffer)
911 //OutputParams runparams(&buffer.params().encoding());
912 OutputParams runparams(encodings.fromLyXName("utf8"));
913 odocstringstream ods;
915 runparams.nice = true;
916 runparams.flavor = OutputParams::XETEX;
917 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
918 // No side effect of file copying and image conversion
919 runparams.dryrun = true;
920 runparams.for_search = true;
921 pit_type const endpit = buffer.paragraphs().size();
922 for (pit_type pit = 0; pit != endpit; ++pit) {
923 TeXOnePar(buffer, buffer.text(), pit, os, runparams);
924 LYXERR(Debug::FIND, "searchString up to here: " << ods.str());
930 static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions const & opt)
933 if (!opt.ignoreformat) {
934 str = buffer_to_latex(buffer);
936 // OutputParams runparams(&buffer.params().encoding());
937 OutputParams runparams(encodings.fromLyXName("utf8"));
938 runparams.nice = true;
939 runparams.flavor = OutputParams::XETEX;
940 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
941 runparams.dryrun = true;
942 runparams.for_search = true;
943 for (pos_type pit = pos_type(0); pit < (pos_type)buffer.paragraphs().size(); ++pit) {
944 Paragraph const & par = buffer.paragraphs().at(pit);
945 LYXERR(Debug::FIND, "Adding to search string: '"
946 << par.asString(pos_type(0), par.size(),
947 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
950 str += par.asString(pos_type(0), par.size(),
951 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
959 /// Return separation pos between the leading material and the rest
960 static size_t identifyLeading(string const & s)
963 // @TODO Support \item[text]
964 // Kornel: Added textsl, textsf, textit, texttt and noun
965 // + allow to search for colored text too
966 while (regex_replace(t, t, REGEX_BOS "\\\\(((footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|emph|noun|minisec|text(bf|md|sl|sf|it|tt))|((textcolor|foreignlanguage|latexenvironment)\\{[a-z]+\\*?\\})|(u|uu)line|(s|x)out|uwave)|((sub)?(((sub)?section)|paragraph)|part|chapter)\\*?)\\{", "")
967 || regex_replace(t, t, REGEX_BOS "\\$", "")
968 || regex_replace(t, t, REGEX_BOS "\\\\\\[", "")
969 || regex_replace(t, t, REGEX_BOS " ?\\\\item\\{[a-z]+\\}", "")
970 || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
972 LYXERR(Debug::FIND, " after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
977 * Given a latexified string, retrieve some handled features
978 * The features of the regex will later be compared with the features
979 * of the searched text. If the regex features are not a
980 * subset of the analized, then, in not format ignoring search
981 * we can early stop the search in the relevant inset.
983 typedef map<string, bool> Features;
985 static Features identifyFeatures(string const & s)
987 static regex const feature("\\\\(([a-zA-Z]+(\\{([a-z]+\\*?)\\}|\\*)?))\\{");
988 static regex const valid("^("
990 "(footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge|"
991 "emph|noun|text(bf|md|sl|sf|it|tt)|"
992 "(textcolor|foreignlanguage|item|listitem|latexenvironment)\\{[a-z]+\\*?\\})|"
993 "(u|uu)line|(s|x)out|uwave|"
994 "(sub|extra)?title|author|subject|publishers|dedication|(upper|lower)titleback|lyx(right)?address)|"
995 "((sub)?(((sub)?section)|paragraph)|part|chapter|lyxslide)\\*?)$");
1000 for (sregex_iterator it(s.begin(), s.end(), feature), end; it != end; ++it) {
1003 if (sub.str(1).compare("regexp") == 0) {
1007 string token = sub.str(1);
1009 if (regex_match(token, sub2, valid)) {
1017 if (sub.str(1).compare("endregexp") == 0) {
1027 * defines values features of a key "\\[a-z]+{"
1032 /* Char type with content discarded
1033 * like \hspace{1cm} */
1035 /* Char, like \backslash */
1037 /* \part, \section*, ... */
1039 /* title, author etc */
1041 /* \foreignlanguage{ngerman}, ... */
1044 * to discard language in content */
1047 /* \begin{eqnarray}...\end{eqnarray}, ... $...$ */
1049 /* fonts, colors, markups, ... */
1051 /* footnotesize, ... large, ...
1052 * Ignore all of them */
1055 /* inputencoding, ...
1056 * Discard also content, because they do not help in search */
1059 * like remove, but also all arguments */
1061 /* item, listitem */
1063 /* tex, latex, ... like isChar */
1065 /* like \lettrine[lines=5]{}{} */
1067 /* End of arguments marker for lettrine,
1068 * so that they can be ignored */
1078 parenthesiscount(1),
1082 KeyInfo(KeyType type, int parcount, bool disable)
1088 parenthesiscount(parcount),
1097 int parenthesiscount;
1099 bool used; /* by pattern */
1104 Border(int l=0, int u=0) : low(l), upper(u) {};
1109 #define MAXOPENED 30
1111 bool isPatternString_;
1113 explicit Intervall(bool isPattern, string const & p) :
1114 isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
1115 hasTitle(false), langcount(0)
1123 static vector<Border> borders;
1124 int depts[MAXOPENED];
1125 int closes[MAXOPENED];
1126 int actualdeptindex;
1127 int previousNotIgnored(int);
1128 int nextNotIgnored(int);
1129 void handleOpenP(int i);
1130 void handleCloseP(int i, bool closingAllowed);
1131 void resetOpenedP(int openPos);
1132 void addIntervall(int upper);
1133 void addIntervall(int low, int upper); /* if explicit */
1134 void removeAccents();
1135 void setForDefaultLang(KeyInfo const & defLang);
1136 int findclosing(int start, int end, char up, char down, int repeat);
1137 void handleParentheses(int lastpos, bool closingAllowed);
1139 int langcount; // Number of disabled language specs up to current position in actual interval
1140 int isOpeningPar(int pos);
1142 void output(ostringstream &os, int lastpos);
1143 // string show(int lastpos);
1146 vector<Border> Intervall::borders = vector<Border>(30);
1148 int Intervall::isOpeningPar(int pos)
1150 if ((pos < 0) || (size_t(pos) >= par.size()))
1152 if (par[pos] != '{')
1154 if (size_t(pos) + 2 >= par.size())
1156 if (par[pos+2] != '}')
1158 if (par[pos+1] == '[' || par[pos+1] == ']')
1163 void Intervall::setForDefaultLang(KeyInfo const & defLang)
1165 // Enable the use of first token again
1166 if (ignoreidx >= 0) {
1167 int value = defLang._tokenstart + defLang._tokensize;
1169 if (borders[0].low < value)
1170 borders[0].low = value;
1171 if (borders[0].upper < value)
1172 borders[0].upper = value;
1177 static void checkDepthIndex(int val)
1179 static int maxdepthidx = MAXOPENED-2;
1180 static int lastmaxdepth = 0;
1181 if (val > lastmaxdepth) {
1182 LYXERR(Debug::INFO, "Depth reached " << val);
1185 if (val > maxdepthidx) {
1187 LYXERR(Debug::INFO, "maxdepthidx now " << val);
1192 // Not needed, because borders are now dynamically expanded
1193 static void checkIgnoreIdx(int val)
1195 static int lastmaxignore = -1;
1196 if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
1197 LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
1198 lastmaxignore = val;
1204 * Expand the region of ignored parts of the input latex string
1205 * The region is only relevant in output()
1207 void Intervall::addIntervall(int low, int upper)
1210 if (low == upper) return;
1211 for (idx = ignoreidx+1; idx > 0; --idx) {
1212 if (low > borders[idx-1].upper) {
1216 Border br(low, upper);
1217 if (idx > ignoreidx) {
1218 if (borders.size() <= size_t(idx)) {
1219 borders.push_back(br);
1225 // checkIgnoreIdx(ignoreidx);
1229 // Expand only if one of the new bound is inside the interwall
1230 // We know here that br.low > borders[idx-1].upper
1231 if (br.upper < borders[idx].low) {
1232 // We have to insert at this pos
1233 if (size_t(ignoreidx+1) >= borders.size()) {
1234 borders.push_back(borders[ignoreidx]);
1237 borders[ignoreidx+1] = borders[ignoreidx];
1239 for (int i = ignoreidx; i > idx; --i) {
1240 borders[i] = borders[i-1];
1244 // checkIgnoreIdx(ignoreidx);
1247 // Here we know, that we are overlapping
1248 if (br.low > borders[idx].low)
1249 br.low = borders[idx].low;
1250 // check what has to be concatenated
1252 for (int i = idx; i <= ignoreidx; i++) {
1253 if (br.upper >= borders[i].low) {
1255 if (br.upper < borders[i].upper)
1256 br.upper = borders[i].upper;
1262 // count should be >= 1 here
1265 for (int i = idx + count; i <= ignoreidx; i++) {
1266 borders[i-count+1] = borders[i];
1268 ignoreidx -= count - 1;
1274 typedef map<string, string> AccentsMap;
1275 static AccentsMap accents = map<string, string>();
1277 static void buildaccent(string n, string param, string values)
1281 const char delim = '|';
1282 while (getline(s, name, delim)) {
1284 for (char c : param) {
1285 string key = name + "{" + c + "}";
1286 // get the corresponding utf8-value
1287 if ((values[start] & 0xc0) != 0xc0) {
1288 // should not happen, utf8 encoding starts at least with 11xxxxxx
1289 // but value for '\dot{i}' is 'i', which is ascii
1290 if ((values[start] & 0x80) == 0) {
1292 accents[key] = values.substr(start, 1);
1293 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1298 for (int j = 1; ;j++) {
1299 if (start + j >= values.size()) {
1300 accents[key] = values.substr(start, j);
1301 start = values.size() - 1;
1304 else if ((values[start+j] & 0xc0) != 0x80) {
1305 // This is the first byte of following utf8 char
1306 accents[key] = values.substr(start, j);
1308 // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
1316 static void buildAccentsMap()
1318 accents["imath"] = "ı";
1320 accents["jmath"] = "ȷ";
1321 accents["lyxmathsym{ß}"] = "ß";
1322 accents["text{ß}"] = "ß";
1323 accents["ddot{\\imath}"] = "ï";
1324 buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
1325 "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ"); // umlaut
1326 buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
1327 "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ"); // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
1328 accents["acute{\\imath}"] = "í";
1329 buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
1330 "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
1331 buildaccent("dacute|H|h", "oOuU", "őŐűŰ"); // double acute
1332 buildaccent("mathring|r", "aAuUwy",
1334 accents["check{\\imath}"] = "ǐ";
1335 accents["check{\\jmath}"] = "ǰ";
1336 buildaccent("check|v", "cCdDaAeEiIoOuUgGkKhHlLnNrRsSTtzZ",
1337 "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ"); // caron
1338 accents["hat{\\imath}"] = "î";
1339 accents["hat{\\jmath}"] = "ĵ";
1340 buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
1341 "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ"); // circ
1342 accents["bar{\\imath}"] = "ī";
1343 buildaccent("bar|=", "aAeEiIoOuUyY",
1344 "āĀēĒīĪōŌūŪȳȲ"); // macron
1345 accents["tilde{\\imath}"] = "ĩ";
1346 buildaccent("tilde", "aAeEiInNoOuUvVyY",
1347 "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ"); // tilde
1348 accents["breve{\\imath}"] = "ĭ";
1349 buildaccent("breve|u", "aAeEgGiIoOuU",
1350 "ăĂĕĔğĞĭĬŏŎŭŬ"); // breve
1351 accents["grave{\\imath}"] = "ì";
1352 buildaccent("grave|`", "aAeEiIoOuUnNwWyY",
1353 "àÀèÈìÌòÒùÙǹǸẁẀỳỲ"); // grave
1354 buildaccent("subdot|d", "BbDdHhKkLlMmNnRrSsTtVvWwZzAaEeIiOoUuYy",
1355 "ḄḅḌḍḤḥḲḳḶḷṂṃṆṇṚṛṢṣṬṭṾṿẈẉẒẓẠạẸẹỊịỌọỤụỴỵ"); // dot below
1356 buildaccent("ogonek|k", "AaEeIiUuOo",
1357 "ĄąĘęĮįŲųǪǫ"); // ogonek
1358 buildaccent("cedilla|c", "CcGgKkLlNnRrSsTtEeDdHh",
1359 "ÇçĢĢĶķĻļŅņŖŗŞşŢţȨȩḐḑḨḩ"); // cedilla
1360 buildaccent("subring|textsubring", "Aa",
1362 buildaccent("subhat|textsubcircum", "DdEeLlNnTtUu",
1363 "ḒḓḘḙḼḽṊṋṰṱṶṷ"); // subcircum
1364 buildaccent("subtilde|textsubtilde", "EeIiUu",
1365 "ḚḛḬḭṴṵ"); // subtilde
1366 accents["dgrave{\\imath}"] = "ȉ";
1367 accents["textdoublegrave{\\i}"] = "ȉ";
1368 buildaccent("dgrave|textdoublegrave", "AaEeIiOoRrUu",
1369 "ȀȁȄȅȈȉȌȍȐȑȔȕ"); // double grave
1370 accents["rcap{\\imath}"] = "ȉ";
1371 accents["textroundcap{\\i}"] = "ȉ";
1372 buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
1373 "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
1374 buildaccent("slashed", "oO",
1379 * Created accents in math or regexp environment
1380 * are macros, but we need the utf8 equivalent
1382 void Intervall::removeAccents()
1384 if (accents.empty())
1386 static regex const accre("\\\\(([\\S]|grave|breve|lyxmathsym|text|ddot|dot|acute|dacute|mathring|check|hat|bar|tilde|subdot|ogonek|cedilla|subring|textsubring|subhat|textsubcircum|subtilde|textsubtilde|dgrave|textdoublegrave|rcap|textroundcap|slashed)\\{[^\\{\\}]+\\}|(i|imath|jmath)(?![a-zA-Z]))");
1388 for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
1390 string key = sub.str(1);
1391 if (accents.find(key) != accents.end()) {
1392 string val = accents[key];
1393 size_t pos = sub.position(size_t(0));
1394 for (size_t i = 0; i < val.size(); i++) {
1395 par[pos+i] = val[i];
1397 addIntervall(pos+val.size(), pos + sub.str(0).size());
1398 for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
1399 // remove traces of any remaining chars
1404 LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
1409 void Intervall::handleOpenP(int i)
1412 depts[actualdeptindex] = i+1;
1413 closes[actualdeptindex] = -1;
1414 checkDepthIndex(actualdeptindex);
1417 void Intervall::handleCloseP(int i, bool closingAllowed)
1419 if (actualdeptindex <= 0) {
1420 if (! closingAllowed)
1421 LYXERR(Debug::FIND, "Bad closing parenthesis in latex"); /* should not happen, but the latex input may be wrong */
1422 // if we are at the very end
1423 addIntervall(i, i+1);
1426 closes[actualdeptindex] = i+1;
1431 void Intervall::resetOpenedP(int openPos)
1433 // Used as initializer for foreignlanguage entry
1434 actualdeptindex = 1;
1435 depts[1] = openPos+1;
1439 int Intervall::previousNotIgnored(int start)
1441 int idx = 0; /* int intervalls */
1442 for (idx = ignoreidx; idx >= 0; --idx) {
1443 if (start > borders[idx].upper)
1445 if (start >= borders[idx].low)
1446 start = borders[idx].low-1;
1451 int Intervall::nextNotIgnored(int start)
1453 int idx = 0; /* int intervalls */
1454 for (idx = 0; idx <= ignoreidx; idx++) {
1455 if (start < borders[idx].low)
1457 if (start < borders[idx].upper)
1458 start = borders[idx].upper;
1463 typedef map<string, KeyInfo> KeysMap;
1464 typedef vector< KeyInfo> Entries;
1465 static KeysMap keys = map<string, KeyInfo>();
1471 Intervall interval_;
1472 void buildKeys(bool);
1473 void buildEntries(bool);
1474 void makeKey(const string &, KeyInfo, bool isPatternString);
1475 void processRegion(int start, int region_end); /* remove {} parts */
1476 void removeHead(KeyInfo const &, int count=0);
1479 LatexInfo(string const & par, bool isPatternString)
1480 : entidx_(-1), interval_(isPatternString, par)
1482 buildKeys(isPatternString);
1483 entries_ = vector<KeyInfo>();
1484 buildEntries(isPatternString);
1488 if (entries_.empty()) {
1491 if (entries_[0].keytype == KeyInfo::isTitle) {
1492 if (! entries_[0].disabled) {
1493 interval_.hasTitle = true;
1494 interval_.titleValue = entries_[0].head;
1497 interval_.hasTitle = false;
1498 interval_.titleValue = "";
1500 removeHead(entries_[0]);
1501 if (entries_.size() > 1)
1510 if (int(entries_.size()) > entidx_) {
1517 bool setNextKey(int idx) {
1518 if ((idx == entidx_) && (entidx_ >= 0)) {
1525 int find(int start, KeyInfo::KeyType keytype) {
1529 while (tmpIdx < int(entries_.size())) {
1530 if (entries_[tmpIdx].keytype == keytype)
1536 int process(ostringstream & os, KeyInfo const & actual);
1537 int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
1538 // string show(int lastpos) { return interval.show(lastpos);};
1539 int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
1540 KeyInfo &getKeyInfo(int keyinfo) {
1541 static KeyInfo invalidInfo = KeyInfo();
1542 if ((keyinfo < 0) || ( keyinfo >= int(entries_.size())))
1545 return entries_[keyinfo];
1547 void setForDefaultLang(KeyInfo &defLang) {interval_.setForDefaultLang(defLang);};
1548 void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
1552 int Intervall::findclosing(int start, int end, char up = '{', char down = '}', int repeat = 1)
1556 for (int i = start; i < end; i += 1 + skip) {
1560 if (c == '\\') skip = 1;
1564 else if (c == down) {
1567 if ((repeat <= 0) || (par[i+1] != up))
1585 vector<MathEntry> entries_;
1590 void insert(string const & wait, size_t start, size_t end) {
1591 MathEntry m = MathEntry();
1593 m.mathStart = start;
1595 m.mathSize = end - start;
1596 entries_.push_back(m);
1598 bool empty() { return entries_.empty(); };
1599 size_t getEndPos() {
1600 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1603 return entries_[actualIdx_].mathEnd;
1605 size_t getStartPos() {
1606 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1607 return 100000; /* definitely enough? */
1609 return entries_[actualIdx_].mathStart;
1611 size_t getFirstPos() {
1613 return getStartPos();
1616 if (entries_.empty() || (actualIdx_ >= entries_.size())) {
1619 return entries_[actualIdx_].mathSize;
1621 void incrEntry() { actualIdx_++; };
1624 void LatexInfo::buildEntries(bool isPatternString)
1626 static regex const rmath("\\$|\\\\\\[|\\\\\\]|\\\\(begin|end)\\{((eqnarray|equation|flalign|gather|multline|align|alignat)\\*?)\\}");
1627 static regex const rkeys("\\$|\\\\\\[|\\\\\\]|\\\\((([a-zA-Z]+\\*?)(\\{([a-z]+\\*?)\\}|=[0-9]+[a-z]+)?))");
1628 static bool disableLanguageOverride = false;
1629 smatch sub, submath;
1630 bool evaluatingRegexp = false;
1632 bool evaluatingMath = false;
1633 bool evaluatingCode = false;
1635 bool evaluatingOptional = false;
1636 size_t optionalEnd = 0;
1639 bool math_end_waiting = false;
1640 size_t math_pos = 10000;
1643 interval_.removeAccents();
1645 for (sregex_iterator itmath(interval_.par.begin(), interval_.par.end(), rmath), end; itmath != end; ++itmath) {
1647 if (math_end_waiting) {
1648 size_t pos = submath.position(size_t(0));
1649 if ((math_end == "$") &&
1650 (submath.str(0) == "$") &&
1651 (interval_.par[pos-1] != '\\')) {
1652 mi.insert("$", math_pos, pos + 1);
1653 math_end_waiting = false;
1655 else if ((math_end == "\\]") &&
1656 (submath.str(0) == "\\]")) {
1657 mi.insert("\\]", math_pos, pos + 2);
1658 math_end_waiting = false;
1660 else if ((submath.str(1).compare("end") == 0) &&
1661 (submath.str(2).compare(math_end) == 0)) {
1662 mi.insert(math_end, math_pos, pos + submath.str(0).length());
1663 math_end_waiting = false;
1669 if (submath.str(1).compare("begin") == 0) {
1670 math_end_waiting = true;
1671 math_end = submath.str(2);
1672 math_pos = submath.position(size_t(0));
1674 else if (submath.str(0).compare("\\[") == 0) {
1675 math_end_waiting = true;
1677 math_pos = submath.position(size_t(0));
1679 else if (submath.str(0) == "$") {
1680 size_t pos = submath.position(size_t(0));
1681 if ((pos == 0) || (interval_.par[pos-1] != '\\')) {
1682 math_end_waiting = true;
1689 // Ignore language if there is math somewhere in pattern-string
1690 if (isPatternString) {
1693 keys["foreignlanguage"].disabled = true;
1694 disableLanguageOverride = true;
1697 disableLanguageOverride = false;
1700 if (disableLanguageOverride) {
1701 keys["foreignlanguage"].disabled = true;
1704 math_pos = mi.getFirstPos();
1705 for (sregex_iterator it(interval_.par.begin(), interval_.par.end(), rkeys), end; it != end; ++it) {
1707 string key = sub.str(3);
1709 if (sub.str(0)[0] == '\\')
1710 key = sub.str(0)[1];
1714 size_t k_pos = sub.position(size_t(0));
1715 if ((k_pos > 0) && (interval_.par[k_pos - 1] == '\\')) {
1716 // Escaped '$', ignoring
1722 if (evaluatingRegexp) {
1723 if (sub.str(1).compare("endregexp") == 0) {
1724 evaluatingRegexp = false;
1725 // found._tokenstart already set
1726 found._dataEnd = sub.position(size_t(0)) + 13;
1727 found._dataStart = found._dataEnd;
1728 found._tokensize = found._dataEnd - found._tokenstart;
1729 found.parenthesiscount = 0;
1730 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1737 if (evaluatingMath) {
1738 if (size_t(sub.position(size_t(0))) < mi.getEndPos())
1740 evaluatingMath = false;
1742 math_pos = mi.getStartPos();
1744 if (keys.find(key) == keys.end()) {
1745 found = KeyInfo(KeyInfo::isStandard, 0, true);
1746 if (isPatternString) {
1747 found.keytype = KeyInfo::isChar;
1748 found.disabled = false;
1755 if (key.compare("regexp") == 0) {
1756 evaluatingRegexp = true;
1757 found._tokenstart = sub.position(size_t(0));
1758 found._tokensize = 0;
1762 // Handle the other params of key
1763 if (found.keytype == KeyInfo::isIgnored)
1765 else if (found.keytype == KeyInfo::isMath) {
1766 if (size_t(sub.position(size_t(0))) == math_pos) {
1768 found._tokenstart = sub.position(size_t(0));
1769 found._tokensize = mi.getSize();
1770 found._dataEnd = found._tokenstart + found._tokensize;
1771 found._dataStart = found._dataEnd;
1772 found.parenthesiscount = 0;
1773 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1774 evaluatingMath = true;
1777 // begin|end of unknown env, discard
1778 // First handle tables
1779 // longtable|tabular
1780 bool discardComment;
1782 found.keytype = KeyInfo::doRemove;
1783 if ((sub.str(5).compare("longtable") == 0) ||
1784 (sub.str(5).compare("tabular") == 0)) {
1785 discardComment = true; /* '%' */
1788 discardComment = false;
1789 static regex const removeArgs("^(multicols|multipar|sectionbox|subsectionbox|tcolorbox)$");
1791 string token = sub.str(5);
1792 if (regex_match(token, sub2, removeArgs)) {
1793 found.keytype = KeyInfo::removeWithArg;
1796 // discard spaces before pos(0)
1797 int pos = sub.position(size_t(0));
1799 for (count = 0; pos - count > 0; count++) {
1800 char c = interval_.par[pos-count-1];
1801 if (discardComment) {
1802 if ((c != ' ') && (c != '%'))
1808 found._tokenstart = pos - count;
1809 if (sub.str(1).compare(0, 5, "begin") == 0) {
1810 size_t pos1 = pos + sub.str(0).length();
1811 if (sub.str(5).compare("cjk") == 0) {
1812 pos1 = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1813 if ((interval_.par[pos1] == '{') && (interval_.par[pos1+1] == '}'))
1815 found.keytype = KeyInfo::isMain;
1816 found._dataStart = pos1;
1817 found._dataEnd = interval_.par.length();
1818 found.disabled = keys["foreignlanguage"].disabled;
1819 found.used = keys["foreignlanguage"].used;
1820 found._tokensize = pos1 - found._tokenstart;
1821 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1824 // Swallow possible optional params
1825 while (interval_.par[pos1] == '[') {
1826 pos1 = interval_.findclosing(pos1+1, interval_.par.length(), '[', ']')+1;
1828 // Swallow also the eventual parameter
1829 if (interval_.par[pos1] == '{') {
1830 found._dataEnd = interval_.findclosing(pos1+1, interval_.par.length()) + 1;
1833 found._dataEnd = pos1;
1835 found._dataStart = found._dataEnd;
1836 found._tokensize = count + found._dataEnd - pos;
1837 found.parenthesiscount = 0;
1838 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1839 found.disabled = true;
1843 // Handle "\end{...}"
1844 found._dataStart = pos + sub.str(0).length();
1845 found._dataEnd = found._dataStart;
1846 found._tokensize = count + found._dataEnd - pos;
1847 found.parenthesiscount = 0;
1848 found.head = interval_.par.substr(found._tokenstart, found._tokensize);
1849 found.disabled = true;
1853 else if (found.keytype != KeyInfo::isRegex) {
1854 found._tokenstart = sub.position(size_t(0));
1855 if (found.parenthesiscount == 0) {
1856 // Probably to be discarded
1857 size_t following_pos = sub.position(size_t(0)) + sub.str(3).length() + 1;
1858 char following = interval_.par[following_pos];
1859 if (following == ' ')
1860 found.head = "\\" + sub.str(3) + " ";
1861 else if (following == '=') {
1862 // like \uldepth=1000pt
1863 found.head = sub.str(0);
1866 found.head = "\\" + key;
1867 found._tokensize = found.head.length();
1868 found._dataEnd = found._tokenstart + found._tokensize;
1869 found._dataStart = found._dataEnd;
1872 int params = found._tokenstart + key.length() + 1;
1873 if (evaluatingOptional) {
1874 if (size_t(found._tokenstart) > optionalEnd) {
1875 evaluatingOptional = false;
1878 found.disabled = true;
1881 int optend = params;
1882 while (interval_.par[optend] == '[') {
1883 // discard optional parameters
1884 optend = interval_.findclosing(optend+1, interval_.par.length(), '[', ']') + 1;
1886 if (optend > params) {
1887 key += interval_.par.substr(params, optend-params);
1888 evaluatingOptional = true;
1889 optionalEnd = optend;
1891 string token = sub.str(5);
1892 int closings = found.parenthesiscount;
1893 if (found.parenthesiscount == 1) {
1894 found.head = "\\" + key + "{";
1896 else if (found.parenthesiscount > 1) {
1898 found.head = sub.str(0) + "{";
1899 closings = found.parenthesiscount - 1;
1902 found.head = "\\" + key + "{";
1905 found._tokensize = found.head.length();
1906 found._dataStart = found._tokenstart + found.head.length();
1907 if (found.keytype == KeyInfo::doRemove) {
1908 int endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1909 found._dataStart = endpar;
1910 found._tokensize = found._dataStart - found._tokenstart;
1913 if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
1914 found._dataStart += 15;
1918 endpos = found._dataStart - 1;
1920 endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
1921 if (found.keytype == KeyInfo::isList) {
1922 // Check if it really is list env
1923 static regex const listre("^([a-z]+)$");
1925 if (!regex_match(token, sub2, listre)) {
1926 // Change the key of this entry. It is not in a list/item environment
1927 found.keytype = KeyInfo::endArguments;
1930 if (found.keytype == KeyInfo::noMain) {
1931 evaluatingCode = true;
1933 codeStart = found._dataStart;
1935 else if (evaluatingCode) {
1936 if (size_t(found._dataStart) > codeEnd)
1937 evaluatingCode = false;
1938 else if (found.keytype == KeyInfo::isMain) {
1939 // Disable this key, treate it as standard
1940 found.keytype = KeyInfo::isStandard;
1941 found.disabled = true;
1942 if ((codeEnd == interval_.par.length()) &&
1943 (found._tokenstart == codeStart)) {
1944 // trickery, because the code inset starts
1945 // with \selectlanguage ...
1947 if (entries_.size() > 1) {
1948 entries_[entries_.size()-1]._dataEnd = codeEnd;
1953 if ((endpos == interval_.par.length()) &&
1954 (found.keytype == KeyInfo::doRemove)) {
1955 // Missing closing => error in latex-input?
1956 // therefore do not delete remaining data
1957 found._dataStart -= 1;
1958 found._dataEnd = found._dataStart;
1961 found._dataEnd = endpos;
1963 if (isPatternString) {
1964 keys[key].used = true;
1967 entries_.push_back(found);
1971 void LatexInfo::makeKey(const string &keysstring, KeyInfo keyI, bool isPatternString)
1973 stringstream s(keysstring);
1975 const char delim = '|';
1976 while (getline(s, key, delim)) {
1977 KeyInfo keyII(keyI);
1978 if (isPatternString) {
1981 else if ( !keys[key].used)
1982 keyII.disabled = true;
1987 void LatexInfo::buildKeys(bool isPatternString)
1990 static bool keysBuilt = false;
1991 if (keysBuilt && !isPatternString) return;
1993 // Known standard keys with 1 parameter.
1994 // Split is done, if not at start of region
1995 makeKey("textsf|textss|texttt", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getFamily()), isPatternString);
1996 makeKey("textbf", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getSeries()), isPatternString);
1997 makeKey("textit|textsc|textsl", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getShape()), isPatternString);
1998 makeKey("uuline|uline|uwave", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getUnderline()), isPatternString);
1999 makeKey("emph|noun", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getMarkUp()), isPatternString);
2000 makeKey("sout|xout", KeyInfo(KeyInfo::isStandard, 1, ignoreFormats.getStrikeOut()), isPatternString);
2002 makeKey("section|subsection|subsubsection|paragraph|subparagraph|minisec",
2003 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2004 makeKey("section*|subsection*|subsubsection*|paragraph*",
2005 KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2006 makeKey("part|part*|chapter|chapter*", KeyInfo(KeyInfo::isSectioning, 1, ignoreFormats.getSectioning()), isPatternString);
2007 makeKey("title|subtitle|author|subject|publishers|dedication|uppertitleback|lowertitleback|extratitle|lyxaddress|lyxrightaddress", KeyInfo(KeyInfo::isTitle, 1, ignoreFormats.getFrontMatter()), isPatternString);
2009 makeKey("regexp", KeyInfo(KeyInfo::isRegex, 1, false), isPatternString);
2011 // Split is done, if not at start of region
2012 makeKey("textcolor", KeyInfo(KeyInfo::isStandard, 2, ignoreFormats.getColor()), isPatternString);
2013 makeKey("latexenvironment", KeyInfo(KeyInfo::isStandard, 2, false), isPatternString);
2015 // Split is done always.
2016 makeKey("foreignlanguage", KeyInfo(KeyInfo::isMain, 2, ignoreFormats.getLanguage()), isPatternString);
2020 makeKey("backslash|textbackslash|slash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2021 makeKey("textasciicircum|textasciitilde", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2022 makeKey("textasciiacute|texemdash", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2023 makeKey("dots|ldots", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2025 makeKey("quad|qquad|hfill|dotfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2026 makeKey("textvisiblespace|nobreakspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2027 makeKey("negthickspace|negmedspace|negthinspace", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2029 // makeKey("enskip|smallskip|medskip|bigskip|vfill", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2030 // Custom space/skip, remove the content (== length value)
2031 makeKey("vspace|vspace*|hspace|hspace*|mspace", KeyInfo(KeyInfo::noContent, 1, false), isPatternString);
2032 // Found in fr/UserGuide.lyx
2033 makeKey("og|fg", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2035 makeKey("textquotedbl|quotesinglbase|lyxarrow", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2036 makeKey("textquotedblleft|textquotedblright", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2037 // Known macros to remove (including their parameter)
2039 makeKey("input|inputencoding|label|ref|index|bibitem", KeyInfo(KeyInfo::doRemove, 1, false), isPatternString);
2040 makeKey("addtocounter|setlength", KeyInfo(KeyInfo::noContent, 2, true), isPatternString);
2041 // handle like standard keys with 1 parameter.
2042 makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
2044 // Ignore deleted text
2045 makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
2046 // but preserve added text
2047 makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
2049 // Macros to remove, but let the parameter survive
2051 makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2053 // Remove language spec from content of these insets
2054 makeKey("code", KeyInfo(KeyInfo::noMain, 1, false), isPatternString);
2056 // Same effect as previous, parameter will survive (because there is no one anyway)
2058 makeKey("noindent|textcompwordmark|maketitle", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2059 // Remove table decorations
2060 makeKey("hline|tabularnewline|toprule|bottomrule|midrule", KeyInfo(KeyInfo::doRemove, 0, true), isPatternString);
2061 // Discard shape-header.
2062 // For footnote or shortcut too, because of lang settings
2063 // and wrong handling if used 'KeyInfo::noMain'
2064 makeKey("circlepar|diamondpar|heartpar|nutpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2065 makeKey("trianglerightpar|hexagonpar|starpar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2066 makeKey("triangleuppar|triangledownpar|droppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2067 makeKey("triangleleftpar|shapepar|dropuppar", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2068 makeKey("hphantom|vphantom|footnote|shortcut|include|includegraphics", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
2069 makeKey("parbox", KeyInfo(KeyInfo::doRemove, 1, true), isPatternString);
2070 // like ('tiny{}' or '\tiny ' ... )
2071 makeKey("footnotesize|tiny|scriptsize|small|large|Large|LARGE|huge|Huge", KeyInfo(KeyInfo::isSize, 0, false), isPatternString);
2073 // Survives, like known character
2074 makeKey("lyx|LyX|latex|LaTeX|latexe|LaTeXe|tex|TeX", KeyInfo(KeyInfo::isChar, 0, false), isPatternString);
2075 makeKey("item|listitem", KeyInfo(KeyInfo::isList, 1, false), isPatternString);
2077 makeKey("begin|end", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2078 makeKey("[|]", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2079 makeKey("$", KeyInfo(KeyInfo::isMath, 1, false), isPatternString);
2081 makeKey("par|uldepth|ULdepth|protect|nobreakdash|medskip|relax", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2082 // Remove RTL/LTR marker
2083 makeKey("l|r|textlr|textfr|textar|beginl|endl", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2084 makeKey("lettrine", KeyInfo(KeyInfo::cleanToStart, 0, true), isPatternString);
2085 makeKey("lyxslide", KeyInfo(KeyInfo::isSectioning, 1, true), isPatternString);
2086 makeKey("endarguments", KeyInfo(KeyInfo::endArguments, 0, true), isPatternString);
2087 makeKey("twocolumn", KeyInfo(KeyInfo::removeWithArg, 2, true), isPatternString);
2088 makeKey("tnotetext|ead|fntext|cortext|address", KeyInfo(KeyInfo::removeWithArg, 0, true), isPatternString);
2089 makeKey("lyxend", KeyInfo(KeyInfo::isStandard, 0, true), isPatternString);
2090 if (isPatternString) {
2091 // Allow the first searched string to rebuild the keys too
2095 // no need to rebuild again
2101 * Keep the list of actual opened parentheses actual
2102 * (e.g. depth == 4 means there are 4 '{' not processed yet)
2104 void Intervall::handleParentheses(int lastpos, bool closingAllowed)
2107 for (int i = depts[actualdeptindex]; i < lastpos; i+= 1 + skip) {
2111 if (c == '\\') skip = 1;
2112 else if (c == '{') {
2115 else if (c == '}') {
2116 handleCloseP(i, closingAllowed);
2122 string Intervall::show(int lastpos)
2124 int idx = 0; /* int intervalls */
2127 for (idx = 0; idx <= ignoreidx; idx++) {
2128 while (i < lastpos) {
2130 if (i <= borders[idx].low) {
2131 if (borders[idx].low > lastpos)
2132 printsize = lastpos - i;
2134 printsize = borders[idx].low - i;
2135 s += par.substr(i, printsize);
2137 if (i >= borders[idx].low)
2138 i = borders[idx].upper;
2141 i = borders[idx].upper;
2147 s += par.substr(i, lastpos-i);
2153 void Intervall::output(ostringstream &os, int lastpos)
2155 // get number of chars to output
2156 int idx = 0; /* int intervalls */
2159 string startTitle = titleValue;
2160 for (idx = 0; idx <= ignoreidx; idx++) {
2162 if (i <= borders[idx].low) {
2164 if (borders[idx].low > lastpos)
2165 printsize = lastpos - i;
2167 printsize = borders[idx].low - i;
2168 if (printsize > 0) {
2169 os << startTitle << par.substr(i, printsize);
2171 printed += printsize;
2174 handleParentheses(i, false);
2175 if (i >= borders[idx].low)
2176 i = borders[idx].upper;
2179 i = borders[idx].upper;
2186 os << startTitle << par.substr(i, lastpos-i);
2187 printed += lastpos-i;
2189 handleParentheses(lastpos, false);
2191 if (keys["foreignlanguage"].disabled)
2192 startindex = actualdeptindex-langcount;
2194 startindex = actualdeptindex;
2195 for (int i = startindex; i > 0; --i) {
2198 if (hasTitle && (printed > 0))
2200 if (! isPatternString_)
2202 handleParentheses(lastpos, true); /* extra closings '}' allowed here */
2205 void LatexInfo::processRegion(int start, int region_end)
2207 while (start < region_end) { /* Let {[} and {]} survive */
2208 int cnt = interval_.isOpeningPar(start);
2210 // Closing is allowed past the region
2211 int closing = interval_.findclosing(start+1, interval_.par.length());
2212 interval_.addIntervall(start, start+1);
2213 interval_.addIntervall(closing, closing+1);
2217 start = interval_.nextNotIgnored(start+1);
2221 void LatexInfo::removeHead(KeyInfo const & actual, int count)
2223 if (actual.parenthesiscount == 0) {
2224 // "{\tiny{} ...}" ==> "{{} ...}"
2225 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart + actual._tokensize);
2228 // Remove header hull, that is "\url{abcd}" ==> "abcd"
2229 interval_.addIntervall(actual._tokenstart - count, actual._dataStart);
2230 interval_.addIntervall(actual._dataEnd, actual._dataEnd+1);
2234 int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
2237 switch (actual.keytype)
2239 case KeyInfo::isTitle: {
2241 nextKeyIdx = getNextKey();
2244 case KeyInfo::cleanToStart: {
2245 actual._dataEnd = actual._dataStart;
2246 nextKeyIdx = getNextKey();
2247 // Search for end of arguments
2248 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2250 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2251 entries_[i].disabled = true;
2253 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2255 while (interval_.par[actual._dataEnd] == ' ')
2257 interval_.addIntervall(0, actual._dataEnd+1);
2258 interval_.actualdeptindex = 0;
2259 interval_.depts[0] = actual._dataEnd+1;
2260 interval_.closes[0] = -1;
2263 case KeyInfo::noContent: { /* char like "\hspace{2cm}" */
2264 if (actual.disabled)
2265 interval_.addIntervall(actual._tokenstart, actual._dataEnd);
2267 interval_.addIntervall(actual._dataStart, actual._dataEnd);
2270 case KeyInfo::isChar: {
2271 nextKeyIdx = getNextKey();
2274 case KeyInfo::isSize: {
2275 if (actual.disabled || (interval_.par[actual._dataStart] != '{') || (interval_.par[actual._dataStart-1] == ' ')) {
2276 processRegion(actual._dataEnd, actual._dataEnd+1); /* remove possibly following {} */
2277 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2278 nextKeyIdx = getNextKey();
2280 // Here _dataStart points to '{', so correct it
2281 actual._dataStart += 1;
2282 actual._tokensize += 1;
2283 actual.parenthesiscount = 1;
2284 if (interval_.par[actual._dataStart] == '}') {
2285 // Determine the end if used like '{\tiny{}...}'
2286 actual._dataEnd = interval_.findclosing(actual._dataStart+1, interval_.par.length()) + 1;
2287 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2290 // Determine the end if used like '\tiny{...}'
2291 actual._dataEnd = interval_.findclosing(actual._dataStart, interval_.par.length()) + 1;
2293 // Split on this key if not at start
2294 int start = interval_.nextNotIgnored(previousStart);
2295 if (start < actual._tokenstart) {
2296 interval_.output(os, actual._tokenstart);
2297 interval_.addIntervall(start, actual._tokenstart);
2299 // discard entry if at end of actual
2300 nextKeyIdx = process(os, actual);
2304 case KeyInfo::endArguments:
2305 // Remove trailing '{}' too
2306 actual._dataStart += 1;
2307 actual._dataEnd += 1;
2308 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2309 nextKeyIdx = getNextKey();
2311 case KeyInfo::noMain:
2313 case KeyInfo::isStandard: {
2314 if (actual.disabled) {
2316 processRegion(actual._dataStart, actual._dataStart+1);
2317 nextKeyIdx = getNextKey();
2319 // Split on this key if not at datastart of calling entry
2320 int start = interval_.nextNotIgnored(previousStart);
2321 if (start < actual._tokenstart) {
2322 interval_.output(os, actual._tokenstart);
2323 interval_.addIntervall(start, actual._tokenstart);
2325 // discard entry if at end of actual
2326 nextKeyIdx = process(os, actual);
2330 case KeyInfo::removeWithArg: {
2331 nextKeyIdx = getNextKey();
2332 // Search for end of arguments
2333 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2335 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2336 entries_[i].disabled = true;
2338 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2340 interval_.addIntervall(actual._tokenstart, actual._dataEnd+1);
2343 case KeyInfo::doRemove: {
2344 // Remove the key with all parameters and following spaces
2346 for (pos = actual._dataEnd+1; pos < interval_.par.length(); pos++) {
2347 if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
2350 // Remove also enclosing parentheses [] and {}
2353 while (actual._tokenstart > numpars) {
2354 if (pos+numpars >= interval_.par.size())
2356 else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
2358 else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
2364 if (interval_.par[pos+numpars] == ' ')
2368 interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
2369 nextKeyIdx = getNextKey();
2372 case KeyInfo::isList: {
2373 // Discard space before _tokenstart
2375 for (count = 0; count < actual._tokenstart; count++) {
2376 if (interval_.par[actual._tokenstart-count-1] != ' ')
2379 nextKeyIdx = getNextKey();
2380 int tmpIdx = find(nextKeyIdx, KeyInfo::endArguments);
2382 // Special case: \item is not a list, but a command (like in Style Author_Biography in maa-monthly.layout)
2384 // How else can we catch this one?
2385 for (int i = nextKeyIdx; i <= tmpIdx; i++) {
2386 entries_[i].disabled = true;
2388 actual._dataEnd = entries_[tmpIdx]._dataEnd;
2390 else if (nextKeyIdx > 0) {
2391 // Ignore any lang entries inside data region
2392 for (int i = nextKeyIdx; i < int(entries_.size()) && entries_[i]._tokenstart < actual._dataEnd; i++) {
2393 if (entries_[i].keytype == KeyInfo::isMain)
2394 entries_[i].disabled = true;
2397 if (actual.disabled) {
2398 interval_.addIntervall(actual._tokenstart-count, actual._dataEnd+1);
2401 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2403 if (interval_.par[actual._dataEnd+1] == '[') {
2404 int posdown = interval_.findclosing(actual._dataEnd+2, interval_.par.length(), '[', ']');
2405 if ((interval_.par[actual._dataEnd+2] == '{') &&
2406 (interval_.par[posdown-1] == '}')) {
2407 interval_.addIntervall(actual._dataEnd+1,actual._dataEnd+3);
2408 interval_.addIntervall(posdown-1, posdown+1);
2411 interval_.addIntervall(actual._dataEnd+1, actual._dataEnd+2);
2412 interval_.addIntervall(posdown, posdown+1);
2414 int blk = interval_.nextNotIgnored(actual._dataEnd+1);
2415 if (blk > posdown) {
2416 // Discard at most 1 space after empty item
2418 for (count = 0; count < 1; count++) {
2419 if (interval_.par[blk+count] != ' ')
2423 interval_.addIntervall(blk, blk+count);
2428 case KeyInfo::isSectioning: {
2429 // Discard spaces before _tokenstart
2431 int val = actual._tokenstart;
2432 for (count = 0; count < actual._tokenstart;) {
2433 val = interval_.previousNotIgnored(val-1);
2434 if (val < 0 || interval_.par[val] != ' ')
2437 count = actual._tokenstart - val;
2440 if (actual.disabled) {
2441 removeHead(actual, count);
2442 nextKeyIdx = getNextKey();
2444 interval_.addIntervall(actual._tokenstart-count, actual._tokenstart);
2445 nextKeyIdx = process(os, actual);
2449 case KeyInfo::isMath: {
2450 // Same as regex, use the content unchanged
2451 nextKeyIdx = getNextKey();
2454 case KeyInfo::isRegex: {
2455 // DO NOT SPLIT ON REGEX
2457 nextKeyIdx = getNextKey();
2460 case KeyInfo::isIgnored: {
2461 // Treat like a character for now
2462 nextKeyIdx = getNextKey();
2465 case KeyInfo::isMain: {
2466 if (interval_.par.substr(actual._dataStart, 2) == "% ")
2467 interval_.addIntervall(actual._dataStart, actual._dataStart+2);
2468 if (actual._tokenstart > 0) {
2469 int prev = interval_.previousNotIgnored(actual._tokenstart - 1);
2470 if ((prev >= 0) && interval_.par[prev] == '%')
2471 interval_.addIntervall(prev, prev+1);
2473 if (actual.disabled) {
2475 interval_.langcount++;
2476 if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
2477 (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
2478 // Discard also the space before math-equation
2479 interval_.addIntervall(actual._dataStart, actual._dataStart+1);
2481 nextKeyIdx = getNextKey();
2482 // interval.resetOpenedP(actual._dataStart-1);
2485 if (actual._tokenstart < 26) {
2486 // for the first (and maybe dummy) language
2487 interval_.setForDefaultLang(actual);
2489 interval_.resetOpenedP(actual._dataStart-1);
2493 case KeyInfo::invalid:
2494 // This cannot happen, already handled
2497 // LYXERR(Debug::INFO, "Unhandled keytype");
2498 nextKeyIdx = getNextKey();
2505 int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
2507 int end = interval_.nextNotIgnored(actual._dataEnd);
2508 int oldStart = actual._dataStart;
2509 int nextKeyIdx = getNextKey();
2511 if ((nextKeyIdx < 0) ||
2512 (entries_[nextKeyIdx]._tokenstart >= actual._dataEnd) ||
2513 (entries_[nextKeyIdx].keytype == KeyInfo::invalid)) {
2514 if (oldStart <= end) {
2515 processRegion(oldStart, end);
2520 KeyInfo &nextKey = getKeyInfo(nextKeyIdx);
2522 if ((nextKey.keytype == KeyInfo::isMain) && !nextKey.disabled) {
2523 (void) dispatch(os, actual._dataStart, nextKey);
2524 end = nextKey._tokenstart;
2527 processRegion(oldStart, nextKey._tokenstart);
2528 nextKeyIdx = dispatch(os, actual._dataStart, nextKey);
2530 oldStart = nextKey._dataEnd+1;
2532 // now nextKey is either invalid or is outside of actual._dataEnd
2533 // output the remaining and discard myself
2534 if (oldStart <= end) {
2535 processRegion(oldStart, end);
2537 if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
2539 // This is the normal case.
2540 // But if using the firstlanguage, the closing may be missing
2542 // get minimum of 'end' and 'actual._dataEnd' in case that the nextKey.keytype was 'KeyInfo::isMain'
2544 if (actual._dataEnd < end)
2545 output_end = interval_.nextNotIgnored(actual._dataEnd);
2547 output_end = interval_.nextNotIgnored(end);
2548 if ((actual.keytype == KeyInfo::isMain) && actual.disabled) {
2549 interval_.addIntervall(actual._tokenstart, actual._tokenstart+actual._tokensize);
2551 // Remove possible empty data
2552 int dstart = interval_.nextNotIgnored(actual._dataStart);
2553 while (interval_.isOpeningPar(dstart) == 1) {
2554 interval_.addIntervall(dstart, dstart+1);
2555 int dend = interval_.findclosing(dstart+1, output_end);
2556 interval_.addIntervall(dend, dend+1);
2557 dstart = interval_.nextNotIgnored(dstart+1);
2559 if (dstart < output_end)
2560 interval_.output(os, output_end);
2561 interval_.addIntervall(actual._tokenstart, end);
2565 string splitOnKnownMacros(string par, bool isPatternString)
2568 LatexInfo li(par, isPatternString);
2569 // LYXERR(Debug::INFO, "Berfore split: " << par);
2570 KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
2572 DummyKey._tokensize = 0;
2573 DummyKey._dataStart = 0;
2574 DummyKey._dataEnd = par.length();
2575 DummyKey.disabled = true;
2576 int firstkeyIdx = li.getFirstKey();
2578 if (firstkeyIdx >= 0) {
2579 KeyInfo firstKey = li.getKeyInfo(firstkeyIdx);
2580 DummyKey._tokenstart = firstKey._tokenstart;
2582 if ((firstKey.keytype != KeyInfo::isMain) || firstKey.disabled) {
2583 // Use dummy firstKey
2584 firstKey = DummyKey;
2585 (void) li.setNextKey(firstkeyIdx);
2588 if (par.substr(firstKey._dataStart, 2) == "% ")
2589 li.addIntervall(firstKey._dataStart, firstKey._dataStart+2);
2591 nextkeyIdx = li.process(os, firstKey);
2592 while (nextkeyIdx >= 0) {
2593 // Check for a possible gap between the last
2594 // entry and this one
2595 int datastart = li.nextNotIgnored(firstKey._dataStart);
2596 KeyInfo &nextKey = li.getKeyInfo(nextkeyIdx);
2597 if ((nextKey._tokenstart > datastart)) {
2599 firstKey._dataStart = datastart;
2600 firstKey._dataEnd = par.length();
2601 (void) li.setNextKey(nextkeyIdx);
2602 // Fake the last opened parenthesis
2603 li.setForDefaultLang(firstKey);
2604 nextkeyIdx = li.process(os, firstKey);
2607 if (nextKey.keytype != KeyInfo::isMain) {
2608 firstKey._dataStart = datastart;
2609 firstKey._dataEnd = nextKey._dataEnd+1;
2610 (void) li.setNextKey(nextkeyIdx);
2611 li.setForDefaultLang(firstKey);
2612 nextkeyIdx = li.process(os, firstKey);
2615 nextkeyIdx = li.process(os, nextKey);
2619 // Handle the remaining
2620 firstKey._dataStart = li.nextNotIgnored(firstKey._dataStart);
2621 firstKey._dataEnd = par.length();
2623 if ((firstKey._dataStart < firstKey._dataEnd) &&
2624 (par[firstKey._dataStart] != '}')) {
2625 li.setForDefaultLang(firstKey);
2626 (void) li.process(os, firstKey);
2630 // return string definitelly impossible to match
2631 s = "\\foreignlanguage{ignore}{ }";
2635 s = par; /* no known macros found */
2636 // LYXERR(Debug::INFO, "After split: " << s);
2641 * Try to unify the language specs in the latexified text.
2642 * Resulting modified string is set to "", if
2643 * the searched tex does not contain all the features in the search pattern
2645 static string correctlanguagesetting(string par, bool isPatternString, bool withformat)
2647 static Features regex_f;
2648 static int missed = 0;
2649 static bool regex_with_format = false;
2651 int parlen = par.length();
2653 while ((parlen > 0) && (par[parlen-1] == '\n')) {
2656 if (isPatternString && (parlen > 0) && (par[parlen-1] == '~')) {
2657 // Happens to be there in case of description or labeling environment
2662 // Split the latex input into pieces which
2663 // can be digested by our search engine
2664 LYXERR(Debug::FIND, "input: \"" << par << "\"");
2665 result = splitOnKnownMacros(par.substr(0,parlen), isPatternString);
2666 LYXERR(Debug::FIND, "After split: \"" << result << "\"");
2669 result = par.substr(0, parlen);
2670 if (isPatternString) {
2673 regex_f = identifyFeatures(result);
2674 string features = "";
2675 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2676 string a = it->first;
2677 regex_with_format = true;
2678 features += " " + a;
2679 // LYXERR(Debug::INFO, "Identified regex format:" << a);
2681 LYXERR(Debug::FIND, "Identified Features" << features);
2684 } else if (regex_with_format) {
2685 Features info = identifyFeatures(result);
2686 for (auto it = regex_f.cbegin(); it != regex_f.cend(); ++it) {
2687 string a = it->first;
2688 bool b = it->second;
2689 if (b && ! info[a]) {
2691 LYXERR(Debug::FIND, "Missed(" << missed << " " << a <<", srclen = " << parlen );
2697 // LYXERR(Debug::INFO, "No regex formats");
2703 // Remove trailing closure of math, macros and environments, so to catch parts of them.
2704 static int identifyClosing(string & t)
2706 int open_braces = 0;
2708 LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
2709 if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
2711 if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]" REGEX_EOS, "$1"))
2713 if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
2715 if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
2724 static int num_replaced = 0;
2725 static bool previous_single_replace = true;
2727 MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const & opt)
2728 : p_buf(&buf), p_first_buf(&buf), opt(opt)
2730 Buffer & find_buf = *theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true);
2731 docstring const & ds = stringifySearchBuffer(find_buf, opt);
2732 use_regexp = lyx::to_utf8(ds).find("\\regexp{") != std::string::npos;
2733 if (opt.replace_all && previous_single_replace) {
2734 previous_single_replace = false;
2737 else if (!opt.replace_all) {
2738 num_replaced = 0; // count number of replaced strings
2739 previous_single_replace = true;
2741 // When using regexp, braces are hacked already by escape_for_regex()
2742 par_as_string = normalize(ds, !use_regexp);
2744 close_wildcards = 0;
2746 size_t lead_size = 0;
2747 // correct the language settings
2748 par_as_string = correctlanguagesetting(par_as_string, true, !opt.ignoreformat);
2749 if (opt.ignoreformat) {
2751 // if par_as_string_nolead were emty,
2752 // the following call to findAux will always *find* the string
2753 // in the checked data, and thus always using the slow
2754 // examining of the current text part.
2755 par_as_string_nolead = par_as_string;
2758 lead_size = identifyLeading(par_as_string);
2759 LYXERR(Debug::FIND, "Lead_size: " << lead_size);
2760 lead_as_string = par_as_string.substr(0, lead_size);
2761 par_as_string_nolead = par_as_string.substr(lead_size, par_as_string.size() - lead_size);
2765 open_braces = identifyClosing(par_as_string);
2766 identifyClosing(par_as_string_nolead);
2767 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2768 LYXERR(Debug::FIND, "Built MatchStringAdv object: par_as_string = '" << par_as_string << "'");
2770 string lead_as_regexp;
2771 if (lead_size > 0) {
2772 // @todo No need to search for \regexp{} insets in leading material
2773 lead_as_regexp = escape_for_regex(par_as_string.substr(0, lead_size), !opt.ignoreformat);
2774 par_as_string = par_as_string_nolead;
2775 LYXERR(Debug::FIND, "lead_as_regexp is '" << lead_as_regexp << "'");
2776 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2778 par_as_string = escape_for_regex(par_as_string, !opt.ignoreformat);
2779 // Insert (.*?) before trailing closure of math, macros and environments, so to catch parts of them.
2780 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2782 // Insert .* before trailing '\$' ('$' has been escaped by escape_for_regex)
2783 regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\$)\\'", "$1(.*?)$2")
2784 // Insert .* before trailing '\\\]' ('\]' has been escaped by escape_for_regex)
2785 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])( \\\\\\\\\\\\\\])\\'", "$1(.*?)$2")
2786 // Insert .* before trailing '\\end\{...}' ('\end{...}' has been escaped by escape_for_regex)
2787 || regex_replace(par_as_string, par_as_string,
2788 "(.*[^\\\\])( \\\\\\\\end\\\\\\{[a-zA-Z_]*)(\\\\\\*)?(\\\\\\})\\'", "$1(.*?)$2$3$4")
2789 // Insert .* before trailing '\}' ('}' has been escaped by escape_for_regex)
2790 || regex_replace(par_as_string, par_as_string, "(.*[^\\\\])(\\\\\\})\\'", "$1(.*?)$2")
2794 if (!opt.ignoreformat) {
2795 // Remove extra '\}' at end if not part of \{\.\}
2796 size_t lng = par_as_string.size();
2798 if (par_as_string.substr(lng-2, 2).compare("\\}") == 0) {
2800 if (par_as_string.substr(lng-6,3).compare("\\{\\") == 0)
2809 if (lng < par_as_string.size())
2810 par_as_string = par_as_string.substr(0,lng);
2813 regex_replace(par_as_string, par_as_string, "\\\\\\.", "_xxbdotxx_");
2814 // handle '.' -> '[^]', replace later as '[^\}\{\\]'
2815 regex_replace(par_as_string, par_as_string, "\\.", "[^]");
2816 // replace '[^...]' with '[^...\}\{\\]'
2817 regex_replace(par_as_string, par_as_string, "\\[\\^([^\\\\\\]]*)\\]", "_xxbrlxx_$1\\}\\{\\\\_xxbrrxx_");
2818 regex_replace(par_as_string, par_as_string, "_xxbrlxx_", "[^");
2819 regex_replace(par_as_string, par_as_string, "_xxbrrxx_", "]");
2821 regex_replace(par_as_string, par_as_string, "_xxbdotxx_", "\\.");
2824 LYXERR(Debug::FIND, "par_as_string now is '" << par_as_string << "'");
2825 LYXERR(Debug::FIND, "Open braces: " << open_braces);
2826 LYXERR(Debug::FIND, "Close .*? : " << close_wildcards);
2827 LYXERR(Debug::FIND, "Replaced text (to be used as regex): " << par_as_string);
2829 // If entered regexp must match at begin of searched string buffer
2830 // Kornel: Added parentheses to use $1 for size of the leading string
2834 // TODO: Adapt '\[12345678]' in par_as_string to acount for the first '()
2835 // Unfortunately is '\1', '\2', etc not working for strings with extra format
2836 // so the convert has no effect in that case
2837 for (int i = 8; i > 0; --i) {
2838 string orig = "\\\\" + std::to_string(i);
2839 string dest = "\\" + std::to_string(i+1);
2840 while (regex_replace(par_as_string, par_as_string, orig, dest));
2842 regexp_str = "(" + lead_as_regexp + ")" + par_as_string;
2843 regexp2_str = "(" + lead_as_regexp + ").*?" + par_as_string;
2845 LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
2846 regexp = lyx::regex(regexp_str);
2848 LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
2849 regexp2 = lyx::regex(regexp2_str);
2854 // Count number of characters in string
2858 // \\[a-zA-Z]+ ==> 1
2859 static int computeSize(string s, int len)
2865 for (int i = 0; i < len; i += skip, count++) {
2868 if (isalpha(s[i+1])) {
2869 for (int j = 2; i+j < len; j++) {
2870 if (! isalpha(s[i+j])) {
2873 else if ((s[i+j] == '{') && s[i+j+1] == '}')
2875 else if ((s[i+j] == '{') && (i + j + 1 >= len))
2883 else if (s[i] == '{') {
2889 else if (s[i] == '-') {
2890 if (s[i+1] == '-') {
2906 MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_begin) const
2911 (opt.restr == FindAndReplaceOptions::R_ONLY_MATHS && !cur.inMathed()) )
2914 docstring docstr = stringifyFromForSearch(opt, cur, len);
2915 string str = normalize(docstr, true);
2916 if (!opt.ignoreformat) {
2917 str = correctlanguagesetting(str, false, !opt.ignoreformat);
2920 mres.match_len = -1;
2923 LYXERR(Debug::FIND, "Matching against '" << lyx::to_utf8(docstr) << "'");
2924 LYXERR(Debug::FIND, "After normalization: '" << str << "'");
2927 LYXERR(Debug::FIND, "Searching in regexp mode: at_begin=" << at_begin);
2928 regex const *p_regexp;
2929 regex_constants::match_flag_type flags;
2931 flags = regex_constants::match_continuous;
2934 flags = regex_constants::match_default;
2935 p_regexp = ®exp2;
2937 sregex_iterator re_it(str.begin(), str.end(), *p_regexp, flags);
2938 if (re_it == sregex_iterator())
2940 match_results<string::const_iterator> const & m = *re_it;
2942 if (0) { // Kornel Benko: DO NOT CHECKK
2943 // Check braces on the segment that matched the entire regexp expression,
2944 // plus the last subexpression, if a (.*?) was inserted in the constructor.
2945 if (!braces_match(m[0].first, m[0].second, open_braces))
2949 // Check braces on segments that matched all (.*?) subexpressions,
2950 // except the last "padding" one inserted by lyx.
2951 for (size_t i = 1; i < m.size() - 1; ++i)
2952 if (!braces_match(m[i].first, m[i].second, open_braces))
2955 // Exclude from the returned match length any length
2956 // due to close wildcards added at end of regexp
2957 // and also the length of the leading (e.g. '\emph{}')
2959 // Whole found string, including the leading: m[0].second - m[0].first
2960 // Size of the leading string: m[1].second - m[1].first
2961 int leadingsize = 0;
2963 leadingsize = m[1].second - m[1].first;
2965 for (size_t i = 0; i < m.size(); i++) {
2966 LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
2968 if (close_wildcards == 0)
2969 result = m[0].second - m[0].first;
2972 result = m[m.size() - close_wildcards].first - m[0].first;
2974 size_t pos = m.position(size_t(0));
2975 // Ignore last closing characters
2976 while (result > 0) {
2977 if (str[pos+result-1] == '}')
2982 if (result > leadingsize)
2983 result -= leadingsize;
2986 mres.match_len = computeSize(str.substr(pos+leadingsize,result), result);
2987 mres.match2end = str.size() - pos - leadingsize;
2988 mres.pos = pos+leadingsize;
2992 // else !use_regexp: but all code paths above return
2993 LYXERR(Debug::FIND, "Searching in normal mode: par_as_string='"
2994 << par_as_string << "', str='" << str << "'");
2995 LYXERR(Debug::FIND, "Searching in normal mode: lead_as_string='"
2996 << lead_as_string << "', par_as_string_nolead='"
2997 << par_as_string_nolead << "'");
3000 LYXERR(Debug::FIND, "size=" << par_as_string.size()
3001 << ", substr='" << str.substr(0, par_as_string.size()) << "'");
3002 if (str.substr(0, par_as_string.size()) == par_as_string) {
3003 mres.match_len = par_as_string.size();
3004 mres.match2end = str.size();
3009 // Start the search _after_ the leading part
3010 size_t pos = str.find(par_as_string_nolead, lead_as_string.size());
3011 if (pos != string::npos) {
3012 mres.match_len = par_as_string.size();
3013 mres.match2end = str.size() - pos;
3022 MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at_begin) const
3024 MatchResult mres = findAux(cur, len, at_begin);
3025 int res = mres.match_len;
3027 "res=" << res << ", at_begin=" << at_begin
3028 << ", matchword=" << opt.matchword
3029 << ", inTexted=" << cur.inTexted());
3030 if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
3032 if ((len > 0) && (res < len)) {
3036 Paragraph const & par = cur.paragraph();
3037 bool ws_left = (cur.pos() > 0)
3038 ? par.isWordSeparator(cur.pos() - 1)
3044 ws_right = (cur.pos() + len < par.size())
3045 ? par.isWordSeparator(cur.pos() + len)
3049 "cur.pos()=" << cur.pos() << ", res=" << res
3050 << ", separ: " << ws_left << ", " << ws_right
3053 if (ws_left && ws_right) {
3054 // Check for word separators inside the found 'word'
3055 for (int i = 0; i < len; i++) {
3056 if (par.isWordSeparator(cur.pos() + i)) {
3068 string MatchStringAdv::normalize(docstring const & s, bool hack_braces) const
3071 if (! opt.casesensitive)
3072 t = lyx::to_utf8(lowercase(s));
3074 t = lyx::to_utf8(s);
3075 // Remove \n at begin
3076 while (!t.empty() && t[0] == '\n')
3079 while (!t.empty() && t[t.size() - 1] == '\n')
3080 t = t.substr(0, t.size() - 1);
3082 // Handle all other '\n'
3083 while ((pos = t.find("\n")) != string::npos) {
3084 if (pos > 1 && t[pos-1] == '\\' && t[pos-2] == '\\' ) {
3086 if (isAlnumASCII(t[pos+1])) {
3087 t.replace(pos-2, 3, " ");
3090 t.replace(pos-2, 3, "");
3093 else if (!isAlnumASCII(t[pos+1]) || !isAlnumASCII(t[pos-1])) {
3094 // '\n' adjacent to non-alpha-numerics, discard
3095 t.replace(pos, 1, "");
3098 // Replace all other \n with spaces
3099 t.replace(pos, 1, " ");
3102 // Remove stale empty \emph{}, \textbf{} and similar blocks from latexify
3103 // Kornel: Added textsl, textsf, textit, texttt and noun
3104 // + allow to seach for colored text too
3105 LYXERR(Debug::FIND, "Removing stale empty \\emph{}, \\textbf{}, \\*section{} macros from: " << t);
3106 while (regex_replace(t, t, "\\\\(emph|noun|text(bf|sl|sf|it|tt)|(u|uu)line|(s|x)out|uwave)(\\{(\\{\\})?\\})+", ""))
3107 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3108 while (regex_replace(t, t, "\\\\((sub)?(((sub)?section)|paragraph)|part)\\*?(\\{(\\{\\})?\\})+", ""))
3109 LYXERR(Debug::FIND, " further removing stale empty \\emph{}, \\textbf{} macros from: " << t);
3111 while (regex_replace(t, t, "\\\\(foreignlanguage|textcolor|item)\\{[a-z]+\\}(\\{(\\{\\})?\\})+", ""));
3112 // FIXME - check what preceeds the brace
3114 if (opt.ignoreformat)
3115 while (regex_replace(t, t, "\\{", "_x_<")
3116 || regex_replace(t, t, "\\}", "_x_>"))
3117 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3119 while (regex_replace(t, t, "\\\\\\{", "_x_<")
3120 || regex_replace(t, t, "\\\\\\}", "_x_>"))
3121 LYXERR(Debug::FIND, "After {} replacement: '" << t << "'");
3128 docstring stringifyFromCursor(DocIterator const & cur, int len)
3130 LYXERR(Debug::FIND, "Stringifying with len=" << len << " from cursor at pos: " << cur);
3131 if (cur.inTexted()) {
3132 Paragraph const & par = cur.paragraph();
3133 // TODO what about searching beyond/across paragraph breaks ?
3134 // TODO Try adding a AS_STR_INSERTS as last arg
3135 pos_type end = ( len == -1 || cur.pos() + len > int(par.size()) ) ?
3136 int(par.size()) : cur.pos() + len;
3137 // OutputParams runparams(&cur.buffer()->params().encoding());
3138 OutputParams runparams(encodings.fromLyXName("utf8"));
3139 runparams.nice = true;
3140 runparams.flavor = OutputParams::XETEX;
3141 runparams.linelen = 10000; //lyxrc.plaintext_linelen;
3142 // No side effect of file copying and image conversion
3143 runparams.dryrun = true;
3144 runparams.for_search = true;
3145 LYXERR(Debug::FIND, "Stringifying with cur: "
3146 << cur << ", from pos: " << cur.pos() << ", end: " << end);
3147 return par.asString(cur.pos(), end,
3148 AS_STR_INSETS | AS_STR_SKIPDELETE | AS_STR_PLAINTEXT,
3150 } else if (cur.inMathed()) {
3151 CursorSlice cs = cur.top();
3152 MathData md = cs.cell();
3153 MathData::const_iterator it_end =
3154 (( len == -1 || cs.pos() + len > int(md.size()))
3156 : md.begin() + cs.pos() + len );
3158 for (MathData::const_iterator it = md.begin() + cs.pos();
3161 docstring s = asString(md2);
3162 LYXERR(Debug::FIND, "Stringified math: '" << s << "'");
3165 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3170 /** Computes the LaTeX export of buf starting from cur and ending len positions
3171 * after cur, if len is positive, or at the paragraph or innermost inset end
3174 docstring latexifyFromCursor(DocIterator const & cur, int len)
3176 LYXERR(Debug::FIND, "Latexifying with len=" << len << " from cursor at pos: " << cur);
3177 LYXERR(Debug::FIND, " with cur.lastpost=" << cur.lastpos() << ", cur.lastrow="
3178 << cur.lastrow() << ", cur.lastcol=" << cur.lastcol());
3179 Buffer const & buf = *cur.buffer();
3181 odocstringstream ods;
3183 //OutputParams runparams(&buf.params().encoding());
3184 OutputParams runparams(encodings.fromLyXName("utf8"));
3185 runparams.nice = false;
3186 runparams.flavor = OutputParams::XETEX;
3187 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3188 // No side effect of file copying and image conversion
3189 runparams.dryrun = true;
3190 runparams.for_search = true;
3192 if (cur.inTexted()) {
3193 // @TODO what about searching beyond/across paragraph breaks ?
3194 pos_type endpos = cur.paragraph().size();
3195 if (len != -1 && endpos > cur.pos() + len)
3196 endpos = cur.pos() + len;
3197 TeXOnePar(buf, *cur.innerText(), cur.pit(), os, runparams,
3198 string(), cur.pos(), endpos);
3199 string s = lyx::to_utf8(ods.str());
3200 LYXERR(Debug::FIND, "Latexified +modified text: '" << s << "'");
3201 return(lyx::from_utf8(s));
3202 } else if (cur.inMathed()) {
3203 // Retrieve the math environment type, and add '$' or '$[' or others (\begin{equation}) accordingly
3204 for (int s = cur.depth() - 1; s >= 0; --s) {
3205 CursorSlice const & cs = cur[s];
3206 if (cs.asInsetMath() && cs.asInsetMath()->asHullInset()) {
3208 cs.asInsetMath()->asHullInset()->header_write(ws);
3213 CursorSlice const & cs = cur.top();
3214 MathData md = cs.cell();
3215 MathData::const_iterator it_end =
3216 ((len == -1 || cs.pos() + len > int(md.size()))
3218 : md.begin() + cs.pos() + len);
3220 for (MathData::const_iterator it = md.begin() + cs.pos();
3224 ods << asString(md2);
3225 // Retrieve the math environment type, and add '$' or '$]'
3226 // or others (\end{equation}) accordingly
3227 for (int s = cur.depth() - 1; s >= 0; --s) {
3228 CursorSlice const & cs2 = cur[s];
3229 InsetMath * inset = cs2.asInsetMath();
3230 if (inset && inset->asHullInset()) {
3232 inset->asHullInset()->footer_write(ws);
3236 LYXERR(Debug::FIND, "Latexified math: '" << lyx::to_utf8(ods.str()) << "'");
3238 LYXERR(Debug::FIND, "Don't know how to stringify from here: " << cur);
3244 /** Finalize an advanced find operation, advancing the cursor to the innermost
3245 ** position that matches, plus computing the length of the matching text to
3248 int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
3250 // Search the foremost position that matches (avoids find of entire math
3251 // inset when match at start of it)
3253 DocIterator old_cur(cur.buffer());
3255 LYXERR(Debug::FIND, "Forwarding one step (searching for innermost match)");
3259 } while (cur && cur.depth() > d && match(cur).match_len > 0);
3261 int max_match = match(cur).match_len; /* match valid only if not searching whole words */
3262 if (max_match <= 0) return 0;
3263 LYXERR(Debug::FIND, "Ok");
3265 // Compute the match length
3267 if (cur.pos() + len > cur.lastpos())
3269 if (match.opt.matchword) {
3270 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3271 while (cur.pos() + len <= cur.lastpos() && match(cur, len).match_len <= 0) {
3273 LYXERR(Debug::FIND, "verifying unmatch with len = " << len);
3275 // Length of matched text (different from len param)
3276 int old_match = match(cur, len).match_len;
3280 // Greedy behaviour while matching regexps
3281 while ((new_match = match(cur, len + 1).match_len) > old_match) {
3283 old_match = new_match;
3284 LYXERR(Debug::FIND, "verifying match with len = " << len);
3291 int maxl = cur.lastpos() - cur.pos();
3292 // Greedy behaviour while matching regexps
3293 while (maxl > minl) {
3294 int actual_match = match(cur, len).match_len;
3295 if (actual_match >= max_match) {
3296 // actual_match > max_match _can_ happen,
3297 // if the search area splits
3298 // some following word so that the regex
3299 // (e.g. 'r.*r\b' matches 'r' from the middle of the
3301 // This means, the len value is too big
3303 len = (int)((maxl + minl)/2);
3306 // (actual_match < max_match)
3308 len = (int)((maxl + minl)/2);
3312 // Search for real start of matched characters
3317 } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
3318 if (cur.depth() < old_cur.depth()) {
3320 LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
3323 if (cur.pos() != old_cur.pos()) {
3324 // OK, forwarded 1 pos in actual inset
3325 actual_match = match(cur, len-1).match_len;
3326 if (actual_match == max_match) {
3327 // Ha, got it! The shorter selection has the same match length
3332 // OK, the shorter selection matches less chars, revert to previous value
3338 LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
3339 actual_match = match(cur, len).match_len;
3340 if (actual_match == max_match)
3350 int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
3354 while (!theApp()->longOperationCancelled() && cur) {
3355 LYXERR(Debug::FIND, "findForwardAdv() cur: " << cur);
3356 MatchResult mres = match(cur, -1, false);
3357 int match_len = mres.match_len;
3358 LYXERR(Debug::FIND, "match_len: " << match_len);
3359 if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
3360 LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
3363 if (match_len > 0) {
3364 // Try to find the begin of searched string
3365 int increment = mres.pos/2;
3366 while (mres.pos > 5 && (increment > 5)) {
3367 DocIterator old_cur = cur;
3368 for (int i = 0; i < increment && cur; cur.forwardPos(), i++) {
3370 if (! cur || (cur.pit() > old_cur.pit())) {
3371 // Are we outside of the paragraph?
3372 // This can happen if moving past some UTF8-encoded chars
3377 MatchResult mres2 = match(cur, -1, false);
3378 if ((mres2.match2end < mres.match2end) ||
3379 (mres2.match_len < mres.match_len)) {
3386 if (increment > mres.pos/2)
3387 increment = mres.pos/2;
3391 int match_len_zero_count = 0;
3392 for (int i = 0; !theApp()->longOperationCancelled() && cur; cur.forwardPos()) {
3394 int remaining_len = match(cur, -1, false).match_len;
3395 if (remaining_len <= 0) {
3396 // Apparently the searched string is not in the remaining part
3403 LYXERR(Debug::FIND, "Advancing cur: " << cur);
3404 int match_len3 = match(cur, 1).match_len;
3407 int match_len2 = match(cur).match_len;
3408 LYXERR(Debug::FIND, "match_len2: " << match_len2);
3409 if (match_len2 > 0) {
3410 // Sometimes in finalize we understand it wasn't a match
3411 // and we need to continue the outest loop
3412 int len = findAdvFinalize(cur, match);
3417 if (match_len2 >= 0) {
3418 if (match_len2 == 0)
3419 match_len_zero_count++;
3421 match_len_zero_count = 0;
3424 if (++match_len_zero_count > 3) {
3425 LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
3433 if (match_len >= 0 && cur.pit() < cur.lastpit()) {
3434 LYXERR(Debug::FIND, "Advancing par: cur=" << cur);
3437 // This should exit nested insets, if any, or otherwise undefine the currsor.
3438 cur.pos() = cur.lastpos();
3439 LYXERR(Debug::FIND, "Advancing pos: cur=" << cur);
3447 /// Find the most backward consecutive match within same paragraph while searching backwards.
3448 int findMostBackwards(DocIterator & cur, MatchStringAdv const & match)
3450 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3451 DocIterator tmp_cur = cur;
3452 int len = findAdvFinalize(tmp_cur, match);
3453 Inset & inset = cur.inset();
3454 for (; cur != cur_begin; cur.backwardPos()) {
3455 LYXERR(Debug::FIND, "findMostBackwards(): cur=" << cur);
3456 DocIterator new_cur = cur;
3457 new_cur.backwardPos();
3458 if (new_cur == cur || &new_cur.inset() != &inset || !match(new_cur).match_len)
3460 int new_len = findAdvFinalize(new_cur, match);
3465 LYXERR(Debug::FIND, "findMostBackwards(): exiting with cur=" << cur);
3471 int findBackwardsAdv(DocIterator & cur, MatchStringAdv & match)
3475 // Backup of original position
3476 DocIterator cur_begin = doc_iterator_begin(cur.buffer());
3477 if (cur == cur_begin)
3480 DocIterator cur_orig(cur);
3481 bool pit_changed = false;
3484 bool found_match = (match(cur, -1, false).match_len > 0);
3488 cur.pos() = cur.lastpos();
3490 cur.pos() = cur_orig.pos();
3491 LYXERR(Debug::FIND, "findBackAdv2: cur: " << cur);
3492 DocIterator cur_prev_iter;
3494 found_match = (match(cur).match_len > 0);
3495 LYXERR(Debug::FIND, "findBackAdv3: found_match="
3496 << found_match << ", cur: " << cur);
3498 return findMostBackwards(cur, match);
3500 // Stop if begin of document reached
3501 if (cur == cur_begin)
3503 cur_prev_iter = cur;
3507 if (cur == cur_begin)
3514 } while (!theApp()->longOperationCancelled());
3522 docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
3523 DocIterator const & cur, int len)
3525 if (cur.pos() < 0 || cur.pos() > cur.lastpos())
3527 if (!opt.ignoreformat)
3528 return latexifyFromCursor(cur, len);
3530 return stringifyFromCursor(cur, len);
3534 FindAndReplaceOptions::FindAndReplaceOptions(
3535 docstring const & _find_buf_name, bool _casesensitive,
3536 bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
3537 docstring const & _repl_buf_name, bool _keep_case,
3538 SearchScope _scope, SearchRestriction _restr, bool _replace_all)
3539 : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
3540 forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
3541 repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
3549 /** Check if 'len' letters following cursor are all non-lowercase */
3550 static bool allNonLowercase(Cursor const & cur, int len)
3552 pos_type beg_pos = cur.selectionBegin().pos();
3553 pos_type end_pos = cur.selectionBegin().pos() + len;
3554 if (len > cur.lastpos() + 1 - beg_pos) {
3555 LYXERR(Debug::FIND, "This should not happen, more debug needed");
3556 len = cur.lastpos() + 1 - beg_pos;
3557 end_pos = beg_pos + len;
3559 for (pos_type pos = beg_pos; pos != end_pos; ++pos)
3560 if (isLowerCase(cur.paragraph().getChar(pos)))
3566 /** Check if first letter is upper case and second one is lower case */
3567 static bool firstUppercase(Cursor const & cur)
3570 pos_type pos = cur.selectionBegin().pos();
3571 if (pos >= cur.lastpos() - 1) {
3572 LYXERR(Debug::FIND, "No upper-case at cur: " << cur);
3575 ch1 = cur.paragraph().getChar(pos);
3576 ch2 = cur.paragraph().getChar(pos + 1);
3577 bool result = isUpperCase(ch1) && isLowerCase(ch2);
3578 LYXERR(Debug::FIND, "firstUppercase(): "
3579 << "ch1=" << ch1 << "(" << char(ch1) << "), ch2="
3580 << ch2 << "(" << char(ch2) << ")"
3581 << ", result=" << result << ", cur=" << cur);
3586 /** Make first letter of supplied buffer upper-case, and the rest lower-case.
3588 ** \fixme What to do with possible further paragraphs in replace buffer ?
3590 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
3592 ParagraphList::iterator pit = buffer.paragraphs().begin();
3593 LASSERT(!pit->empty(), /**/);
3594 pos_type right = pos_type(1);
3595 pit->changeCase(buffer.params(), pos_type(0), right, first_case);
3596 right = pit->size();
3597 pit->changeCase(buffer.params(), pos_type(1), right, others_case);
3603 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
3605 Cursor & cur = bv->cursor();
3606 if (opt.repl_buf_name.empty()
3607 || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
3608 || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3611 DocIterator sel_beg = cur.selectionBegin();
3612 DocIterator sel_end = cur.selectionEnd();
3613 if (&sel_beg.inset() != &sel_end.inset()
3614 || sel_beg.pit() != sel_end.pit()
3615 || sel_beg.idx() != sel_end.idx())
3617 int sel_len = sel_end.pos() - sel_beg.pos();
3618 LYXERR(Debug::FIND, "sel_beg: " << sel_beg << ", sel_end: " << sel_end
3619 << ", sel_len: " << sel_len << endl);
3622 LASSERT(sel_len > 0, return 0);
3624 if (!matchAdv(sel_beg, sel_len).match_len)
3627 // Build a copy of the replace buffer, adapted to the KeepCase option
3628 Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
3630 repl_buffer_orig.write(oss);
3631 string lyx = oss.str();
3632 Buffer repl_buffer("", false);
3633 repl_buffer.setUnnamed(true);
3634 LASSERT(repl_buffer.readString(lyx), return 0);
3635 if (opt.keep_case && sel_len >= 2) {
3636 LYXERR(Debug::FIND, "keep_case true: cur.pos()=" << cur.pos() << ", sel_len=" << sel_len);
3637 if (cur.inTexted()) {
3638 if (firstUppercase(cur))
3639 changeFirstCase(repl_buffer, text_uppercase, text_lowercase);
3640 else if (allNonLowercase(cur, sel_len))
3641 changeFirstCase(repl_buffer, text_uppercase, text_uppercase);
3644 cap::cutSelection(cur, false);
3645 if (cur.inTexted()) {
3646 repl_buffer.changeLanguage(
3647 repl_buffer.language(),
3648 cur.getFont().language());
3649 LYXERR(Debug::FIND, "Replacing by pasteParagraphList()ing repl_buffer");
3650 LYXERR(Debug::FIND, "Before pasteParagraphList() cur=" << cur << endl);
3651 cap::pasteParagraphList(cur, repl_buffer.paragraphs(),
3652 repl_buffer.params().documentClassPtr(),
3653 bv->buffer().errorList("Paste"));
3654 LYXERR(Debug::FIND, "After pasteParagraphList() cur=" << cur << endl);
3655 sel_len = repl_buffer.paragraphs().begin()->size();
3656 } else if (cur.inMathed()) {
3657 odocstringstream ods;
3659 // OutputParams runparams(&repl_buffer.params().encoding());
3660 OutputParams runparams(encodings.fromLyXName("utf8"));
3661 runparams.nice = false;
3662 runparams.flavor = OutputParams::XETEX;
3663 runparams.linelen = 8000; //lyxrc.plaintext_linelen;
3664 runparams.dryrun = true;
3665 TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);
3666 //repl_buffer.getSourceCode(ods, 0, repl_buffer.paragraphs().size(), false);
3667 docstring repl_latex = ods.str();
3668 LYXERR(Debug::FIND, "Latexified replace_buffer: '" << repl_latex << "'");
3670 (void)regex_replace(to_utf8(repl_latex), s, "\\$(.*)\\$", "$1");
3671 (void)regex_replace(s, s, "\\\\\\[(.*)\\\\\\]", "$1");
3672 repl_latex = from_utf8(s);
3673 LYXERR(Debug::FIND, "Replacing by insert()ing latex: '" << repl_latex << "' cur=" << cur << " with depth=" << cur.depth());
3674 MathData ar(cur.buffer());
3675 asArray(repl_latex, ar, Parse::NORMAL);
3677 sel_len = ar.size();
3678 LYXERR(Debug::FIND, "After insert() cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3680 if (cur.pos() >= sel_len)
3681 cur.pos() -= sel_len;
3684 LYXERR(Debug::FIND, "After pos adj cur=" << cur << " with depth: " << cur.depth() << " and len: " << sel_len);
3685 bv->putSelectionAt(DocIterator(cur), sel_len, !opt.forward);
3686 bv->processUpdateFlags(Update::Force);
3691 /// Perform a FindAdv operation.
3692 bool findAdv(BufferView * bv, FindAndReplaceOptions const & opt)
3697 // e.g., when invoking word-findadv from mini-buffer wither with
3698 // wrong options syntax or before ever opening advanced F&R pane
3699 if (theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
3703 MatchStringAdv matchAdv(bv->buffer(), opt);
3704 int length = bv->cursor().selectionEnd().pos() - bv->cursor().selectionBegin().pos();
3706 bv->putSelectionAt(bv->cursor().selectionBegin(), length, !opt.forward);
3707 num_replaced += findAdvReplace(bv, opt, matchAdv);
3710 match_len = findForwardAdv(cur, matchAdv);
3712 match_len = findBackwardsAdv(cur, matchAdv);
3714 // This may only be raised by lyx::regex()
3715 bv->message(_("Invalid regular expression!"));
3719 if (match_len == 0) {
3720 if (num_replaced > 0) {
3721 switch (num_replaced)
3724 bv->message(_("One match has been replaced."));
3727 bv->message(_("Two matches have been replaced."));
3730 bv->message(bformat(_("%1$d matches have been replaced."), num_replaced));
3736 bv->message(_("Match not found."));
3741 if (num_replaced > 0)
3742 bv->message(_("Match has been replaced."));
3744 bv->message(_("Match found."));
3746 LYXERR(Debug::FIND, "Putting selection at cur=" << cur << " with len: " << match_len);
3747 bv->putSelectionAt(cur, match_len, !opt.forward);
3753 ostringstream & operator<<(ostringstream & os, FindAndReplaceOptions const & opt)
3755 os << to_utf8(opt.find_buf_name) << "\nEOSS\n"
3756 << opt.casesensitive << ' '
3757 << opt.matchword << ' '
3758 << opt.forward << ' '
3759 << opt.expandmacros << ' '
3760 << opt.ignoreformat << ' '
3761 << opt.replace_all << ' '
3762 << to_utf8(opt.repl_buf_name) << "\nEOSS\n"
3763 << opt.keep_case << ' '
3764 << int(opt.scope) << ' '
3767 LYXERR(Debug::FIND, "built: " << os.str());
3773 istringstream & operator>>(istringstream & is, FindAndReplaceOptions & opt)
3775 LYXERR(Debug::FIND, "parsing");
3779 while (line != "EOSS") {
3783 if (is.eof()) // Tolerate malformed request
3787 LYXERR(Debug::FIND, "file_buf_name: '" << s << "'");
3788 opt.find_buf_name = from_utf8(s);
3789 is >> opt.casesensitive >> opt.matchword >> opt.forward >> opt.expandmacros >> opt.ignoreformat >> opt.replace_all;
3790 is.get(); // Waste space before replace string
3793 while (line != "EOSS") {
3797 if (is.eof()) // Tolerate malformed request
3801 LYXERR(Debug::FIND, "repl_buf_name: '" << s << "'");
3802 opt.repl_buf_name = from_utf8(s);
3803 is >> opt.keep_case;
3806 opt.scope = FindAndReplaceOptions::SearchScope(i);
3808 opt.restr = FindAndReplaceOptions::SearchRestriction(i);
3810 LYXERR(Debug::FIND, "parsed: " << opt.casesensitive << ' ' << opt.matchword << ' ' << opt.forward << ' '
3811 << opt.expandmacros << ' ' << opt.ignoreformat << ' ' << opt.keep_case << ' '
3812 << opt.scope << ' ' << opt.restr);