3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
11 * Full author contact details are available in file CREDITS.
19 #include "support/convert.h"
20 #include "support/debug.h"
21 #include "support/FileName.h"
22 #include "support/filetools.h"
23 #include "support/gzstream.h"
24 #include "support/lassert.h"
25 #include "support/lstrings.h"
26 #include "support/lyxalgo.h"
27 #include "support/types.h"
35 using namespace lyx::support;
39 //////////////////////////////////////////////////////////////////////
43 //////////////////////////////////////////////////////////////////////
50 Pimpl(LexerKeyword * tab, int num);
52 string const getString() const;
54 docstring const getDocString() const;
56 void printError(string const & message) const;
58 void printTable(ostream & os);
60 void pushTable(LexerKeyword * tab, int num);
64 bool setFile(FileName const & filename);
66 void setStream(istream & i);
68 void setCommentChar(char c);
70 bool next(bool esc = false);
72 int searchKeyword(char const * const tag) const;
79 /// test if there is a pushed token or the stream is ok
80 bool inputAvailable();
82 void pushToken(string const &);
83 /// fb_ is only used to open files, the stream is accessed through is.
86 /// gz_ is only used to open files, the stream is accessed through is.
89 /// the stream that we use.
107 /// used for error messages
111 Pimpl(Pimpl const &);
112 void operator=(Pimpl const &);
121 : table_elem(0), table_siz(0) {}
123 PushedTable(LexerKeyword * ki, int siz)
124 : table_elem(ki), table_siz(siz) {}
126 LexerKeyword * table_elem;
131 stack<PushedTable> pushed;
139 : public binary_function<LexerKeyword, LexerKeyword, bool> {
141 // used by lower_bound, sort and sorted
142 bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
144 // we use the ascii version, because in turkish, 'i'
145 // is not the lowercase version of 'I', and thus
146 // turkish locale breaks parsing of tags.
147 return compare_ascii_no_case(a.tag, b.tag) < 0;
151 } // end of anon namespace
154 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
155 : is(&fb_), table(tab), no_items(num),
156 status(0), lineno(0), commentChar('#')
162 string const Lexer::Pimpl::getString() const
168 docstring const Lexer::Pimpl::getDocString() const
170 return from_utf8(buff);
174 void Lexer::Pimpl::printError(string const & message) const
176 string const tmpmsg = subst(message, "$$Token", getString());
177 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
178 << " of file " << to_utf8(makeDisplayPath(name))
179 << " current token: '" << getString() << "'"
180 << " context: '" << context << "']" << endl;
184 void Lexer::Pimpl::printTable(ostream & os)
186 os << "\nNumber of tags: " << no_items << endl;
187 for (int i= 0; i < no_items; ++i)
189 << "]: tag: `" << table[i].tag
190 << "' code:" << table[i].code << '\n';
195 void Lexer::Pimpl::verifyTable()
197 // Check if the table is sorted and if not, sort it.
199 && !lyx::sorted(table, table + no_items, CompareTags())) {
200 lyxerr << "The table passed to Lexer is not sorted!\n"
201 << "Tell the developers to fix it!" << endl;
202 // We sort it anyway to avoid problems.
203 lyxerr << "\nUnsorted:" << endl;
206 sort(table, table + no_items, CompareTags());
207 lyxerr << "\nSorted:" << endl;
213 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
215 PushedTable tmppu(table, no_items);
225 void Lexer::Pimpl::popTable()
227 if (pushed.empty()) {
228 lyxerr << "Lexer error: nothing to pop!" << endl;
232 PushedTable tmp = pushed.top();
234 table = tmp.table_elem;
235 no_items = tmp.table_siz;
239 bool Lexer::Pimpl::setFile(FileName const & filename)
241 // Check the format of the file.
242 if (formats.isZippedFile(filename)) {
243 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
244 // The check only outputs a debug message, because it triggers
245 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
246 // a fresh new filebuf. (JMarc)
247 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
248 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
249 "file or stream already set.");
250 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
252 name = filename.absFileName();
254 if (!gz_.is_open() || !is.good())
257 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
259 // The check only outputs a debug message, because it triggers
260 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
261 // a fresh new filebuf. (JMarc)
262 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
263 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
264 "file or stream already set.");
266 fb_.open(filename.toSafeFilesystemEncoding().c_str(), ios::in);
268 name = filename.absFileName();
270 if (!fb_.is_open() || !is.good())
274 // Skip byte order mark.
275 if (is.peek() == 0xef) {
277 if (is.peek() == 0xbb) {
279 LASSERT(is.get() == 0xbf, /**/);
288 void Lexer::Pimpl::setStream(istream & i)
290 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
291 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
292 "file or stream already set.");
299 void Lexer::Pimpl::setCommentChar(char c)
305 bool Lexer::Pimpl::next(bool esc /* = false */)
307 if (!pushTok.empty()) {
308 // There can have been a whole line pushed so
309 // we extract the first word and leaves the rest
311 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
313 pushTok = split(pushTok, buff, ' ');
323 unsigned char c = 0; // getc() returns an int
326 while (is && !status) {
330 if (c == commentChar) {
331 // Read rest of line (fast :-)
333 // That is not fast... (Lgb)
337 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
339 // unfortunately ignore is buggy (Lgb)
340 is.ignore(100, '\n');
351 bool escaped = false;
356 if (c == '\r') continue;
358 // escape the next char
361 if (c == '\"' || c == '\\')
364 buff.push_back('\\');
368 if (!escaped && c == '\"')
370 } while (c != '\n' && is);
379 } while (c != '\"' && c != '\n' && is);
384 printError("Missing quote");
389 buff.resize(buff.size() - 1);
395 continue; /* Skip ','s */
397 // using relational operators with chars other
398 // than == and != is not safe. And if it is done
399 // the type _have_ to be unsigned. It usually a
400 // lot better to use the functions from cctype
405 if (esc && c == '\\') {
406 // escape the next char
414 } while (c > ' ' && c != ',' && is);
418 if (c == '\r' && is) {
419 // The Windows support has lead to the
420 // possibility of "\r\n" at the end of
421 // a line. This will stop LyX choking
422 // when it expected to find a '\n'
434 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
440 int Lexer::Pimpl::searchKeyword(char const * const tag) const
442 LexerKeyword search_tag = { tag, 0 };
444 lower_bound(table, table + no_items,
445 search_tag, CompareTags());
446 // use the compare_ascii_no_case instead of compare_no_case,
447 // because in turkish, 'i' is not the lowercase version of 'I',
448 // and thus turkish locale breaks parsing of tags.
449 if (res != table + no_items
450 && !compare_ascii_no_case(res->tag, tag))
456 int Lexer::Pimpl::lex()
458 //NOTE: possible bug.
459 if (next() && status == LEX_TOKEN)
460 return searchKeyword(getString().c_str());
465 bool Lexer::Pimpl::eatLine()
469 unsigned char c = '\0';
471 while (is && c != '\n') {
474 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
481 buff.resize(buff.size() - 1);
484 } else if (buff.length() > 0) { // last line
493 bool Lexer::Pimpl::nextToken()
495 if (!pushTok.empty()) {
496 // There can have been a whole line pushed so
497 // we extract the first word and leaves the rest
499 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
501 pushTok = split(pushTok, buff, ' ');
511 while (is && !status) {
516 if ((c >= ' ' || c == '\t') && is) {
519 if (c == '\\') { // first char == '\\'
524 } while (c > ' ' && c != '\\' && is);
530 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
534 is.putback(c); // put it back
545 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
551 bool Lexer::Pimpl::inputAvailable()
557 void Lexer::Pimpl::pushToken(string const & pt)
565 //////////////////////////////////////////////////////////////////////
569 //////////////////////////////////////////////////////////////////////
572 : pimpl_(new Pimpl(0, 0)), lastReadOk_(false)
576 void Lexer::init(LexerKeyword * tab, int num)
578 pimpl_ = new Pimpl(tab, num);
588 bool Lexer::isOK() const
590 return pimpl_->inputAvailable();
594 void Lexer::setLineNumber(int l)
600 int Lexer::lineNumber() const
602 return pimpl_->lineno;
606 istream & Lexer::getStream()
612 void Lexer::pushTable(LexerKeyword * tab, int num)
614 pimpl_->pushTable(tab, num);
618 void Lexer::popTable()
624 void Lexer::printTable(ostream & os)
626 pimpl_->printTable(os);
630 void Lexer::printError(string const & message) const
632 pimpl_->printError(message);
636 bool Lexer::setFile(FileName const & filename)
638 return pimpl_->setFile(filename);
642 void Lexer::setStream(istream & i)
644 pimpl_->setStream(i);
648 void Lexer::setCommentChar(char c)
650 pimpl_->setCommentChar(c);
656 return pimpl_->lex();
660 int Lexer::getInteger() const
662 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
664 pimpl_->printError("integer token missing");
668 if (isStrInt(pimpl_->getString()))
669 return convert<int>(pimpl_->getString());
672 pimpl_->printError("Bad integer `$$Token'");
677 double Lexer::getFloat() const
679 // replace comma with dot in case the file was written with
680 // the wrong locale (should be rare, but is easy enough to
682 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
684 pimpl_->printError("float token missing");
688 string const str = subst(pimpl_->getString(), ",", ".");
690 return convert<double>(str);
693 pimpl_->printError("Bad float `$$Token'");
698 string const Lexer::getString() const
700 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
703 return pimpl_->getString();
709 docstring const Lexer::getDocString() const
711 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
714 return pimpl_->getDocString();
720 // I would prefer to give a tag number instead of an explicit token
721 // here, but it is not possible because Buffer::readDocument uses
722 // explicit tokens (JMarc)
723 string const Lexer::getLongString(string const & endtoken)
727 bool firstline = true;
729 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
731 // blank line in the file being read
734 string const token = trim(getString(), " \t");
736 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
738 // We do a case independent comparison, like searchKeyword does.
739 if (compare_ascii_no_case(token, endtoken) == 0)
742 string tmpstr = getString();
744 size_t i = tmpstr.find_first_not_of(' ');
745 if (i != string::npos)
746 prefix = tmpstr.substr(0, i);
748 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
751 // further lines in long strings may have the same
752 // whitespace prefix as the first line. Remove it.
753 if (prefix.length() && prefixIs(tmpstr, prefix))
754 tmpstr.erase(0, prefix.length() - 1);
756 str += ltrim(tmpstr, "\t") + '\n';
760 printError("Long string not ended by `" + endtoken + '\'');
766 bool Lexer::getBool() const
768 string const s = pimpl_->getString();
769 if (s == "false" || s == "0") {
773 if (s == "true" || s == "1") {
777 pimpl_->printError("Bad boolean `$$Token'. "
778 "Use \"false\" or \"true\"");
784 bool Lexer::eatLine()
786 return pimpl_->eatLine();
790 bool Lexer::next(bool esc)
792 return pimpl_->next(esc);
796 bool Lexer::nextToken()
798 return pimpl_->nextToken();
802 void Lexer::pushToken(string const & pt)
804 pimpl_->pushToken(pt);
808 Lexer::operator void const *() const
810 // This behaviour is NOT the same as the streams which would
811 // use fail() here. However, our implementation of getString() et al.
812 // can cause the eof() and fail() bits to be set, even though we
813 // haven't tried to read 'em.
814 return lastReadOk_? this : 0;
818 bool Lexer::operator!() const
824 Lexer & Lexer::operator>>(string & s)
836 Lexer & Lexer::operator>>(docstring & s)
848 Lexer & Lexer::operator>>(double & s)
860 Lexer & Lexer::operator>>(int & s)
872 Lexer & Lexer::operator>>(unsigned int & s)
884 Lexer & Lexer::operator>>(bool & s)
896 Lexer & Lexer::operator>>(char & c)
906 // quotes a string, e.g. for use in preferences files or as an argument
907 // of the "log" dialog
908 string Lexer::quoteString(string const & arg)
912 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
918 // same for docstring
919 docstring Lexer::quoteString(docstring const & arg)
923 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
924 from_ascii("\""), from_ascii("\\\""));
930 Lexer & Lexer::operator>>(char const * required)
934 if (token != required) {
935 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
936 << ". Got " << token << " instead. Line: " << lineNumber());
943 bool Lexer::checkFor(char const * required)
947 if (token == required)
954 void Lexer::setContext(std::string const & str)
956 pimpl_->context = str;