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.
18 #include "support/convert.h"
19 #include "support/debug.h"
20 #include "support/FileName.h"
21 #include "support/filetools.h"
22 #include "support/gzstream.h"
23 #include "support/lstrings.h"
24 #include "support/lyxalgo.h"
25 #include "support/types.h"
33 using namespace lyx::support;
37 //////////////////////////////////////////////////////////////////////
41 //////////////////////////////////////////////////////////////////////
48 Pimpl(LexerKeyword * tab, int num);
50 string const getString() const;
52 docstring const getDocString() const;
54 void printError(string const & message) const;
56 void printTable(ostream & os);
58 void pushTable(LexerKeyword * tab, int num);
62 bool setFile(FileName const & filename);
64 void setStream(istream & i);
66 void setCommentChar(char c);
68 bool next(bool esc = false);
70 int searchKeyword(char const * const tag) const;
77 /// test if there is a pushed token or the stream is ok
78 bool inputAvailable();
80 void pushToken(string const &);
81 /// fb_ is only used to open files, the stream is accessed through is.
84 /// gz_ is only used to open files, the stream is accessed through is.
87 /// the stream that we use.
105 /// used for error messages
109 Pimpl(Pimpl const &);
110 void operator=(Pimpl const &);
119 : table_elem(0), table_siz(0) {}
121 PushedTable(LexerKeyword * ki, int siz)
122 : table_elem(ki), table_siz(siz) {}
124 LexerKeyword * table_elem;
129 stack<PushedTable> pushed;
137 : public binary_function<LexerKeyword, LexerKeyword, bool> {
139 // used by lower_bound, sort and sorted
140 bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
142 // we use the ascii version, because in turkish, 'i'
143 // is not the lowercase version of 'I', and thus
144 // turkish locale breaks parsing of tags.
145 return compare_ascii_no_case(a.tag, b.tag) < 0;
149 } // end of anon namespace
152 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
153 : is(&fb_), table(tab), no_items(num),
154 status(0), lineno(0), commentChar('#')
160 string const Lexer::Pimpl::getString() const
166 docstring const Lexer::Pimpl::getDocString() const
168 return from_utf8(buff);
172 void Lexer::Pimpl::printError(string const & message) const
174 string const tmpmsg = subst(message, "$$Token", getString());
175 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
176 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
180 void Lexer::Pimpl::printTable(ostream & os)
182 os << "\nNumber of tags: " << no_items << endl;
183 for (int i= 0; i < no_items; ++i)
185 << "]: tag: `" << table[i].tag
186 << "' code:" << table[i].code << '\n';
191 void Lexer::Pimpl::verifyTable()
193 // Check if the table is sorted and if not, sort it.
195 && !lyx::sorted(table, table + no_items, CompareTags())) {
196 lyxerr << "The table passed to Lexer is not sorted!\n"
197 << "Tell the developers to fix it!" << endl;
198 // We sort it anyway to avoid problems.
199 lyxerr << "\nUnsorted:" << endl;
202 sort(table, table + no_items, CompareTags());
203 lyxerr << "\nSorted:" << endl;
209 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
211 PushedTable tmppu(table, no_items);
221 void Lexer::Pimpl::popTable()
223 if (pushed.empty()) {
224 lyxerr << "Lexer error: nothing to pop!" << endl;
228 PushedTable tmp = pushed.top();
230 table = tmp.table_elem;
231 no_items = tmp.table_siz;
235 bool Lexer::Pimpl::setFile(FileName const & filename)
237 // Check the format of the file.
238 string const format = filename.guessFormatFromContents();
240 if (format == "gzip" || format == "zip" || format == "compress") {
241 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
242 // The check only outputs a debug message, because it triggers
243 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
244 // a fresh new filebuf. (JMarc)
245 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
246 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
247 "file or stream already set.");
248 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
250 name = filename.absFilename();
252 return gz_.is_open() && is.good();
254 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
256 // The check only outputs a debug message, because it triggers
257 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
258 // a fresh new filebuf. (JMarc)
259 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
260 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
261 "file or stream already set.");
263 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
265 name = filename.absFilename();
267 return fb_.is_open() && is.good();
272 void Lexer::Pimpl::setStream(istream & i)
274 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
275 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
276 "file or stream already set.");
283 void Lexer::Pimpl::setCommentChar(char c)
289 bool Lexer::Pimpl::next(bool esc /* = false */)
291 if (!pushTok.empty()) {
292 // There can have been a whole line pushed so
293 // we extract the first word and leaves the rest
295 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
297 pushTok = split(pushTok, buff, ' ');
307 unsigned char c = 0; // getc() returns an int
310 while (is && !status) {
314 if (c == commentChar) {
315 // Read rest of line (fast :-)
317 // That is not fast... (Lgb)
321 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
323 // unfortunately ignore is buggy (Lgb)
324 is.ignore(100, '\n');
335 bool escaped = false;
340 if (c == '\r') continue;
342 // escape the next char
345 if (c == '\"' || c == '\\')
348 buff.push_back('\\');
352 if (!escaped && c == '\"')
354 } while (c != '\n' && is);
363 } while (c != '\"' && c != '\n' && is);
368 printError("Missing quote");
373 buff.resize(buff.size() - 1);
379 continue; /* Skip ','s */
381 // using relational operators with chars other
382 // than == and != is not safe. And if it is done
383 // the type _have_ to be unsigned. It usually a
384 // lot better to use the functions from cctype
389 if (esc && c == '\\') {
390 // escape the next char
398 } while (c > ' ' && c != ',' && is);
402 if (c == '\r' && is) {
403 // The Windows support has lead to the
404 // possibility of "\r\n" at the end of
405 // a line. This will stop LyX choking
406 // when it expected to find a '\n'
418 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
424 int Lexer::Pimpl::searchKeyword(char const * const tag) const
426 LexerKeyword search_tag = { tag, 0 };
428 lower_bound(table, table + no_items,
429 search_tag, CompareTags());
430 // use the compare_ascii_no_case instead of compare_no_case,
431 // because in turkish, 'i' is not the lowercase version of 'I',
432 // and thus turkish locale breaks parsing of tags.
433 if (res != table + no_items
434 && !compare_ascii_no_case(res->tag, tag))
440 int Lexer::Pimpl::lex()
442 //NOTE: possible bug.
443 if (next() && status == LEX_TOKEN)
444 return searchKeyword(getString().c_str());
449 bool Lexer::Pimpl::eatLine()
453 unsigned char c = '\0';
455 while (is && c != '\n') {
458 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
465 buff.resize(buff.size() - 1);
468 } else if (buff.length() > 0) { // last line
477 bool Lexer::Pimpl::nextToken()
479 if (!pushTok.empty()) {
480 // There can have been a whole line pushed so
481 // we extract the first word and leaves the rest
483 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
485 pushTok = split(pushTok, buff, ' ');
495 while (is && !status) {
500 if (c >= ' ' && is) {
503 if (c == '\\') { // first char == '\\'
508 } while (c > ' ' && c != '\\' && is);
514 } while (c >= ' ' && c != '\\' && is);
518 is.putback(c); // put it back
529 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
535 bool Lexer::Pimpl::inputAvailable()
541 void Lexer::Pimpl::pushToken(string const & pt)
549 //////////////////////////////////////////////////////////////////////
553 //////////////////////////////////////////////////////////////////////
556 : pimpl_(new Pimpl(0, 0))
560 void Lexer::init(LexerKeyword * tab, int num)
562 pimpl_ = new Pimpl(tab, num);
572 bool Lexer::isOK() const
574 return pimpl_->inputAvailable();
578 void Lexer::setLineNumber(int l)
584 int Lexer::lineNumber() const
586 return pimpl_->lineno;
590 istream & Lexer::getStream()
596 void Lexer::pushTable(LexerKeyword * tab, int num)
598 pimpl_->pushTable(tab, num);
602 void Lexer::popTable()
608 void Lexer::printTable(ostream & os)
610 pimpl_->printTable(os);
614 void Lexer::printError(string const & message) const
616 pimpl_->printError(message);
620 bool Lexer::setFile(FileName const & filename)
622 return pimpl_->setFile(filename);
626 void Lexer::setStream(istream & i)
628 pimpl_->setStream(i);
632 void Lexer::setCommentChar(char c)
634 pimpl_->setCommentChar(c);
639 return pimpl_->lex();
643 int Lexer::getInteger() const
645 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
647 pimpl_->printError("integer token missing");
651 if (isStrInt(pimpl_->getString()))
652 return convert<int>(pimpl_->getString());
655 pimpl_->printError("Bad integer `$$Token'");
660 double Lexer::getFloat() const
662 // replace comma with dot in case the file was written with
663 // the wrong locale (should be rare, but is easy enough to
665 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
667 pimpl_->printError("float token missing");
671 string const str = subst(pimpl_->getString(), ",", ".");
673 return convert<double>(str);
676 pimpl_->printError("Bad float `$$Token'");
681 string const Lexer::getString() const
683 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
686 return pimpl_->getString();
692 docstring const Lexer::getDocString() const
694 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
697 return pimpl_->getDocString();
703 // I would prefer to give a tag number instead of an explicit token
704 // here, but it is not possible because Buffer::readDocument uses
705 // explicit tokens (JMarc)
706 string const Lexer::getLongString(string const & endtoken)
710 bool firstline = true;
712 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
714 // blank line in the file being read
717 string const token = trim(getString(), " \t");
719 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
721 // We do a case independent comparison, like searchKeyword does.
722 if (compare_ascii_no_case(token, endtoken) == 0)
725 string tmpstr = getString();
727 size_t i = tmpstr.find_first_not_of(' ');
728 if (i != string::npos)
729 prefix = tmpstr.substr(0, i);
731 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
734 // further lines in long strings may have the same
735 // whitespace prefix as the first line. Remove it.
736 if (prefix.length() && prefixIs(tmpstr, prefix))
737 tmpstr.erase(0, prefix.length() - 1);
739 str += ltrim(tmpstr, "\t") + '\n';
743 printError("Long string not ended by `" + endtoken + '\'');
749 bool Lexer::getBool() const
751 string const s = pimpl_->getString();
752 if (s == "false" || s == "0") {
756 if (s == "true" || s == "1") {
760 pimpl_->printError("Bad boolean `$$Token'. "
761 "Use \"false\" or \"true\"");
766 bool Lexer::eatLine()
768 return pimpl_->eatLine();
772 bool Lexer::next(bool esc)
774 return pimpl_->next(esc);
778 bool Lexer::nextToken()
780 return pimpl_->nextToken();
784 void Lexer::pushToken(string const & pt)
786 pimpl_->pushToken(pt);
790 Lexer::operator void const *() const
792 // This behaviour is NOT the same as the streams which would
793 // use fail() here. However, our implementation of getString() et al.
794 // can cause the eof() and fail() bits to be set, even though we
795 // haven't tried to read 'em.
796 return lastReadOk_? this : 0;
800 bool Lexer::operator!() const
806 Lexer & Lexer::operator>>(string & s)
818 Lexer & Lexer::operator>>(docstring & s)
830 Lexer & Lexer::operator>>(double & s)
842 Lexer & Lexer::operator>>(int & s)
854 Lexer & Lexer::operator>>(unsigned int & s)
866 Lexer & Lexer::operator>>(bool & s)
878 Lexer & Lexer::operator>>(char & c)
888 // quotes a string, e.g. for use in preferences files or as an argument
889 // of the "log" dialog
890 string Lexer::quoteString(string const & arg)
894 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
900 Lexer & Lexer::operator>>(char const * required)
904 if (token != required) {
905 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
906 << ". Got " << token << " instead. Line: " << lineNumber());
913 bool Lexer::checkFor(char const * required)
917 if (token == required)
924 void Lexer::setContext(std::string const & str)
926 pimpl_->context = str;