]> git.lyx.org Git - lyx.git/blobdiff - src/lyxfind.cpp
Refactor InsetQuotes.h enums
[lyx.git] / src / lyxfind.cpp
index af9896f3820010f53b36c9429c5457c47405b39e..95dcf196749c3b4927c908c0e28944c6e90b8e6c 100644 (file)
@@ -17,7 +17,6 @@
 #include "lyxfind.h"
 
 #include "Buffer.h"
-#include "buffer_funcs.h"
 #include "BufferList.h"
 #include "BufferParams.h"
 #include "BufferView.h"
@@ -29,8 +28,6 @@
 #include "output_latex.h"
 #include "OutputParams.h"
 #include "Paragraph.h"
-#include "ParIterator.h"
-#include "TexRow.h"
 #include "Text.h"
 #include "Encoding.h"
 
 #include "frontends/alert.h"
 
 #include "mathed/InsetMath.h"
-#include "mathed/InsetMathGrid.h"
 #include "mathed/InsetMathHull.h"
 #include "mathed/MathData.h"
 #include "mathed/MathStream.h"
 #include "mathed/MathSupport.h"
 
-#include "support/convert.h"
 #include "support/debug.h"
 #include "support/docstream.h"
 #include "support/FileName.h"
 #include "support/gettext.h"
 #include "support/lassert.h"
 #include "support/lstrings.h"
-
-#include "support/regex.h"
 #include "support/textutils.h"
+
 #include <map>
+#include <regex>
 
 using namespace std;
 using namespace lyx::support;
