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/lassert.h"
24 #include "support/lstrings.h"
25 #include "support/lyxalgo.h"
27 #include <algorithm> // sort, lower_bound
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 /// gz_ is only used to open files, the stream is accessed through is.
86 /// the stream that we use.
102 /// used for error messages
108 Pimpl(Pimpl const &);
109 void operator=(Pimpl const &);
118 : table_elem(nullptr), table_siz(0) {}
120 PushedTable(LexerKeyword * ki, int siz)
121 : table_elem(ki), table_siz(siz) {}
123 LexerKeyword * table_elem;
128 stack<PushedTable> pushed;
134 // used by lower_bound, sort and sorted
135 bool compareTags(LexerKeyword const & a, LexerKeyword const & b)
137 // we use the ascii version, because in turkish, 'i'
138 // is not the lowercase version of 'I', and thus
139 // turkish locale breaks parsing of tags.
140 return compare_ascii_no_case(a.tag, b.tag) < 0;
147 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
148 : is(&gz_), table(tab), no_items(num),
149 status(0), lineno(0), commentChar('#')
155 string const Lexer::Pimpl::getString() const
161 docstring const Lexer::Pimpl::getDocString() const
163 return from_utf8(buff);
167 void Lexer::Pimpl::printError(string const & message) const
169 string const tmpmsg = subst(message, "$$Token", getString());
170 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
171 << " of file " << to_utf8(makeDisplayPath(name))
172 << " current token: '" << getString() << "'"
173 << " context: '" << context << "']" << endl;
177 void Lexer::Pimpl::printTable(ostream & os)
179 os << "\nNumber of tags: " << no_items << endl;
180 for (int i= 0; i < no_items; ++i)
182 << "]: tag: `" << table[i].tag
183 << "' code:" << table[i].code << '\n';
188 void Lexer::Pimpl::verifyTable()
190 // Check if the table is sorted and if not, sort it.
192 && !lyx::sorted(table, table + no_items, &compareTags)) {
193 lyxerr << "The table passed to Lexer is not sorted!\n"
194 << "Tell the developers to fix it!" << endl;
195 // We sort it anyway to avoid problems.
196 lyxerr << "\nUnsorted:" << endl;
199 sort(table, table + no_items, &compareTags);
200 lyxerr << "\nSorted:" << endl;
206 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
208 PushedTable tmppu(table, no_items);
218 void Lexer::Pimpl::popTable()
220 if (pushed.empty()) {
221 lyxerr << "Lexer error: nothing to pop!" << endl;
225 PushedTable tmp = pushed.top();
227 table = tmp.table_elem;
228 no_items = tmp.table_siz;
232 bool Lexer::Pimpl::setFile(FileName const & filename)
234 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
235 LYXERR0("Error in LyXLex::setFile: file or stream already set.");
236 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
238 name = filename.absFileName();
240 if (!gz_.is_open() || !is.good())
243 // Skip byte order mark.
244 if (is.peek() == 0xef) {
246 if (is.peek() == 0xbb) {
248 LASSERT(is.get() == 0xbf, /**/);
257 void Lexer::Pimpl::setStream(istream & i)
259 if (gz_.is_open() || istream::off_type(is.tellg()) > 0)
260 LYXERR0("Error in Lexer::setStream: file or stream already set.");
266 void Lexer::Pimpl::setCommentChar(char c)
272 bool Lexer::Pimpl::next(bool esc /* = false */)
274 if (!pushTok.empty()) {
275 // There can have been a whole line pushed so
276 // we extract the first word and leaves the rest
278 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
280 pushTok = split(pushTok, buff, ' ');
292 while (is && !status) {
294 unsigned char c = cc;
296 if (c == commentChar) {
297 // Read rest of line (fast :-)
299 // That is not fast... (Lgb)
303 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
305 // unfortunately ignore is buggy (Lgb)
306 is.ignore(100, '\n');
318 bool escaped = false;
321 if (c == '\r') continue;
323 // escape the next char
326 if (c == '\"' || c == '\\')
329 buff.push_back('\\');
333 if (!escaped && c == '\"')
335 } while (c != '\n' && is);
344 } while (c != '\"' && c != '\n' && is);
349 printError("Missing quote");
354 buff.resize(buff.size() - 1);
360 continue; /* Skip ','s */
362 // using relational operators with chars other
363 // than == and != is not safe. And if it is done
364 // the type _have_ to be unsigned. It usually a
365 // lot better to use the functions from cctype
370 if (esc && c == '\\') {
371 // escape the next char
379 } while (c > ' ' && c != ',' && is);
383 if (c == '\r' && is) {
384 // The Windows support has lead to the
385 // possibility of "\r\n" at the end of
386 // a line. This will stop LyX choking
387 // when it expected to find a '\n'
399 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
405 int Lexer::Pimpl::searchKeyword(char const * const tag) const
407 LexerKeyword search_tag = { tag, 0 };
409 lower_bound(table, table + no_items,
410 search_tag, &compareTags);
411 // use the compare_ascii_no_case instead of compare_no_case,
412 // because in turkish, 'i' is not the lowercase version of 'I',
413 // and thus turkish locale breaks parsing of tags.
414 if (res != table + no_items
415 && !compare_ascii_no_case(res->tag, tag))
421 int Lexer::Pimpl::lex()
423 //NOTE: possible bug.
424 if (next() && status == LEX_TOKEN)
425 return searchKeyword(getString().c_str());
430 bool Lexer::Pimpl::eatLine()
434 unsigned char c = '\0';
436 while (is && c != '\n') {
439 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
446 buff.resize(buff.size() - 1);
449 } else if (buff.length() > 0) { // last line
458 bool Lexer::Pimpl::nextToken()
460 if (!pushTok.empty()) {
461 // There can have been a whole line pushed so
462 // we extract the first word and leaves the rest
464 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
466 pushTok = split(pushTok, buff, ' ');
476 while (is && !status) {
481 if ((c >= ' ' || c == '\t') && is) {
484 if (c == '\\') { // first char == '\\'
489 } while (c > ' ' && c != '\\' && is);
495 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
499 is.putback(c); // put it back
510 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
516 bool Lexer::Pimpl::inputAvailable()
522 void Lexer::Pimpl::pushToken(string const & pt)
530 //////////////////////////////////////////////////////////////////////
534 //////////////////////////////////////////////////////////////////////
537 : pimpl_(new Pimpl(nullptr, 0)), lastReadOk_(false)
541 void Lexer::init(LexerKeyword * tab, int num)
543 pimpl_ = new Pimpl(tab, num);
553 bool Lexer::isOK() const
555 return pimpl_->inputAvailable();
559 void Lexer::setLineNumber(int l)
565 int Lexer::lineNumber() const
567 return pimpl_->lineno;
571 istream & Lexer::getStream()
577 void Lexer::pushTable(LexerKeyword * tab, int num)
579 pimpl_->pushTable(tab, num);
583 void Lexer::popTable()
589 void Lexer::printTable(ostream & os)
591 pimpl_->printTable(os);
595 void Lexer::printError(string const & message) const
597 pimpl_->printError(message);
601 bool Lexer::setFile(FileName const & filename)
603 return pimpl_->setFile(filename);
607 void Lexer::setStream(istream & i)
609 pimpl_->setStream(i);
613 void Lexer::setCommentChar(char c)
615 pimpl_->setCommentChar(c);
621 return pimpl_->lex();
625 int Lexer::getInteger() const
627 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
629 pimpl_->printError("integer token missing");
633 if (isStrInt(pimpl_->getString()))
634 return convert<int>(pimpl_->getString());
637 pimpl_->printError("Bad integer `$$Token'");
642 double Lexer::getFloat() const
644 // replace comma with dot in case the file was written with
645 // the wrong locale (should be rare, but is easy enough to
647 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
649 pimpl_->printError("float token missing");
653 string const str = subst(pimpl_->getString(), ",", ".");
655 return convert<double>(str);
658 pimpl_->printError("Bad float `$$Token'");
663 string const Lexer::getString(bool trim) const
665 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
668 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
674 docstring const Lexer::getDocString(bool trim) const
676 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
679 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
685 // I would prefer to give a tag number instead of an explicit token
686 // here, but it is not possible because Buffer::readDocument uses
687 // explicit tokens (JMarc)
688 docstring Lexer::getLongString(docstring const & endtoken)
692 bool firstline = true;
694 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
696 // blank line in the file being read
698 docstring tmpstr = getDocString();
699 docstring const token = trim(tmpstr, " \t");
701 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
703 // We do a case independent comparison, like searchKeyword does.
704 if (compare_no_case(token, endtoken) == 0)
708 size_t i = tmpstr.find_first_not_of(from_ascii(" \t"));
709 if (i != string::npos)
710 prefix = tmpstr.substr(0, i);
712 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
715 // further lines in long strings may have the same
716 // whitespace prefix as the first line. Remove it.
717 if (!prefix.empty() && prefixIs(tmpstr, prefix))
718 tmpstr.erase(0, prefix.length());
720 str += tmpstr + '\n';
724 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
730 bool Lexer::getBool() const
732 string const s = pimpl_->getString();
733 if (s == "false" || s == "0") {
737 if (s == "true" || s == "1") {
741 pimpl_->printError("Bad boolean `$$Token'. "
742 "Use \"false\" or \"true\"");
748 bool Lexer::eatLine()
750 return pimpl_->eatLine();
754 bool Lexer::next(bool esc)
756 return pimpl_->next(esc);
760 bool Lexer::nextToken()
762 return pimpl_->nextToken();
766 void Lexer::pushToken(string const & pt)
768 pimpl_->pushToken(pt);
772 Lexer::operator void const *() const
774 // This behaviour is NOT the same as the streams which would
775 // use fail() here. However, our implementation of getString() et al.
776 // can cause the eof() and fail() bits to be set, even though we
777 // haven't tried to read 'em.
778 return lastReadOk_? this : nullptr;
782 bool Lexer::operator!() const
788 Lexer & Lexer::operator>>(string & s)
800 Lexer & Lexer::operator>>(docstring & s)
812 Lexer & Lexer::operator>>(double & s)
824 Lexer & Lexer::operator>>(int & s)
836 Lexer & Lexer::operator>>(unsigned int & s)
848 Lexer & Lexer::operator>>(bool & s)
860 Lexer & Lexer::operator>>(char & c)
870 // quotes a string, e.g. for use in preferences files or as an argument
871 // of the "log" dialog
872 string Lexer::quoteString(string const & arg)
876 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
882 // same for docstring
883 docstring Lexer::quoteString(docstring const & arg)
887 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
888 from_ascii("\""), from_ascii("\\\""));
894 Lexer & Lexer::operator>>(char const * required)
898 if (token != required) {
899 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
900 << ". Got " << token << " instead. Line: " << lineNumber());
907 bool Lexer::checkFor(char const * required)
911 if (token == required)
918 void Lexer::setContext(std::string const & functionName)
920 pimpl_->context = functionName;