]> git.lyx.org Git - lyx.git/blobdiff - src/Lexer.cpp
Account for old versions of Pygments
[lyx.git] / src / Lexer.cpp
index fd9a1f362c302ce3460d7a2f076a6ab5c05c685b..bbae12418c0bd1da6abfd542a6cdbc63b2e1976b 100644 (file)
@@ -4,7 +4,7 @@
  * Licence details can be found in the file COPYING.
  *
  * \author Alejandro Aguilar Sierra
- * \author Lars Gullik Bjønnes
+ * \author Lars Gullik Bjønnes
  * \author Jean-Marc Lasgouttes
  * \author John Levon
  *
 #include <config.h>
 
 #include "Lexer.h"
+#include "Format.h"
 
 #include "support/convert.h"
 #include "support/debug.h"
 #include "support/FileName.h"
 #include "support/filetools.h"
 #include "support/gzstream.h"
+#include "support/lassert.h"
 #include "support/lstrings.h"
 #include "support/lyxalgo.h"
 #include "support/types.h"
@@ -45,7 +47,7 @@ namespace lyx {
 class Lexer::Pimpl {
 public:
        ///
-       Pimpl(keyword_item * tab, int num);
+       Pimpl(LexerKeyword * tab, int num);
        ///
        string const getString() const;
        ///
@@ -55,7 +57,7 @@ public:
        ///
        void printTable(ostream & os);
        ///
-       void pushTable(keyword_item * tab, int num);
+       void pushTable(LexerKeyword * tab, int num);
        ///
        void popTable();
        ///
@@ -67,7 +69,7 @@ public:
        ///
        bool next(bool esc = false);
        ///
-       int search_kw(char const * const tag) const;
+       int searchKeyword(char const * const tag) const;
        ///
        int lex();
        ///
@@ -89,7 +91,7 @@ public:
        ///
        string name;
        ///
-       keyword_item * table;
+       LexerKeyword * table;
        ///
        int no_items;
        ///
@@ -102,6 +104,8 @@ public:
        string pushTok;
        ///
        char commentChar;
+       /// used for error messages
+       string context;
 private:
        /// non-copyable
        Pimpl(Pimpl const &);
@@ -116,10 +120,10 @@ private:
                PushedTable()
                        : table_elem(0), table_siz(0) {}
                ///
-               PushedTable(keyword_item * ki, int siz)
+               PushedTable(LexerKeyword * ki, int siz)
                        : table_elem(ki), table_siz(siz) {}
                ///
-               keyword_item * table_elem;
+               LexerKeyword * table_elem;
                ///
                int table_siz;
        };
@@ -132,10 +136,10 @@ private:
 namespace {
 
 class CompareTags
-       : public binary_function<keyword_item, keyword_item, bool> {
+       : public binary_function<LexerKeyword, LexerKeyword, bool> {
 public:
        // used by lower_bound, sort and sorted
-       bool operator()(keyword_item const & a, keyword_item const & b) const
+       bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
        {
                // we use the ascii version, because in turkish, 'i'
                // is not the lowercase version of 'I', and thus
@@ -147,7 +151,7 @@ public:
 } // end of anon namespace
 
 
-Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
+Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
        : is(&fb_), table(tab), no_items(num),
          status(0), lineno(0), commentChar('#')
 {
@@ -171,7 +175,9 @@ void Lexer::Pimpl::printError(string const & message) const
 {
        string const tmpmsg = subst(message, "$$Token", getString());
        lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
-               << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
+               << " of file " << to_utf8(makeDisplayPath(name))
+               << " current token: '" << getString() << "'"
+               << " context: '" << context << "']" << endl;
 }
 
 
@@ -204,7 +210,7 @@ void Lexer::Pimpl::verifyTable()
 }
 
 
-void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
+void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
 {
        PushedTable tmppu(table, no_items);
        pushed.push(tmppu);
@@ -233,9 +239,7 @@ void Lexer::Pimpl::popTable()
 bool Lexer::Pimpl::setFile(FileName const & filename)
 {
        // Check the format of the file.
-       string const format = filename.guessFormatFromContents();
-
-       if (format == "gzip" || format == "zip" || format == "compress") {
+       if (theFormats().isZippedFile(filename)) {
                LYXERR(Debug::LYXLEX, "lyxlex: compressed");
                // The check only outputs a debug message, because it triggers
                // a bug in compaq cxx 6.2, where is_open() returns 'true' for
@@ -245,9 +249,10 @@ bool Lexer::Pimpl::setFile(FileName const & filename)
                                "file or stream already set.");
                gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
                is.rdbuf(&gz_);
-               name = filename.absFilename();
+               name = filename.absFileName();
                lineno = 0;
-               return gz_.is_open() && is.good();
+               if (!gz_.is_open() || !is.good())
+                       return false;
        } else {
                LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
 
@@ -258,12 +263,25 @@ bool Lexer::Pimpl::setFile(FileName const & filename)
                        LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
                                "file or stream already set.");
                }
-               fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
+               fb_.open(filename.toSafeFilesystemEncoding().c_str(), ios::in);
                is.rdbuf(&fb_);
-               name = filename.absFilename();
+               name = filename.absFileName();
                lineno = 0;
-               return fb_.is_open() && is.good();
+               if (!fb_.is_open() || !is.good())
+                       return false;
+       }
+
+       // Skip byte order mark.
+       if (is.peek() == 0xef) {
+               is.get();
+               if (is.peek() == 0xbb) {
+                       is.get();
+                       LASSERT(is.get() == 0xbf, /**/);
+               } else
+                       is.unget();
        }
+
+       return true;
 }
 
 
@@ -300,125 +318,37 @@ bool Lexer::Pimpl::next(bool esc /* = false */)
                status = LEX_TOKEN;
                return true;
        }
-       if (!esc) {
-               unsigned char c = 0; // getc() returns an int
-               char cc = 0;
-               status = 0;
-               while (is && !status) {
-                       is.get(cc);
-                       c = cc;
-                       if (c == commentChar) {
-                               // Read rest of line (fast :-)
-#if 1
-                               // That is not fast... (Lgb)
-                               string dummy;
-                               getline(is, dummy);
-
-                               LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
-#else
-                               // unfortunately ignore is buggy (Lgb)
-                               is.ignore(100, '\n');
-#endif
-                               ++lineno;
-                               continue;
-                       }
-
-                       if (c == '\"') {
-                               buff.clear();
-
-                               do {
-                                       is.get(cc);
-                                       c = cc;
-                                       if (c != '\r')
-                                               buff.push_back(c);
-                               } while (c != '\"' && c != '\n' && is);
-
-                               if (c != '\"') {
-                                       printError("Missing quote");
-                                       if (c == '\n')
-                                               ++lineno;
-                               }
-
-                               buff.resize(buff.size()-1);
-                               status = LEX_DATA;
-                               break;
-                       }
-
-                       if (c == ',')
-                               continue;              /* Skip ','s */
-
-                               // using relational operators with chars other
-                               // than == and != is not safe. And if it is done
-                               // the type _have_ to be unsigned. It usually a
-                               // lot better to use the functions from cctype
-                       if (c > ' ' && is)  {
-                               buff.clear();
-
-                               do {
-                                       buff.push_back(c);
-                                       is.get(cc);
-                                       c = cc;
-                               } while (c > ' ' && c != ',' && is);
-
-                               status = LEX_TOKEN;
-                       }
-
-                       if (c == '\r' && is) {
-                               // The Windows support has lead to the
-                               // possibility of "\r\n" at the end of
-                               // a line.  This will stop LyX choking
-                               // when it expected to find a '\n'
-                               is.get(cc);
-                               c = cc;
-                       }
 
-                       if (c == '\n')
-                               ++lineno;
-
-               }
-               if (status)
-                       return true;
-
-               status = is.eof() ? LEX_FEOF: LEX_UNDEF;
-               buff.clear();
-               return false;
-       } else {
-               unsigned char c = 0; // getc() returns an int
-               char cc = 0;
 
-               status = 0;
-               while (is && !status) {
-                       is.get(cc);
-                       c = cc;
-
-                       // skip ','s
-                       if (c == ',')
-                               continue;
+       char cc = 0;
+       status = 0;
+       while (is && !status) {
+               is.get(cc);
+               unsigned char c = cc;
 
-                       if (c == commentChar) {
-                               // Read rest of line (fast :-)
+               if (c == commentChar) {
+                       // Read rest of line (fast :-)
 #if 1
-                               // That is still not fast... (Lgb)
-                               string dummy;
-                               getline(is, dummy);
+                       // That is not fast... (Lgb)
+                       string dummy;
+                       getline(is, dummy);
 
-                               LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
+                       LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
 #else
-                               // but ignore is also still buggy (Lgb)
-                               // This is fast (Lgb)
-                               is.ignore(100, '\n');
+                       // unfortunately ignore is buggy (Lgb)
+                       is.ignore(100, '\n');
 #endif
-                               ++lineno;
-                               continue;
-                       }
+                       ++lineno;
+                       continue;
+               }
+
+               if (c == '\"') {
+                       buff.clear();
 
-                       // string
-                       if (c == '\"') {
-                               buff.clear();
+                       if (esc) {
 
-                               bool escaped = false;
                                do {
-                                       escaped = false;
+                                       bool escaped = false;
                                        is.get(cc);
                                        c = cc;
                                        if (c == '\r') continue;
@@ -437,53 +367,78 @@ bool Lexer::Pimpl::next(bool esc /* = false */)
                                                break;
                                } while (c != '\n' && is);
 
-                               if (c != '\"') {
-                                       printError("Missing quote");
-                                       if (c == '\n')
-                                               ++lineno;
-                               }
+                       } else {
+
+                               do {
+                                       is.get(cc);
+                                       c = cc;
+                                       if (c != '\r')
+                                               buff.push_back(c);
+                               } while (c != '\"' && c != '\n' && is);
 
-                               buff.resize(buff.size() -1);
-                               status = LEX_DATA;
-                               break;
                        }
 
-                       if (c > ' ' && is) {
-                               buff.clear();
+                       if (c != '\"') {
+                               printError("Missing quote");
+                               if (c == '\n')
+                                       ++lineno;
+                       }
 
-                               do {
-                                       if (c == '\\') {
-                                               // escape the next char
-                                               is.get(cc);
-                                               c = cc;
-                                               //escaped = true;
-                                       }
-                                       buff.push_back(c);
+                       buff.resize(buff.size() - 1);
+                       status = LEX_DATA;
+                       break;
+               }
+
+               if (c == ',')
+                       continue;              /* Skip ','s */
+
+               // using relational operators with chars other
+               // than == and != is not safe. And if it is done
+               // the type _have_ to be unsigned. It usually a
+               // lot better to use the functions from cctype
+               if (c > ' ' && is)  {
+                       buff.clear();
+
+                       do {
+                               if (esc && c == '\\') {
+                                       // escape the next char
                                        is.get(cc);
                                        c = cc;
-                               } while (c > ' ' && c != ',' && is);
+                                       //escaped = true;
+                               }
+                               buff.push_back(c);
+                               is.get(cc);
+                               c = cc;
+                       } while (c > ' ' && c != ',' && is);
+                       status = LEX_TOKEN;
+               }
 
-                               status = LEX_TOKEN;
-                       }
-                       // new line
-                       if (c == '\n')
-                               ++lineno;
+               if (c == '\r' && is) {
+                       // The Windows support has lead to the
+                       // possibility of "\r\n" at the end of
+                       // a line.  This will stop LyX choking
+                       // when it expected to find a '\n'
+                       is.get(cc);
+                       c = cc;
                }
 
-               if (status)
-                       return true;
+               if (c == '\n')
+                       ++lineno;
 
-               status = is.eof() ? LEX_FEOF : LEX_UNDEF;
-               buff.clear();
-               return false;
        }
+       if (status)
+               return true;
+
+       status = is.eof() ? LEX_FEOF: LEX_UNDEF;
+       buff.clear();
+       return false;
 }
 
 
-int Lexer::Pimpl::search_kw(char const * const tag) const
+int Lexer::Pimpl::searchKeyword(char const * const tag) const
 {
-       keyword_item search_tag = { tag, 0 };
-       keyword_item * res =
+       LexerKeyword search_tag = { tag, 0 };
+       LexerKeyword * res =
                lower_bound(table, table + no_items,
                            search_tag, CompareTags());
        // use the compare_ascii_no_case instead of compare_no_case,
@@ -500,7 +455,7 @@ int Lexer::Pimpl::lex()
 {
        //NOTE: possible bug.
        if (next() && status == LEX_TOKEN)
-               return search_kw(getString().c_str());
+               return searchKeyword(getString().c_str());
        return status;
 }
 
@@ -515,7 +470,7 @@ bool Lexer::Pimpl::eatLine()
                is.get(cc);
                c = cc;
                //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
-               if (c != '\r')
+               if (c != '\r' && is)
                        buff.push_back(c);
        }
 
@@ -556,7 +511,7 @@ bool Lexer::Pimpl::nextToken()
                char cc = 0;
                is.get(cc);
                c = cc;
-               if (c >= ' ' && is) {
+               if ((c >= ' ' || c == '\t') && is) {
                        buff.clear();
 
                        if (c == '\\') { // first char == '\\'
@@ -570,7 +525,7 @@ bool Lexer::Pimpl::nextToken()
                                        buff.push_back(c);
                                        is.get(cc);
                                        c = cc;
-                               } while (c >= ' ' && c != '\\' && is);
+                               } while ((c >= ' ' || c == '\t') && c != '\\' && is);
                        }
 
                        if (c == '\\')
@@ -611,11 +566,17 @@ void Lexer::Pimpl::pushToken(string const & pt)
 //
 //////////////////////////////////////////////////////////////////////
 
-Lexer::Lexer(keyword_item * tab, int num)
-       : pimpl_(new Pimpl(tab, num))
+Lexer::Lexer()
+       : pimpl_(new Pimpl(0, 0)), lastReadOk_(false)
 {}
 
 
+void Lexer::init(LexerKeyword * tab, int num)
+{
+        pimpl_ = new Pimpl(tab, num);
+}
+
+
 Lexer::~Lexer()
 {
        delete pimpl_;
@@ -628,13 +589,13 @@ bool Lexer::isOK() const
 }
 
 
-void Lexer::setLineNo(int l)
+void Lexer::setLineNumber(int l)
 {
        pimpl_->lineno = l;
 }
 
 
-int Lexer::getLineNo() const
+int Lexer::lineNumber() const
 {
        return pimpl_->lineno;
 }
@@ -646,7 +607,7 @@ istream & Lexer::getStream()
 }
 
 
-void Lexer::pushTable(keyword_item * tab, int num)
+void Lexer::pushTable(LexerKeyword * tab, int num)
 {
        pimpl_->pushTable(tab, num);
 }
@@ -687,6 +648,7 @@ void Lexer::setCommentChar(char c)
        pimpl_->setCommentChar(c);
 }
 
+
 int Lexer::lex()
 {
        return pimpl_->lex();
@@ -731,23 +693,23 @@ double Lexer::getFloat() const
 }
 
 
-string const Lexer::getString() const
+string const Lexer::getString(bool trim) const
 {
        lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
 
        if (lastReadOk_)
-       return pimpl_->getString();
+               return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
 
        return string();
 }
 
 
-docstring const Lexer::getDocString() const
+docstring const Lexer::getDocString(bool trim) const
 {
        lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
 
        if (lastReadOk_)
-               return pimpl_->getDocString();
+               return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
 
        return docstring();
 }
@@ -756,28 +718,27 @@ docstring const Lexer::getDocString() const
 // I would prefer to give a tag number instead of an explicit token
 // here, but it is not possible because Buffer::readDocument uses
 // explicit tokens (JMarc)
-string const Lexer::getLongString(string const & endtoken)
+docstring Lexer::getLongString(docstring const & endtoken)
 {
-       string str;
-       string prefix;
+       docstring str;
+       docstring prefix;
        bool firstline = true;
 
        while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
                if (!eatLine())
                        // blank line in the file being read
                        continue;
+               docstring tmpstr = getDocString();
+               docstring const token = trim(tmpstr, " \t");
 
-               string const token = trim(getString(), " \t");
-
-               LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
+               LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
 
-               // We do a case independent comparison, like search_kw does.
-               if (compare_ascii_no_case(token, endtoken) == 0)
+               // We do a case independent comparison, like searchKeyword does.
+               if (compare_no_case(token, endtoken) == 0)
                        break;
 
-               string tmpstr = getString();
                if (firstline) {
-                       size_t i = tmpstr.find_first_not_of(' ');
+                       size_t i = tmpstr.find_first_not_of(char_type(' '));
                        if (i != string::npos)
                                prefix = tmpstr.substr(0, i);
                        firstline = false;
@@ -793,7 +754,7 @@ string const Lexer::getLongString(string const & endtoken)
        }
 
        if (!pimpl_->is)
-               printError("Long string not ended by `" + endtoken + '\'');
+               printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
 
        return str;
 }
@@ -801,15 +762,18 @@ string const Lexer::getLongString(string const & endtoken)
 
 bool Lexer::getBool() const
 {
-       if (pimpl_->getString() == "true") {
+       string const s = pimpl_->getString();   
+       if (s == "false" || s == "0") {
+               lastReadOk_ = true;
+               return false;
+       }
+       if (s == "true" || s == "1") {
                lastReadOk_ = true;
                return true;
-       } else if (pimpl_->getString() != "false") {
-               pimpl_->printError("Bad boolean `$$Token'. "
-                                  "Use \"false\" or \"true\"");
-               lastReadOk_ = false;
        }
-       lastReadOk_ = true;
+       pimpl_->printError("Bad boolean `$$Token'. "
+                                "Use \"false\" or \"true\"");
+       lastReadOk_ = false;
        return false;
 }
 
@@ -926,9 +890,19 @@ Lexer & Lexer::operator>>(bool & s)
 }
 
 
+Lexer & Lexer::operator>>(char & c)
+{
+       string s;
+       operator>>(s);
+       if (!s.empty())
+               c = s[0];
+       return *this;
+}
+
+
 // quotes a string, e.g. for use in preferences files or as an argument
 // of the "log" dialog
-string const Lexer::quoteString(string const & arg)
+string Lexer::quoteString(string const & arg)
 {
        string res;
        res += '"';
@@ -938,4 +912,46 @@ string const Lexer::quoteString(string const & arg)
 }
 
 
+// same for docstring
+docstring Lexer::quoteString(docstring const & arg)
+{
+       docstring res;
+       res += '"';
+       res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")), 
+                    from_ascii("\""), from_ascii("\\\""));
+       res += '"';
+       return res;
+}
+
+
+Lexer & Lexer::operator>>(char const * required)
+{
+       string token;
+       *this >> token;
+       if (token != required) {
+               LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context 
+                       << ". Got " << token << " instead. Line: " << lineNumber());
+               pushToken(token);
+       }
+       return *this;
+}
+
+
+bool Lexer::checkFor(char const * required)
+{
+       string token;
+       *this >> token;
+       if (token == required)
+               return true;
+       pushToken(token);
+       return false;
+}
+
+
+void Lexer::setContext(std::string const & str)
+{
+       pimpl_->context = str;
+}
+
+
 } // namespace lyx