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"
28 #include <algorithm> // sort, lower_bound
36 using namespace lyx::support;
40 //////////////////////////////////////////////////////////////////////
44 //////////////////////////////////////////////////////////////////////
51 Pimpl(LexerKeyword * tab, int num);
53 string const getString() const;
55 docstring const getDocString() const;
57 void printError(string const & message) const;
59 void printTable(ostream & os);
61 void pushTable(LexerKeyword * tab, int num);
65 bool setFile(FileName const & filename);
67 void setStream(istream & i);
69 void setCommentChar(char c);
71 bool next(bool esc = false);
73 int searchKeyword(char const * const tag) const;
80 /// test if there is a pushed token or the stream is ok
81 bool inputAvailable();
83 void pushToken(string const &);
84 /// fb_ is only used to open files, the stream is accessed through is.
87 /// gz_ is only used to open files, the stream is accessed through is.
90 /// the stream that we use.
106 /// used for error messages
112 Pimpl(Pimpl const &);
113 void operator=(Pimpl const &);
122 : table_elem(nullptr), table_siz(0) {}
124 PushedTable(LexerKeyword * ki, int siz)
125 : table_elem(ki), table_siz(siz) {}
127 LexerKeyword * table_elem;
132 stack<PushedTable> pushed;
138 // used by lower_bound, sort and sorted
139 bool compareTags(LexerKeyword const & a, LexerKeyword const & b)
141 // we use the ascii version, because in turkish, 'i'
142 // is not the lowercase version of 'I', and thus
143 // turkish locale breaks parsing of tags.
144 return compare_ascii_no_case(a.tag, b.tag) < 0;
151 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
152 : is(&fb_), table(tab), no_items(num),
153 status(0), lineno(0), commentChar('#')
159 string const Lexer::Pimpl::getString() const
165 docstring const Lexer::Pimpl::getDocString() const
167 return from_utf8(buff);
171 void Lexer::Pimpl::printError(string const & message) const
173 string const tmpmsg = subst(message, "$$Token", getString());
174 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
175 << " of file " << to_utf8(makeDisplayPath(name))
176 << " current token: '" << getString() << "'"
177 << " context: '" << context << "']" << endl;
181 void Lexer::Pimpl::printTable(ostream & os)
183 os << "\nNumber of tags: " << no_items << endl;
184 for (int i= 0; i < no_items; ++i)
186 << "]: tag: `" << table[i].tag
187 << "' code:" << table[i].code << '\n';
192 void Lexer::Pimpl::verifyTable()
194 // Check if the table is sorted and if not, sort it.
196 && !lyx::sorted(table, table + no_items, &compareTags)) {
197 lyxerr << "The table passed to Lexer is not sorted!\n"
198 << "Tell the developers to fix it!" << endl;
199 // We sort it anyway to avoid problems.
200 lyxerr << "\nUnsorted:" << endl;
203 sort(table, table + no_items, &compareTags);
204 lyxerr << "\nSorted:" << endl;
210 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
212 PushedTable tmppu(table, no_items);
222 void Lexer::Pimpl::popTable()
224 if (pushed.empty()) {
225 lyxerr << "Lexer error: nothing to pop!" << endl;
229 PushedTable tmp = pushed.top();
231 table = tmp.table_elem;
232 no_items = tmp.table_siz;
236 bool Lexer::Pimpl::setFile(FileName const & filename)
238 // Check the format of the file.
239 if (theFormats().isZippedFile(filename)) {
240 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
241 // The check only outputs a debug message, because it triggers
242 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
243 // a fresh new filebuf. (JMarc)
244 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
245 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
246 "file or stream already set.");
247 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
249 name = filename.absFileName();
251 if (!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.toSafeFilesystemEncoding().c_str(), ios::in);
265 name = filename.absFileName();
267 if (!fb_.is_open() || !is.good())
271 // Skip byte order mark.
272 if (is.peek() == 0xef) {
274 if (is.peek() == 0xbb) {
276 LASSERT(is.get() == 0xbf, /**/);
285 void Lexer::Pimpl::setStream(istream & i)
287 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
288 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
289 "file or stream already set.");
296 void Lexer::Pimpl::setCommentChar(char c)
302 bool Lexer::Pimpl::next(bool esc /* = false */)
304 if (!pushTok.empty()) {
305 // There can have been a whole line pushed so
306 // we extract the first word and leaves the rest
308 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
310 pushTok = split(pushTok, buff, ' ');
322 while (is && !status) {
324 unsigned char c = cc;
326 if (c == commentChar) {
327 // Read rest of line (fast :-)
329 // That is not fast... (Lgb)
333 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
335 // unfortunately ignore is buggy (Lgb)
336 is.ignore(100, '\n');
348 bool escaped = false;
351 if (c == '\r') continue;
353 // escape the next char
356 if (c == '\"' || c == '\\')
359 buff.push_back('\\');
363 if (!escaped && c == '\"')
365 } while (c != '\n' && is);
374 } while (c != '\"' && c != '\n' && is);
379 printError("Missing quote");
384 buff.resize(buff.size() - 1);
390 continue; /* Skip ','s */
392 // using relational operators with chars other
393 // than == and != is not safe. And if it is done
394 // the type _have_ to be unsigned. It usually a
395 // lot better to use the functions from cctype
400 if (esc && c == '\\') {
401 // escape the next char
409 } while (c > ' ' && c != ',' && is);
413 if (c == '\r' && is) {
414 // The Windows support has lead to the
415 // possibility of "\r\n" at the end of
416 // a line. This will stop LyX choking
417 // when it expected to find a '\n'
429 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
435 int Lexer::Pimpl::searchKeyword(char const * const tag) const
437 LexerKeyword search_tag = { tag, 0 };
439 lower_bound(table, table + no_items,
440 search_tag, &compareTags);
441 // use the compare_ascii_no_case instead of compare_no_case,
442 // because in turkish, 'i' is not the lowercase version of 'I',
443 // and thus turkish locale breaks parsing of tags.
444 if (res != table + no_items
445 && !compare_ascii_no_case(res->tag, tag))
451 int Lexer::Pimpl::lex()
453 //NOTE: possible bug.
454 if (next() && status == LEX_TOKEN)
455 return searchKeyword(getString().c_str());
460 bool Lexer::Pimpl::eatLine()
464 unsigned char c = '\0';
466 while (is && c != '\n') {
469 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
476 buff.resize(buff.size() - 1);
479 } else if (buff.length() > 0) { // last line
488 bool Lexer::Pimpl::nextToken()
490 if (!pushTok.empty()) {
491 // There can have been a whole line pushed so
492 // we extract the first word and leaves the rest
494 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
496 pushTok = split(pushTok, buff, ' ');
506 while (is && !status) {
511 if ((c >= ' ' || c == '\t') && is) {
514 if (c == '\\') { // first char == '\\'
519 } while (c > ' ' && c != '\\' && is);
525 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
529 is.putback(c); // put it back
540 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
546 bool Lexer::Pimpl::inputAvailable()
552 void Lexer::Pimpl::pushToken(string const & pt)
560 //////////////////////////////////////////////////////////////////////
564 //////////////////////////////////////////////////////////////////////
567 : pimpl_(new Pimpl(nullptr, 0)), lastReadOk_(false)
571 void Lexer::init(LexerKeyword * tab, int num)
573 pimpl_ = new Pimpl(tab, num);
583 bool Lexer::isOK() const
585 return pimpl_->inputAvailable();
589 void Lexer::setLineNumber(int l)
595 int Lexer::lineNumber() const
597 return pimpl_->lineno;
601 istream & Lexer::getStream()
607 void Lexer::pushTable(LexerKeyword * tab, int num)
609 pimpl_->pushTable(tab, num);
613 void Lexer::popTable()
619 void Lexer::printTable(ostream & os)
621 pimpl_->printTable(os);
625 void Lexer::printError(string const & message) const
627 pimpl_->printError(message);
631 bool Lexer::setFile(FileName const & filename)
633 return pimpl_->setFile(filename);
637 void Lexer::setStream(istream & i)
639 pimpl_->setStream(i);
643 void Lexer::setCommentChar(char c)
645 pimpl_->setCommentChar(c);
651 return pimpl_->lex();
655 int Lexer::getInteger() const
657 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
659 pimpl_->printError("integer token missing");
663 if (isStrInt(pimpl_->getString()))
664 return convert<int>(pimpl_->getString());
667 pimpl_->printError("Bad integer `$$Token'");
672 double Lexer::getFloat() const
674 // replace comma with dot in case the file was written with
675 // the wrong locale (should be rare, but is easy enough to
677 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
679 pimpl_->printError("float token missing");
683 string const str = subst(pimpl_->getString(), ",", ".");
685 return convert<double>(str);
688 pimpl_->printError("Bad float `$$Token'");
693 string const Lexer::getString(bool trim) const
695 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
698 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
704 docstring const Lexer::getDocString(bool trim) const
706 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
709 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
715 // I would prefer to give a tag number instead of an explicit token
716 // here, but it is not possible because Buffer::readDocument uses
717 // explicit tokens (JMarc)
718 docstring Lexer::getLongString(docstring const & endtoken)
722 bool firstline = true;
724 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
726 // blank line in the file being read
728 docstring tmpstr = getDocString();
729 docstring const token = trim(tmpstr, " \t");
731 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
733 // We do a case independent comparison, like searchKeyword does.
734 if (compare_no_case(token, endtoken) == 0)
738 size_t i = tmpstr.find_first_not_of(from_ascii(" \t"));
739 if (i != string::npos)
740 prefix = tmpstr.substr(0, i);
742 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
745 // further lines in long strings may have the same
746 // whitespace prefix as the first line. Remove it.
747 if (!prefix.empty() && prefixIs(tmpstr, prefix))
748 tmpstr.erase(0, prefix.length());
750 str += tmpstr + '\n';
754 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
760 bool Lexer::getBool() const
762 string const s = pimpl_->getString();
763 if (s == "false" || s == "0") {
767 if (s == "true" || s == "1") {
771 pimpl_->printError("Bad boolean `$$Token'. "
772 "Use \"false\" or \"true\"");
778 bool Lexer::eatLine()
780 return pimpl_->eatLine();
784 bool Lexer::next(bool esc)
786 return pimpl_->next(esc);
790 bool Lexer::nextToken()
792 return pimpl_->nextToken();
796 void Lexer::pushToken(string const & pt)
798 pimpl_->pushToken(pt);
802 Lexer::operator void const *() const
804 // This behaviour is NOT the same as the streams which would
805 // use fail() here. However, our implementation of getString() et al.
806 // can cause the eof() and fail() bits to be set, even though we
807 // haven't tried to read 'em.
808 return lastReadOk_? this : nullptr;
812 bool Lexer::operator!() const
818 Lexer & Lexer::operator>>(string & s)
830 Lexer & Lexer::operator>>(docstring & s)
842 Lexer & Lexer::operator>>(double & s)
854 Lexer & Lexer::operator>>(int & s)
866 Lexer & Lexer::operator>>(unsigned int & s)
878 Lexer & Lexer::operator>>(bool & s)
890 Lexer & Lexer::operator>>(char & c)
900 // quotes a string, e.g. for use in preferences files or as an argument
901 // of the "log" dialog
902 string Lexer::quoteString(string const & arg)
906 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
912 // same for docstring
913 docstring Lexer::quoteString(docstring const & arg)
917 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
918 from_ascii("\""), from_ascii("\\\""));
924 Lexer & Lexer::operator>>(char const * required)
928 if (token != required) {
929 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
930 << ". Got " << token << " instead. Line: " << lineNumber());
937 bool Lexer::checkFor(char const * required)
941 if (token == required)
948 void Lexer::setContext(std::string const & functionName)
950 pimpl_->context = functionName;