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, ' ');
325 while (is && !status) {
327 unsigned char c = cc;
329 if (c == commentChar) {
330 // Read rest of line (fast :-)
332 // That is not fast... (Lgb)
336 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
338 // unfortunately ignore is buggy (Lgb)
339 is.ignore(100, '\n');
351 bool escaped = false;
354 if (c == '\r') continue;
356 // escape the next char
359 if (c == '\"' || c == '\\')
362 buff.push_back('\\');
366 if (!escaped && c == '\"')
368 } while (c != '\n' && is);
377 } while (c != '\"' && c != '\n' && is);
382 printError("Missing quote");
387 buff.resize(buff.size() - 1);
393 continue; /* Skip ','s */
395 // using relational operators with chars other
396 // than == and != is not safe. And if it is done
397 // the type _have_ to be unsigned. It usually a
398 // lot better to use the functions from cctype
403 if (esc && c == '\\') {
404 // escape the next char
412 } while (c > ' ' && c != ',' && is);
416 if (c == '\r' && is) {
417 // The Windows support has lead to the
418 // possibility of "\r\n" at the end of
419 // a line. This will stop LyX choking
420 // when it expected to find a '\n'
432 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
438 int Lexer::Pimpl::searchKeyword(char const * const tag) const
440 LexerKeyword search_tag = { tag, 0 };
442 lower_bound(table, table + no_items,
443 search_tag, CompareTags());
444 // use the compare_ascii_no_case instead of compare_no_case,
445 // because in turkish, 'i' is not the lowercase version of 'I',
446 // and thus turkish locale breaks parsing of tags.
447 if (res != table + no_items
448 && !compare_ascii_no_case(res->tag, tag))
454 int Lexer::Pimpl::lex()
456 //NOTE: possible bug.
457 if (next() && status == LEX_TOKEN)
458 return searchKeyword(getString().c_str());
463 bool Lexer::Pimpl::eatLine()
467 unsigned char c = '\0';
469 while (is && c != '\n') {
472 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
479 buff.resize(buff.size() - 1);
482 } else if (buff.length() > 0) { // last line
491 bool Lexer::Pimpl::nextToken()
493 if (!pushTok.empty()) {
494 // There can have been a whole line pushed so
495 // we extract the first word and leaves the rest
497 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
499 pushTok = split(pushTok, buff, ' ');
509 while (is && !status) {
514 if ((c >= ' ' || c == '\t') && is) {
517 if (c == '\\') { // first char == '\\'
522 } while (c > ' ' && c != '\\' && is);
528 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
532 is.putback(c); // put it back
543 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
549 bool Lexer::Pimpl::inputAvailable()
555 void Lexer::Pimpl::pushToken(string const & pt)
563 //////////////////////////////////////////////////////////////////////
567 //////////////////////////////////////////////////////////////////////
570 : pimpl_(new Pimpl(0, 0)), lastReadOk_(false)
574 void Lexer::init(LexerKeyword * tab, int num)
576 pimpl_ = new Pimpl(tab, num);
586 bool Lexer::isOK() const
588 return pimpl_->inputAvailable();
592 void Lexer::setLineNumber(int l)
598 int Lexer::lineNumber() const
600 return pimpl_->lineno;
604 istream & Lexer::getStream()
610 void Lexer::pushTable(LexerKeyword * tab, int num)
612 pimpl_->pushTable(tab, num);
616 void Lexer::popTable()
622 void Lexer::printTable(ostream & os)
624 pimpl_->printTable(os);
628 void Lexer::printError(string const & message) const
630 pimpl_->printError(message);
634 bool Lexer::setFile(FileName const & filename)
636 return pimpl_->setFile(filename);
640 void Lexer::setStream(istream & i)
642 pimpl_->setStream(i);
646 void Lexer::setCommentChar(char c)
648 pimpl_->setCommentChar(c);
654 return pimpl_->lex();
658 int Lexer::getInteger() const
660 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
662 pimpl_->printError("integer token missing");
666 if (isStrInt(pimpl_->getString()))
667 return convert<int>(pimpl_->getString());
670 pimpl_->printError("Bad integer `$$Token'");
675 double Lexer::getFloat() const
677 // replace comma with dot in case the file was written with
678 // the wrong locale (should be rare, but is easy enough to
680 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
682 pimpl_->printError("float token missing");
686 string const str = subst(pimpl_->getString(), ",", ".");
688 return convert<double>(str);
691 pimpl_->printError("Bad float `$$Token'");
696 string const Lexer::getString(bool trim) const
698 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
701 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
707 docstring const Lexer::getDocString(bool trim) const
709 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
712 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
718 // I would prefer to give a tag number instead of an explicit token
719 // here, but it is not possible because Buffer::readDocument uses
720 // explicit tokens (JMarc)
721 docstring Lexer::getLongString(docstring const & endtoken)
725 bool firstline = true;
727 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
729 // blank line in the file being read
731 docstring tmpstr = getDocString();
732 docstring const token = trim(tmpstr, " \t");
734 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
736 // We do a case independent comparison, like searchKeyword does.
737 if (compare_no_case(token, endtoken) == 0)
741 size_t i = tmpstr.find_first_not_of(char_type(' '));
742 if (i != string::npos)
743 prefix = tmpstr.substr(0, i);
745 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
748 // further lines in long strings may have the same
749 // whitespace prefix as the first line. Remove it.
750 if (prefix.length() && prefixIs(tmpstr, prefix))
751 tmpstr.erase(0, prefix.length() - 1);
753 str += ltrim(tmpstr, "\t") + '\n';
757 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
763 bool Lexer::getBool() const
765 string const s = pimpl_->getString();
766 if (s == "false" || s == "0") {
770 if (s == "true" || s == "1") {
774 pimpl_->printError("Bad boolean `$$Token'. "
775 "Use \"false\" or \"true\"");
781 bool Lexer::eatLine()
783 return pimpl_->eatLine();
787 bool Lexer::next(bool esc)
789 return pimpl_->next(esc);
793 bool Lexer::nextToken()
795 return pimpl_->nextToken();
799 void Lexer::pushToken(string const & pt)
801 pimpl_->pushToken(pt);
805 Lexer::operator void const *() const
807 // This behaviour is NOT the same as the streams which would
808 // use fail() here. However, our implementation of getString() et al.
809 // can cause the eof() and fail() bits to be set, even though we
810 // haven't tried to read 'em.
811 return lastReadOk_? this : 0;
815 bool Lexer::operator!() const
821 Lexer & Lexer::operator>>(string & s)
833 Lexer & Lexer::operator>>(docstring & s)
845 Lexer & Lexer::operator>>(double & s)
857 Lexer & Lexer::operator>>(int & s)
869 Lexer & Lexer::operator>>(unsigned int & s)
881 Lexer & Lexer::operator>>(bool & s)
893 Lexer & Lexer::operator>>(char & c)
903 // quotes a string, e.g. for use in preferences files or as an argument
904 // of the "log" dialog
905 string Lexer::quoteString(string const & arg)
909 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
915 // same for docstring
916 docstring Lexer::quoteString(docstring const & arg)
920 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
921 from_ascii("\""), from_ascii("\\\""));
927 Lexer & Lexer::operator>>(char const * required)
931 if (token != required) {
932 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
933 << ". Got " << token << " instead. Line: " << lineNumber());
940 bool Lexer::checkFor(char const * required)
944 if (token == required)
951 void Lexer::setContext(std::string const & str)
953 pimpl_->context = str;