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)
242 // tex2lyx does not read lyxrc and therefore can't really check for
246 // Check the format of the file.
247 if (formats.isZippedFile(filename)) {
249 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
250 // The check only outputs a debug message, because it triggers
251 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
252 // a fresh new filebuf. (JMarc)
253 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
254 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
255 "file or stream already set.");
256 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
258 name = filename.absFileName();
260 if (!gz_.is_open() || !is.good())
263 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
265 // The check only outputs a debug message, because it triggers
266 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
267 // a fresh new filebuf. (JMarc)
268 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
269 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
270 "file or stream already set.");
272 fb_.open(filename.toSafeFilesystemEncoding().c_str(), ios::in);
274 name = filename.absFileName();
276 if (!fb_.is_open() || !is.good())
280 // Skip byte order mark.
281 if (is.peek() == 0xef) {
283 if (is.peek() == 0xbb) {
285 LASSERT(is.get() == 0xbf, /**/);
294 void Lexer::Pimpl::setStream(istream & i)
296 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
297 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
298 "file or stream already set.");
305 void Lexer::Pimpl::setCommentChar(char c)
311 bool Lexer::Pimpl::next(bool esc /* = false */)
313 if (!pushTok.empty()) {
314 // There can have been a whole line pushed so
315 // we extract the first word and leaves the rest
317 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
319 pushTok = split(pushTok, buff, ' ');
329 unsigned char c = 0; // getc() returns an int
332 while (is && !status) {
336 if (c == commentChar) {
337 // Read rest of line (fast :-)
339 // That is not fast... (Lgb)
343 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
345 // unfortunately ignore is buggy (Lgb)
346 is.ignore(100, '\n');
357 bool escaped = false;
362 if (c == '\r') continue;
364 // escape the next char
367 if (c == '\"' || c == '\\')
370 buff.push_back('\\');
374 if (!escaped && c == '\"')
376 } while (c != '\n' && is);
385 } while (c != '\"' && c != '\n' && is);
390 printError("Missing quote");
395 buff.resize(buff.size() - 1);
401 continue; /* Skip ','s */
403 // using relational operators with chars other
404 // than == and != is not safe. And if it is done
405 // the type _have_ to be unsigned. It usually a
406 // lot better to use the functions from cctype
411 if (esc && c == '\\') {
412 // escape the next char
420 } while (c > ' ' && c != ',' && is);
424 if (c == '\r' && is) {
425 // The Windows support has lead to the
426 // possibility of "\r\n" at the end of
427 // a line. This will stop LyX choking
428 // when it expected to find a '\n'
440 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
446 int Lexer::Pimpl::searchKeyword(char const * const tag) const
448 LexerKeyword search_tag = { tag, 0 };
450 lower_bound(table, table + no_items,
451 search_tag, CompareTags());
452 // use the compare_ascii_no_case instead of compare_no_case,
453 // because in turkish, 'i' is not the lowercase version of 'I',
454 // and thus turkish locale breaks parsing of tags.
455 if (res != table + no_items
456 && !compare_ascii_no_case(res->tag, tag))
462 int Lexer::Pimpl::lex()
464 //NOTE: possible bug.
465 if (next() && status == LEX_TOKEN)
466 return searchKeyword(getString().c_str());
471 bool Lexer::Pimpl::eatLine()
475 unsigned char c = '\0';
477 while (is && c != '\n') {
480 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
487 buff.resize(buff.size() - 1);
490 } else if (buff.length() > 0) { // last line
499 bool Lexer::Pimpl::nextToken()
501 if (!pushTok.empty()) {
502 // There can have been a whole line pushed so
503 // we extract the first word and leaves the rest
505 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
507 pushTok = split(pushTok, buff, ' ');
517 while (is && !status) {
522 if ((c >= ' ' || c == '\t') && is) {
525 if (c == '\\') { // first char == '\\'
530 } while (c > ' ' && c != '\\' && is);
536 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
540 is.putback(c); // put it back
551 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
557 bool Lexer::Pimpl::inputAvailable()
563 void Lexer::Pimpl::pushToken(string const & pt)
571 //////////////////////////////////////////////////////////////////////
575 //////////////////////////////////////////////////////////////////////
578 : pimpl_(new Pimpl(0, 0))
582 void Lexer::init(LexerKeyword * tab, int num)
584 pimpl_ = new Pimpl(tab, num);
594 bool Lexer::isOK() const
596 return pimpl_->inputAvailable();
600 void Lexer::setLineNumber(int l)
606 int Lexer::lineNumber() const
608 return pimpl_->lineno;
612 istream & Lexer::getStream()
618 void Lexer::pushTable(LexerKeyword * tab, int num)
620 pimpl_->pushTable(tab, num);
624 void Lexer::popTable()
630 void Lexer::printTable(ostream & os)
632 pimpl_->printTable(os);
636 void Lexer::printError(string const & message) const
638 pimpl_->printError(message);
642 bool Lexer::setFile(FileName const & filename)
644 return pimpl_->setFile(filename);
648 void Lexer::setStream(istream & i)
650 pimpl_->setStream(i);
654 void Lexer::setCommentChar(char c)
656 pimpl_->setCommentChar(c);
662 return pimpl_->lex();
666 int Lexer::getInteger() const
668 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
670 pimpl_->printError("integer token missing");
674 if (isStrInt(pimpl_->getString()))
675 return convert<int>(pimpl_->getString());
678 pimpl_->printError("Bad integer `$$Token'");
683 double Lexer::getFloat() const
685 // replace comma with dot in case the file was written with
686 // the wrong locale (should be rare, but is easy enough to
688 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
690 pimpl_->printError("float token missing");
694 string const str = subst(pimpl_->getString(), ",", ".");
696 return convert<double>(str);
699 pimpl_->printError("Bad float `$$Token'");
704 string const Lexer::getString() const
706 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
709 return pimpl_->getString();
715 docstring const Lexer::getDocString() const
717 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
720 return pimpl_->getDocString();
726 // I would prefer to give a tag number instead of an explicit token
727 // here, but it is not possible because Buffer::readDocument uses
728 // explicit tokens (JMarc)
729 string const Lexer::getLongString(string const & endtoken)
733 bool firstline = true;
735 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
737 // blank line in the file being read
740 string const token = trim(getString(), " \t");
742 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
744 // We do a case independent comparison, like searchKeyword does.
745 if (compare_ascii_no_case(token, endtoken) == 0)
748 string tmpstr = getString();
750 size_t i = tmpstr.find_first_not_of(' ');
751 if (i != string::npos)
752 prefix = tmpstr.substr(0, i);
754 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
757 // further lines in long strings may have the same
758 // whitespace prefix as the first line. Remove it.
759 if (prefix.length() && prefixIs(tmpstr, prefix))
760 tmpstr.erase(0, prefix.length() - 1);
762 str += ltrim(tmpstr, "\t") + '\n';
766 printError("Long string not ended by `" + endtoken + '\'');
772 bool Lexer::getBool() const
774 string const s = pimpl_->getString();
775 if (s == "false" || s == "0") {
779 if (s == "true" || s == "1") {
783 pimpl_->printError("Bad boolean `$$Token'. "
784 "Use \"false\" or \"true\"");
790 bool Lexer::eatLine()
792 return pimpl_->eatLine();
796 bool Lexer::next(bool esc)
798 return pimpl_->next(esc);
802 bool Lexer::nextToken()
804 return pimpl_->nextToken();
808 void Lexer::pushToken(string const & pt)
810 pimpl_->pushToken(pt);
814 Lexer::operator void const *() const
816 // This behaviour is NOT the same as the streams which would
817 // use fail() here. However, our implementation of getString() et al.
818 // can cause the eof() and fail() bits to be set, even though we
819 // haven't tried to read 'em.
820 return lastReadOk_? this : 0;
824 bool Lexer::operator!() const
830 Lexer & Lexer::operator>>(string & s)
842 Lexer & Lexer::operator>>(docstring & s)
854 Lexer & Lexer::operator>>(double & s)
866 Lexer & Lexer::operator>>(int & s)
878 Lexer & Lexer::operator>>(unsigned int & s)
890 Lexer & Lexer::operator>>(bool & s)
902 Lexer & Lexer::operator>>(char & c)
912 // quotes a string, e.g. for use in preferences files or as an argument
913 // of the "log" dialog
914 string Lexer::quoteString(string const & arg)
918 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
924 // same for docstring
925 docstring Lexer::quoteString(docstring const & arg)
929 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
930 from_ascii("\""), from_ascii("\\\""));
936 Lexer & Lexer::operator>>(char const * required)
940 if (token != required) {
941 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
942 << ". Got " << token << " instead. Line: " << lineNumber());
949 bool Lexer::checkFor(char const * required)
953 if (token == required)
960 void Lexer::setContext(std::string const & str)
962 pimpl_->context = str;