@@ -66,60 +61,55 @@ namespace lyx {
 class IgnoreFormats {
  public:
        ///
-       IgnoreFormats()
-               : ignoreFamily_(false), ignoreSeries_(false),
-                 ignoreShape_(false), ignoreUnderline_(false),
-                 ignoreMarkUp_(false), ignoreStrikeOut_(false),
-                 ignoreSectioning_(false), ignoreFrontMatter_(false),
-                 ignoreColor_(false), ignoreLanguage_(false) {}
+       IgnoreFormats() = default;
        ///
-       bool getFamily() { return ignoreFamily_; };
+       bool getFamily() const { return ignoreFamily_; }
        ///
-       bool getSeries() { return ignoreSeries_; };
+       bool getSeries() const { return ignoreSeries_; }
        ///
-       bool getShape() { return ignoreShape_; };
+       bool getShape() const { return ignoreShape_; }
        ///
-       bool getUnderline() { return ignoreUnderline_; };
+       bool getUnderline() const { return ignoreUnderline_; }
        ///
-       bool getMarkUp() { return ignoreMarkUp_; };
+       bool getMarkUp() const { return ignoreMarkUp_; }
        ///
-       bool getStrikeOut() { return ignoreStrikeOut_; };
+       bool getStrikeOut() const { return ignoreStrikeOut_; }
        ///
-       bool getSectioning() { return ignoreSectioning_; };
+       bool getSectioning() const { return ignoreSectioning_; }
        ///
-       bool getFrontMatter() { return ignoreFrontMatter_; };
+       bool getFrontMatter() const { return ignoreFrontMatter_; }
        ///
-       bool getColor() { return ignoreColor_; };
+       bool getColor() const { return ignoreColor_; }
        ///
-       bool getLanguage() { return ignoreLanguage_; };
+       bool getLanguage() const { return ignoreLanguage_; }
        ///
-       void setIgnoreFormat(string type, bool value);
+       void setIgnoreFormat(string const & type, bool value);
 
 private:
        ///
-       bool ignoreFamily_;
+       bool ignoreFamily_ = false;
        ///
-       bool ignoreSeries_;
+       bool ignoreSeries_ = false;
        ///
-       bool ignoreShape_;
+       bool ignoreShape_ = false;
        ///
-       bool ignoreUnderline_;
+       bool ignoreUnderline_ = false;
        ///
-       bool ignoreMarkUp_;
+       bool ignoreMarkUp_ = false;
        ///
-       bool ignoreStrikeOut_;
+       bool ignoreStrikeOut_ = false;
        ///
-       bool ignoreSectioning_;
+       bool ignoreSectioning_ = false;
        ///
-       bool ignoreFrontMatter_;
+       bool ignoreFrontMatter_ = false;
        ///
-       bool ignoreColor_;
+       bool ignoreColor_ = false;
        ///
-       bool ignoreLanguage_;
+       bool ignoreLanguage_ = false;
 };
 
 
-void IgnoreFormats::setIgnoreFormat(string type, bool value)
+void IgnoreFormats::setIgnoreFormat(string const & type, bool value)
 {
        if (type == "color") {
                ignoreColor_ = value;
@@ -160,7 +150,7 @@ void IgnoreFormats::setIgnoreFormat(string type, bool value)
 IgnoreFormats ignoreFormats;
 
 
-void setIgnoreFormat(string type, bool value)
+void setIgnoreFormat(string const & type, bool value)
 {
   ignoreFormats.setIgnoreFormat(type, value);
 }
@@ -178,11 +168,11 @@ bool parse_bool(docstring & howto)
 }
 
 
-class MatchString : public binary_function<Paragraph, pos_type, int>
+class MatchString
 {
 public:
-       MatchString(docstring const & str, bool cs, bool mw)
-               : str(str), case_sens(cs), whole_words(mw)
+       MatchString(docstring const & s, bool cs, bool mw)
+               : str(s), case_sens(cs), whole_words(mw)
        {}
 
        // returns true if the specified string is at the specified position
@@ -357,11 +347,10 @@ pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
                           bool whole, bool forward, bool findnext)
 {
        Cursor & cur = bv->cursor();
-       bool found = false;
        if (!cur.selection()) {
                // no selection, non-empty search string: find it
                if (!searchstr.empty()) {
-                       found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
+                       bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
                        return make_pair(found, 0);
                }
                // empty search string
@@ -390,7 +379,7 @@ pair<bool, int> replaceOne(BufferView * bv, docstring searchstr,
        // no selection or current selection is not search word:
        // just find the search word
        if (!have_selection || !match) {
-               found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
+               bool const found = findOne(bv, searchstr, case_sens, whole, forward, true, findnext);
                return make_pair(found, 0);
        }
 
@@ -784,10 +773,10 @@ string escape_for_regex(string s, bool match_latex)
 bool regex_replace(string const & s, string & t, string const & searchstr,
                   string const & replacestr)
 {
-       lyx::regex e(searchstr, regex_constants::ECMAScript);
+       regex e(searchstr, regex_constants::ECMAScript);
        ostringstream oss;
        ostream_iterator<char, char> it(oss);
-       lyx::regex_replace(it, s.begin(), s.end(), e, replacestr);
+       regex_replace(it, s.begin(), s.end(), e, replacestr);
        // tolerate t and s be references to the same variable
        bool rv = (s != oss.str());
        t = oss.str();
@@ -892,9 +881,9 @@ private:
        // normalized string to search
        string par_as_string;
        // regular expression to use for searching
-       lyx::regex regexp;
+       regex regexp;
        // same as regexp, but prefixed with a ".*?"
-       lyx::regex regexp2;
+       regex regexp2;
        // leading format material as string
        string lead_as_string;
        // par_as_string after removal of lead_as_string
@@ -916,7 +905,7 @@ static docstring buffer_to_latex(Buffer & buffer)
        odocstringstream ods;
        otexstream os(ods);
        runparams.nice = true;
-       runparams.flavor = OutputParams::XETEX;
+       runparams.flavor = FLAVOR::XETEX;
        runparams.linelen = 10000; //lyxrc.plaintext_linelen;
        // No side effect of file copying and image conversion
        runparams.dryrun = true;
@@ -939,7 +928,7 @@ static docstring stringifySearchBuffer(Buffer & buffer, FindAndReplaceOptions co
                // OutputParams runparams(&buffer.params().encoding());
                OutputParams runparams(encodings.fromLyXName("utf8"));
                runparams.nice = true;
-               runparams.flavor = OutputParams::XETEX;
+               runparams.flavor = FLAVOR::XETEX;
                runparams.linelen = 10000; //lyxrc.plaintext_linelen;
                runparams.dryrun = true;
                runparams.for_search = true;
@@ -966,11 +955,11 @@ static size_t identifyLeading(string const & s)
        // @TODO Support \item[text]
        // Kornel: Added textsl, textsf, textit, texttt and noun
        // + allow to search for colored text too
-       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)\\*?)\\{", "")
-              || regex_replace(t, t, REGEX_BOS "\\$", "")
-              || regex_replace(t, t, REGEX_BOS "\\\\\\[ ", "")
-              || regex_replace(t, t, REGEX_BOS " ?\\\\item\\{[a-z]+\\}", "")
-              || regex_replace(t, t, REGEX_BOS "\\\\begin\\{[a-zA-Z_]*\\*?\\} ", ""))
+       while (regex_replace(t, t, "^\\\\(((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)\\*?)\\{", "")
+              || regex_replace(t, t, "^\\$", "")
+              || regex_replace(t, t, "^\\\\\\[", "")
+              || regex_replace(t, t, "^ ?\\\\item\\{[a-z]+\\}", "")
+              || regex_replace(t, t, "^\\\\begin\\{[a-zA-Z_]*\\*?\\}", ""))
               ;
        LYXERR(Debug::FIND, "  after removing leading $, \\[ , \\emph{, \\textbf{, etc.: '" << t << "'");
        return s.find(t);
@@ -1071,35 +1060,20 @@ class KeyInfo {
      * so that they can be ignored */
     endArguments
   };
- KeyInfo()
-   : keytype(invalid),
-    head(""),
-    _tokensize(-1),
-    _tokenstart(-1),
-    _dataStart(-1),
-    _dataEnd(-1),
-    parenthesiscount(1),
-    disabled(false),
-    used(false)
-  {};
+ KeyInfo() = default;
  KeyInfo(KeyType type, int parcount, bool disable)
    : keytype(type),
-    _tokensize(-1),
-    _tokenstart(-1),
-    _dataStart(-1),
-    _dataEnd(-1),
     parenthesiscount(parcount),
-    disabled(disable),
-    used(false) {};
-  KeyType keytype;
+    disabled(disable) {}
+  KeyType keytype = invalid;
   string head;
-  int _tokensize;
-  int _tokenstart;
-  int _dataStart;
-  int _dataEnd;
-  int parenthesiscount;
-  bool disabled;
-  bool used;                            /* by pattern */
+  int _tokensize = -1;
+  int _tokenstart = -1;
+  int _dataStart = -1;
+  int _dataEnd = -1;
+  int parenthesiscount = 1;
+  bool disabled = false;
+  bool used = false;                    /* by pattern */
 };
 
 class Border {
@@ -1114,8 +1088,8 @@ class Intervall {
   bool isPatternString_;
 public:
   explicit Intervall(bool isPattern, string const & p) :
-       isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
-       hasTitle(false)
+        isPatternString_(isPattern), par(p), ignoreidx(-1), actualdeptindex(0),
+        hasTitle(false), langcount(0)
   {
     depts[0] = 0;
     closes[0] = 0;
@@ -1127,19 +1101,20 @@ public:
   int depts[MAXOPENED];
   int closes[MAXOPENED];
   int actualdeptindex;
-  int previousNotIgnored(int);
-  int nextNotIgnored(int);
+  int previousNotIgnored(int) const;
+  int nextNotIgnored(int) const;
   void handleOpenP(int i);
   void handleCloseP(int i, bool closingAllowed);
   void resetOpenedP(int openPos);
   void addIntervall(int upper);
   void addIntervall(int low, int upper); /* if explicit */
   void removeAccents();
-  void setForDefaultLang(KeyInfo &defLang);
+  void setForDefaultLang(KeyInfo const & defLang) const;
   int findclosing(int start, int end, char up, char down, int repeat);
   void handleParentheses(int lastpos, bool closingAllowed);
   bool hasTitle;
-  int isOpeningPar(int pos);
+  int langcount;       // Number of disabled language specs up to current position in actual interval
+  int isOpeningPar(int pos) const;
   string titleValue;
   void output(ostringstream &os, int lastpos);
   // string show(int lastpos);
@@ -1147,7 +1122,7 @@ public:
 
 vector<Border> Intervall::borders = vector<Border>(30);
 
-int Intervall::isOpeningPar(int pos)
+int Intervall::isOpeningPar(int pos) const
 {
   if ((pos < 0) || (size_t(pos) >= par.size()))
     return 0;
@@ -1162,7 +1137,7 @@ int Intervall::isOpeningPar(int pos)
   return 1;
 }
 
-void Intervall::setForDefaultLang(KeyInfo &defLang)
+void Intervall::setForDefaultLang(KeyInfo const & defLang) const
 {
   // Enable the use of first token again
   if (ignoreidx >= 0) {
@@ -1181,12 +1156,12 @@ static void checkDepthIndex(int val)
   static int maxdepthidx = MAXOPENED-2;
   static int lastmaxdepth = 0;
   if (val > lastmaxdepth) {
-    LYXERR0("Depth reached " << val);
+    LYXERR(Debug::INFO, "Depth reached " << val);
     lastmaxdepth = val;
   }
   if (val > maxdepthidx) {
     maxdepthidx = val;
-    LYXERR0("maxdepthidx now " << val);
+    LYXERR(Debug::INFO, "maxdepthidx now " << val);
   }
 }
 
@@ -1196,7 +1171,7 @@ static void checkIgnoreIdx(int val)
 {
   static int lastmaxignore = -1;
   if ((lastmaxignore < val) && (size_t(val+1) >= borders.size())) {
-    LYXERR0("IgnoreIdx reached " << val);
+    LYXERR(Debug::INFO, "IgnoreIdx reached " << val);
     lastmaxignore = val;
   }
 }
@@ -1283,8 +1258,8 @@ static void buildaccent(string n, string param, string values)
   const char delim = '|';
   while (getline(s, name, delim)) {
     size_t start = 0;
-    for (size_t i = 0; i < param.size(); i++) {
-      string key = name + "{" + param[i] + "}";
+    for (char c : param) {
+      string key = name + "{" + c + "}";
       // get the corresponding utf8-value
       if ((values[start] & 0xc0) != 0xc0) {
         // should not happen, utf8 encoding starts at least with 11xxxxxx
@@ -1292,7 +1267,7 @@ static void buildaccent(string n, string param, string values)
         if ((values[start] & 0x80) == 0) {
           // is ascii
           accents[key] = values.substr(start, 1);
-          // LYXERR0("" << key << "=" << accents[key]);
+          // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
         }
         start++;
         continue;
@@ -1307,7 +1282,7 @@ static void buildaccent(string n, string param, string values)
           // This is the first byte of following utf8 char
           accents[key] = values.substr(start, j);
           start += j;
-          // LYXERR0("" << key << "=" << accents[key]);
+          // LYXERR(Debug::INFO, "" << key << "=" << accents[key]);
           break;
         }
       }
@@ -1320,16 +1295,17 @@ static void buildAccentsMap()
   accents["imath"] = "ı";
   accents["i"] = "ı";
   accents["jmath"] = "ȷ";
+  accents["cdot"] = "·";
   accents["lyxmathsym{ß}"] = "ß";
   accents["text{ß}"] = "ß";
   accents["ddot{\\imath}"] = "ï";
-  buildaccent("ddot", "aAeEiIioOuUyY",
-                      "äÄëËïÏïöÖüÜÿŸ");   // umlaut
-  buildaccent("dot|.", "cCeEGgIizZaAoObBdDfFyY",
-                       "ċĊėĖĠġİİżŻȧȦȯȮḃḂḋḊḟḞẏẎ");        // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
+  buildaccent("ddot", "aAeEhHiIioOtuUwWxXyY",
+                      "äÄëËḧḦïÏïöÖẗüÜẅẄẍẌÿŸ");      // umlaut
+  buildaccent("dot|.", "aAbBcCdDeEfFGghHIimMnNoOpPrRsStTwWxXyYzZ",
+                       "ȧȦḃḂċĊḋḊėĖḟḞĠġḣḢİİṁṀṅṄȯȮṗṖṙṘṡṠṫṪẇẆẋẊẏẎżŻ");  // dot{i} can only happen if ignoring case, but there is no lowercase of 'İ'
   accents["acute{\\imath}"] = "í";
-  buildaccent("acute", "aAcCeElLoOnNrRsSuUyYzZiI",
-                       "áÁćĆéÉĺĹóÓńŃŕŔśŚúÚýÝźŹíÍ");
+  buildaccent("acute", "aAcCeEgGkKlLmMoOnNpPrRsSuUwWyYzZiI",
+                       "áÁćĆéÉǵǴḱḰĺĹḿḾóÓńŃṕṔŕŔśŚúÚẃẂýÝźŹíÍ");
   buildaccent("dacute|H|h", "oOuU", "őŐűŰ");       // double acute
   buildaccent("mathring|r", "aAuUwy",
                             "åÅůŮẘẙ"); // ring
@@ -1339,14 +1315,14 @@ static void buildAccentsMap()
                          "čČďĎǎǍěĚǐǏǒǑǔǓǧǦǩǨȟȞľĽňŇřŘšŠŤťžŽ");  // caron
   accents["hat{\\imath}"] = "î";
   accents["hat{\\jmath}"] = "ĵ";
-  buildaccent("hat|^", "aAeEiIcCgGhHjJsSwWyYzZoOuU",
-                       "âÂêÊîÎĉĈĝĜĥĤĵĴŝŜŵŴŷŶẑẐôÔûÛ");      // circ
+  buildaccent("hat|^", "aAcCeEgGhHiIjJoOsSuUwWyYzZ",
+                       "âÂĉĈêÊĝĜĥĤîÎĵĴôÔŝŜûÛŵŴŷŶẑẐ");      // circ
   accents["bar{\\imath}"] = "ī";
   buildaccent("bar|=", "aAeEiIoOuUyY",
                        "āĀēĒīĪōŌūŪȳȲ");    // macron
   accents["tilde{\\imath}"] = "ĩ";
-  buildaccent("tilde", "aAnNoOiIuU",
-                       "ãÃñÑõÕĩĨũŨ");        // tilde
+  buildaccent("tilde", "aAeEiInNoOuUvVyY",
+                       "ãÃẽẼĩĨñÑõÕũŨṽṼỹỸ");      // tilde
   accents["breve{\\imath}"] = "ĭ";
   buildaccent("breve|u", "aAeEgGiIoOuU",
                          "ăĂĕĔğĞĭĬŏŎŭŬ");  // breve
@@ -1373,6 +1349,8 @@ static void buildAccentsMap()
   accents["textroundcap{\\i}"] = "ȉ";
   buildaccent("rcap|textroundcap", "AaEeIiOoRrUu",
                                    "ȂȃȆȇȊȋȎȏȒȓȖȗ"); // inverted breve
+  buildaccent("slashed", "oO",
+                         "øØ"); // slashed
 }
 
 /*
@@ -1383,7 +1361,7 @@ void Intervall::removeAccents()
 {
   if (accents.empty())
     buildAccentsMap();
-  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)\\{[^\\{\\}]+\\}|(i|imath|jmath)(?![a-zA-Z]))");
+  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|cdot)(?![a-zA-Z]))");
   smatch sub;
   for (sregex_iterator itacc(par.begin(), par.end(), accre), end; itacc != end; ++itacc) {
     sub = *itacc;
@@ -1394,14 +1372,18 @@ void Intervall::removeAccents()
       for (size_t i = 0; i < val.size(); i++) {
         par[pos+i] = val[i];
       }
-      addIntervall(pos+val.size(), pos + sub.str(0).size());
+      // Remove possibly following space too
+      if (par[pos+sub.str(0).size()] == ' ')
+       addIntervall(pos+val.size(), pos + sub.str(0).size()+1);
+      else
+       addIntervall(pos+val.size(), pos + sub.str(0).size());
       for (size_t i = pos+val.size(); i < pos + sub.str(0).size(); i++) {
         // remove traces of any remaining chars
         par[i] = ' ';
       }
     }
     else {
-      LYXERR0("Not added accent for \"" << key << "\"");
+      LYXERR(Debug::INFO, "Not added accent for \"" << key << "\"");
     }
   }
 }
@@ -1436,7 +1418,7 @@ void Intervall::resetOpenedP(int openPos)
   closes[1] = -1;
 }
 
-int Intervall::previousNotIgnored(int start)
+int Intervall::previousNotIgnored(int start) const
 {
     int idx = 0;                          /* int intervalls */
     for (idx = ignoreidx; idx >= 0; --idx) {
@@ -1448,7 +1430,7 @@ int Intervall::previousNotIgnored(int start)
     return start;
 }
 
-int Intervall::nextNotIgnored(int start)
+int Intervall::nextNotIgnored(int start) const
 {
     int idx = 0;                          /* int intervalls */
     for (idx = 0; idx <= ignoreidx; idx++) {
@@ -1473,10 +1455,11 @@ class LatexInfo {
   void buildEntries(bool);
   void makeKey(const string &, KeyInfo, bool isPatternString);
   void processRegion(int start, int region_end); /*  remove {} parts */
-  void removeHead(KeyInfo&, int count=0);
+  void removeHead(KeyInfo const &, int count=0);
 
  public:
- LatexInfo(string par, bool isPatternString) : entidx_(-1), interval_(isPatternString, par)
+ LatexInfo(string const & par, bool isPatternString)
+        : entidx_(-1), interval_(isPatternString, par)
   {
     buildKeys(isPatternString);
     entries_ = vector<KeyInfo>();
@@ -1521,7 +1504,7 @@ class LatexInfo {
     else
       return false;
   };
-  int find(int start, KeyInfo::KeyType keytype) {
+  int find(int start, KeyInfo::KeyType keytype) const {
     if (start < 0)
       return -1;
     int tmpIdx = start;
@@ -1532,8 +1515,8 @@ class LatexInfo {
     }
     return -1;
   };
-  int process(ostringstream &os, KeyInfo &actual);
-  int dispatch(ostringstream &os, int previousStart, KeyInfo &actual);
+  int process(ostringstream & os, KeyInfo const & actual);
+  int dispatch(ostringstream & os, int previousStart, KeyInfo & actual);
   // string show(int lastpos) { return interval.show(lastpos);};
   int nextNotIgnored(int start) { return interval_.nextNotIgnored(start);};
   KeyInfo &getKeyInfo(int keyinfo) {
@@ -1543,7 +1526,7 @@ class LatexInfo {
     else
       return entries_[keyinfo];
   };
-  void setForDefaultLang(KeyInfo &defLang) {interval_.setForDefaultLang(defLang);};
+  void setForDefaultLang(KeyInfo const & defLang) {interval_.setForDefaultLang(defLang);};
   void addIntervall(int low, int up) { interval_.addIntervall(low, up); };
 };
 
@@ -1552,7 +1535,6 @@ int Intervall::findclosing(int start, int end, char up = '{', char down = '}', i
 {
   int skip = 0;
   int depth = 0;
-  repeat--;
   for (int i = start; i < end; i += 1 + skip) {
     char c;
     c = par[i];
@@ -1563,6 +1545,7 @@ int Intervall::findclosing(int start, int end, char up = '{', char down = '}', i
     }
     else if (c == down) {
       if (depth == 0) {
+        repeat--;
         if ((repeat <= 0) || (par[i+1] != up))
           return i;
       }
@@ -1586,7 +1569,7 @@ class MathInfo {
   MathInfo() {
     actualIdx_ = 0;
   }
-  void insert(string wait, size_t start, size_t end) {
+  void insert(string const & wait, size_t start, size_t end) {
     MathEntry m = MathEntry();
     m.wait = wait;
     m.mathStart = start;
@@ -1594,14 +1577,14 @@ class MathInfo {
     m.mathSize = end - start;
     entries_.push_back(m);
   }
-  bool empty() { return entries_.empty(); };
-  size_t getEndPos() {
+  bool empty() const { return entries_.empty(); };
+  size_t getEndPos() const {
     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
       return 0;
     }
     return entries_[actualIdx_].mathEnd;
   }
-  size_t getStartPos() {
+  size_t getStartPos() const {
     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
       return 100000;                    /*  definitely enough? */
     }
@@ -1611,7 +1594,7 @@ class MathInfo {
     actualIdx_ = 0;
     return getStartPos();
   }
-  size_t getSize() {
+  size_t getSize() const {
     if (entries_.empty() || (actualIdx_ >= entries_.size())) {
       return size_t(0);
     }
@@ -1903,10 +1886,20 @@ void LatexInfo::buildEntries(bool isPatternString)
         }
         found._tokensize = found.head.length();
         found._dataStart = found._tokenstart + found.head.length();
+        if (found.keytype == KeyInfo::doRemove) {
+          int endpar = 2 + interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
+          found._dataStart = endpar;
+          found._tokensize = found._dataStart - found._tokenstart;
+          closings = 0;
+        }
         if (interval_.par.substr(found._dataStart-1, 15).compare("\\endarguments{}") == 0) {
           found._dataStart += 15;
         }
-        size_t endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
+        size_t endpos;
+        if (closings < 1)
+          endpos = found._dataStart - 1;
+        else
+          endpos = interval_.findclosing(found._dataStart, interval_.par.length(), '{', '}', closings);
         if (found.keytype == KeyInfo::isList) {
           // Check if it really is list env
           static regex const listre("^([a-z]+)$");
@@ -2030,6 +2023,11 @@ void LatexInfo::buildKeys(bool isPatternString)
   // handle like standard keys with 1 parameter.
   makeKey("url|href|vref|thanks", KeyInfo(KeyInfo::isStandard, 1, false), isPatternString);
 
+  // Ignore deleted text
+  makeKey("lyxdeleted", KeyInfo(KeyInfo::doRemove, 3, false), isPatternString);
+  // but preserve added text
+  makeKey("lyxadded", KeyInfo(KeyInfo::doRemove, 2, false), isPatternString);
+
   // Macros to remove, but let the parameter survive
   // No split
   makeKey("menuitem|textmd|textrm", KeyInfo(KeyInfo::isStandard, 1, true), isPatternString);
@@ -2171,7 +2169,12 @@ void Intervall::output(ostringstream &os, int lastpos)
     printed += lastpos-i;
   }
   handleParentheses(lastpos, false);
-  for (int i = actualdeptindex; i > 0; --i) {
+  int startindex;
+  if (keys["foreignlanguage"].disabled)
+    startindex = actualdeptindex-langcount;
+  else
+    startindex = actualdeptindex;
+  for (int i = startindex; i > 0; --i) {
     os << "}";
   }
   if (hasTitle && (printed > 0))
@@ -2197,7 +2200,7 @@ void LatexInfo::processRegion(int start, int region_end)
   }
 }
 
-void LatexInfo::removeHead(KeyInfo &actual, int count)
+void LatexInfo::removeHead(KeyInfo const & actual, int count)
 {
   if (actual.parenthesiscount == 0) {
     // "{\tiny{} ...}" ==> "{{} ...}"
@@ -2326,7 +2329,25 @@ int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
         if ((interval_.par[pos] != ' ') && (interval_.par[pos] != '%'))
           break;
       }
-      interval_.addIntervall(actual._tokenstart, pos);
+      // Remove also enclosing parentheses [] and {}
+      int numpars = 0;
+      int spaces = 0;
+      while (actual._tokenstart > numpars) {
+        if (pos+numpars >= interval_.par.size())
+          break;
+        else if (interval_.par[pos+numpars] == ']' && interval_.par[actual._tokenstart-numpars-1] == '[')
+          numpars++;
+        else if (interval_.par[pos+numpars] == '}' && interval_.par[actual._tokenstart-numpars-1] == '{')
+          numpars++;
+        else
+          break;
+      }
+      if (numpars > 0) {
+        if (interval_.par[pos+numpars] == ' ')
+          spaces++;
+      }
+
+      interval_.addIntervall(actual._tokenstart-numpars, pos+numpars+spaces);
       nextKeyIdx = getNextKey();
       break;
     }
@@ -2392,7 +2413,7 @@ int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
       int val = actual._tokenstart;
       for (count = 0; count < actual._tokenstart;) {
         val = interval_.previousNotIgnored(val-1);
-        if (interval_.par[val] != ' ')
+        if (val < 0 || interval_.par[val] != ' ')
           break;
         else {
           count = actual._tokenstart - val;
@@ -2433,6 +2454,7 @@ int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
       }
       if (actual.disabled) {
         removeHead(actual);
+        interval_.langcount++;
         if ((interval_.par.substr(actual._dataStart, 3) == " \\[") ||
             (interval_.par.substr(actual._dataStart, 8) == " \\begin{")) {
           // Discard also the space before math-equation
@@ -2454,7 +2476,7 @@ int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
       // This cannot happen, already handled
       // fall through
     default: {
-      // LYXERR0("Unhandled keytype");
+      // LYXERR(Debug::INFO, "Unhandled keytype");
       nextKeyIdx = getNextKey();
       break;
     }
@@ -2462,7 +2484,7 @@ int LatexInfo::dispatch(ostringstream &os, int previousStart, KeyInfo &actual)
   return nextKeyIdx;
 }
 
-int LatexInfo::process(ostringstream &os, KeyInfo &actual )
+int LatexInfo::process(ostringstream & os, KeyInfo const & actual )
 {
   int end = interval_.nextNotIgnored(actual._dataEnd);
   int oldStart = actual._dataStart;
@@ -2494,7 +2516,7 @@ int LatexInfo::process(ostringstream &os, KeyInfo &actual )
   if (oldStart <= end) {
     processRegion(oldStart, end);
   }
-  if (interval_.par[end] == '}') {
+  if (interval_.par.size() > (size_t) end && interval_.par[end] == '}') {
     end += 1;
     // This is the normal case.
     // But if using the firstlanguage, the closing may be missing
@@ -2526,7 +2548,7 @@ string splitOnKnownMacros(string par, bool isPatternString)
 {
   ostringstream os;
   LatexInfo li(par, isPatternString);
-  // LYXERR0("Berfore split: " << par);
+  // LYXERR(Debug::INFO, "Berfore split: " << par);
   KeyInfo DummyKey = KeyInfo(KeyInfo::KeyType::isMain, 2, true);
   DummyKey.head = "";
   DummyKey._tokensize = 0;
@@ -2593,7 +2615,7 @@ string splitOnKnownMacros(string par, bool isPatternString)
   }
   else
     s = par;                            /* no known macros found */
-  // LYXERR0("After split: " << s);
+  // LYXERR(Debug::INFO, "After split: " << s);
   return s;
 }
 
@@ -2636,7 +2658,7 @@ static string correctlanguagesetting(string par, bool isPatternString, bool with
                                string a = it->first;
                                regex_with_format = true;
                                features += " " + a;
-                               // LYXERR0("Identified regex format:" << a);
+                               // LYXERR(Debug::INFO, "Identified regex format:" << a);
                        }
                        LYXERR(Debug::FIND, "Identified Features" << features);
 
@@ -2654,7 +2676,7 @@ static string correctlanguagesetting(string par, bool isPatternString, bool with
                }
        }
        else {
-               // LYXERR0("No regex formats");
+               // LYXERR(Debug::INFO, "No regex formats");
        }
        return result;
 }
@@ -2666,13 +2688,13 @@ static int identifyClosing(string & t)
        int open_braces = 0;
        do {
                LYXERR(Debug::FIND, "identifyClosing(): t now is '" << t << "'");
-               if (regex_replace(t, t, "(.*[^\\\\])\\$" REGEX_EOS, "$1"))
+               if (regex_replace(t, t, "(.*[^\\\\])\\$$", "$1"))
                        continue;
-               if (regex_replace(t, t, "(.*[^\\\\]) \\\\\\]" REGEX_EOS, "$1"))
+               if (regex_replace(t, t, "(.*[^\\\\])\\\\\\]$", "$1"))
                        continue;
-               if (regex_replace(t, t, "(.*[^\\\\]) \\\\end\\{[a-zA-Z_]*\\*?\\}" REGEX_EOS, "$1"))
+               if (regex_replace(t, t, "(.*[^\\\\])\\\\end\\{[a-zA-Z_]*\\*?\\}$", "$1"))
                        continue;
-               if (regex_replace(t, t, "(.*[^\\\\])\\}" REGEX_EOS, "$1")) {
+               if (regex_replace(t, t, "(.*[^\\\\])\\}$", "$1")) {
                        ++open_braces;
                        continue;
                }
@@ -2763,9 +2785,9 @@ MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const &
                                        lng -= 2;
                                        open_braces++;
                                }
-                               else
+       else
                                        break;
-                       }
+}
                        if (lng < par_as_string.size())
                                par_as_string = par_as_string.substr(0,lng);
                        /*
@@ -2803,10 +2825,10 @@ MatchStringAdv::MatchStringAdv(lyx::Buffer & buf, FindAndReplaceOptions const &
                        regexp2_str = "(" + lead_as_regexp + ").*?" + par_as_string;
                }
                LYXERR(Debug::FIND, "Setting regexp to : '" << regexp_str << "'");
-               regexp = lyx::regex(regexp_str);
+               regexp = regex(regexp_str);
 
                LYXERR(Debug::FIND, "Setting regexp2 to: '" << regexp2_str << "'");
-               regexp2 = lyx::regex(regexp2_str);
+               regexp2 = regex(regexp2_str);
        }
 }
 
@@ -2922,9 +2944,9 @@ MatchResult MatchStringAdv::findAux(DocIterator const & cur, int len, bool at_be
                if (m.size() > 1)
                        leadingsize = m[1].second - m[1].first;
                int result;
-                for (size_t i = 0; i < m.size(); i++) {
-                  LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
-                }
+               for (size_t i = 0; i < m.size(); i++) {
+                       LYXERR(Debug::FIND, "Match " << i << " is " << m[i].second - m[i].first << " long");
+               }
                if (close_wildcards == 0)
                        result = m[0].second - m[0].first;
 
@@ -2989,32 +3011,37 @@ MatchResult MatchStringAdv::operator()(DocIterator const & cur, int len, bool at
               << ", inTexted=" << cur.inTexted());
        if (res == 0 || !at_begin || !opt.matchword || !cur.inTexted())
                return mres;
-        if ((len > 0) && (res < len)) {
+       if ((len > 0) && (res < len)) {
          mres.match_len = 0;
-          return mres;
+         return mres;
        }
        Paragraph const & par = cur.paragraph();
        bool ws_left = (cur.pos() > 0)
                ? par.isWordSeparator(cur.pos() - 1)
                : true;
-       bool ws_right = (cur.pos() + len < par.size())
+       bool ws_right;
+       if (len < 0)
+               ws_right = true;
+       else {
+               ws_right = (cur.pos() + len < par.size())
                ? par.isWordSeparator(cur.pos() + len)
                : true;
+       }
        LYXERR(Debug::FIND,
               "cur.pos()=" << cur.pos() << ", res=" << res
               << ", separ: " << ws_left << ", " << ws_right
-               << ", len: " << len
+              << ", len: " << len
               << endl);
        if (ws_left && ws_right) {
-          // Check for word separators inside the found 'word'
-          for (int i = 0; i < len; i++) {
-            if (par.isWordSeparator(cur.pos() + i)) {
+         // Check for word separators inside the found 'word'
+         for (int i = 0; i < len; i++) {
+           if (par.isWordSeparator(cur.pos() + i)) {
              mres.match_len = 0;
-              return mres;
+             return mres;
            }
-          }
-          return mres;
-        }
+         }
+         return mres;
+       }
        mres.match_len = 0;
        return mres;
 }
@@ -3092,7 +3119,7 @@ docstring stringifyFromCursor(DocIterator const & cur, int len)
                // OutputParams runparams(&cur.buffer()->params().encoding());
                OutputParams runparams(encodings.fromLyXName("utf8"));
                runparams.nice = true;
-               runparams.flavor = OutputParams::XETEX;
+               runparams.flavor = FLAVOR::XETEX;
                runparams.linelen = 10000; //lyxrc.plaintext_linelen;
                // No side effect of file copying and image conversion
                runparams.dryrun = true;
@@ -3138,7 +3165,7 @@ docstring latexifyFromCursor(DocIterator const & cur, int len)
        //OutputParams runparams(&buf.params().encoding());
        OutputParams runparams(encodings.fromLyXName("utf8"));
        runparams.nice = false;
-       runparams.flavor = OutputParams::XETEX;
+       runparams.flavor = FLAVOR::XETEX;
        runparams.linelen = 8000; //lyxrc.plaintext_linelen;
        // No side effect of file copying and image conversion
        runparams.dryrun = true;
@@ -3272,7 +3299,7 @@ int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
             } while (cur.depth() > old_cur.depth()); /* Skip inner insets */
             if (cur.depth() < old_cur.depth()) {
               // Outer inset?
-              LYXERR0("cur.depth() < old_cur.depth(), this should never happen");
+              LYXERR(Debug::INFO, "cur.depth() < old_cur.depth(), this should never happen");
               break;
             }
             if (cur.pos() != old_cur.pos()) {
@@ -3290,7 +3317,7 @@ int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
               }
             }
             else {
-              LYXERR0("cur.pos() == old_cur.pos(), this should never happen");
+              LYXERR(Debug::INFO, "cur.pos() == old_cur.pos(), this should never happen");
               actual_match = match(cur, len).match_len;
               if (actual_match == max_match)
                 old_cur = cur;
@@ -3302,7 +3329,7 @@ int findAdvFinalize(DocIterator & cur, MatchStringAdv const & match)
 
 
 /// Finds forward
-int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
+int findForwardAdv(DocIterator & cur, MatchStringAdv const & match)
 {
        if (!cur)
                return 0;
@@ -3312,7 +3339,7 @@ int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
                int match_len = mres.match_len;
                LYXERR(Debug::FIND, "match_len: " << match_len);
                if ((mres.pos > 100000) || (mres.match2end > 100000) || (match_len > 100000)) {
-                       LYXERR0("BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
+                       LYXERR(Debug::INFO, "BIG LENGTHS: " << mres.pos << ", " << match_len << ", " << mres.match2end);
                        match_len = 0;
                }
                if (match_len > 0) {
@@ -3376,10 +3403,9 @@ int findForwardAdv(DocIterator & cur, MatchStringAdv & match)
                                                match_len_zero_count = 0;
                                }
                                else {
-                                        if (++match_len_zero_count > 3) {
-                                                LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
-                                                match_len_zero_count = 0;
-                                        }
+                                       if (++match_len_zero_count > 3) {
+                                               LYXERR(Debug::FIND, "match_len2_zero_count: " << match_len_zero_count << ", match_len was " << match_len);
+                                       }
                                        break;
                                }
                        }
@@ -3488,13 +3514,13 @@ docstring stringifyFromForSearch(FindAndReplaceOptions const & opt,
 
 
 FindAndReplaceOptions::FindAndReplaceOptions(
-       docstring const & find_buf_name, bool casesensitive,
-       bool matchword, bool forward, bool expandmacros, bool ignoreformat,
-       docstring const & repl_buf_name, bool keep_case,
-       SearchScope scope, SearchRestriction restr, bool replace_all)
-       : find_buf_name(find_buf_name), casesensitive(casesensitive), matchword(matchword),
-         forward(forward), expandmacros(expandmacros), ignoreformat(ignoreformat),
-         repl_buf_name(repl_buf_name), keep_case(keep_case), scope(scope), restr(restr), replace_all(replace_all)
+       docstring const & _find_buf_name, bool _casesensitive,
+       bool _matchword, bool _forward, bool _expandmacros, bool _ignoreformat,
+       docstring const & _repl_buf_name, bool _keep_case,
+       SearchScope _scope, SearchRestriction _restr, bool _replace_all)
+       : find_buf_name(_find_buf_name), casesensitive(_casesensitive), matchword(_matchword),
+         forward(_forward), expandmacros(_expandmacros), ignoreformat(_ignoreformat),
+         repl_buf_name(_repl_buf_name), keep_case(_keep_case), scope(_scope), restr(_restr), replace_all(_replace_all)
 {
 }
 
@@ -3546,7 +3572,7 @@ static bool firstUppercase(Cursor const & cur)
 static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase others_case)
 {
        ParagraphList::iterator pit = buffer.paragraphs().begin();
-       LASSERT(pit->size() >= 1, /**/);
+       LASSERT(!pit->empty(), /**/);
        pos_type right = pos_type(1);
        pit->changeCase(buffer.params(), pos_type(0), right, first_case);
        right = pit->size();
@@ -3559,7 +3585,7 @@ static void changeFirstCase(Buffer & buffer, TextCase first_case, TextCase other
 static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, MatchStringAdv & matchAdv)
 {
        Cursor & cur = bv->cursor();
-       if (opt.repl_buf_name == docstring()
+       if (opt.repl_buf_name.empty()
            || theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true) == 0
            || theBufferList().getBuffer(FileName(to_utf8(opt.find_buf_name)), true) == 0)
                return 0;
@@ -3581,7 +3607,7 @@ static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, Ma
                return 0;
 
        // Build a copy of the replace buffer, adapted to the KeepCase option
-       Buffer & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
+       Buffer const & repl_buffer_orig = *theBufferList().getBuffer(FileName(to_utf8(opt.repl_buf_name)), true);
        ostringstream oss;
        repl_buffer_orig.write(oss);
        string lyx = oss.str();
@@ -3615,7 +3641,7 @@ static int findAdvReplace(BufferView * bv, FindAndReplaceOptions const & opt, Ma
                // OutputParams runparams(&repl_buffer.params().encoding());
                OutputParams runparams(encodings.fromLyXName("utf8"));
                runparams.nice = false;
-               runparams.flavor = OutputParams::XETEX;
+               runparams.flavor = FLAVOR::XETEX;
                runparams.linelen = 8000; //lyxrc.plaintext_linelen;
                runparams.dryrun = true;
                TeXOnePar(repl_buffer, repl_buffer.text(), 0, os, runparams);