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.
105 /// used for error messages
111 Pimpl(Pimpl const &);
112 void operator=(Pimpl const &);
121 : table_elem(nullptr), table_siz(0) {}
123 PushedTable(LexerKeyword * ki, int siz)
124 : table_elem(ki), table_siz(siz) {}
126 LexerKeyword * table_elem;
131 stack<PushedTable> pushed;
137 // used by lower_bound, sort and sorted
138 bool compareTags(LexerKeyword const & a, LexerKeyword const & b)
140 // we use the ascii version, because in turkish, 'i'
141 // is not the lowercase version of 'I', and thus
142 // turkish locale breaks parsing of tags.
143 return compare_ascii_no_case(a.tag, b.tag) < 0;
150 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
151 : is(&fb_), table(tab), no_items(num),
152 status(0), lineno(0), commentChar('#')
158 string const Lexer::Pimpl::getString() const
164 docstring const Lexer::Pimpl::getDocString() const
166 return from_utf8(buff);
170 void Lexer::Pimpl::printError(string const & message) const
172 string const tmpmsg = subst(message, "$$Token", getString());
173 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
174 << " of file " << to_utf8(makeDisplayPath(name))
175 << " current token: '" << getString() << "'"
176 << " context: '" << context << "']" << 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 if (theFormats().isZippedFile(filename)) {
239 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
240 // The check only outputs a debug message, because it triggers
241 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
242 // a fresh new filebuf. (JMarc)
243 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
244 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
245 "file or stream already set.");
246 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
248 name = filename.absFileName();
250 if (!gz_.is_open() || !is.good())
253 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
255 // The check only outputs a debug message, because it triggers
256 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
257 // a fresh new filebuf. (JMarc)
258 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
259 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
260 "file or stream already set.");
262 fb_.open(filename.toSafeFilesystemEncoding().c_str(), ios::in);
264 name = filename.absFileName();
266 if (!fb_.is_open() || !is.good())
270 // Skip byte order mark.
271 if (is.peek() == 0xef) {
273 if (is.peek() == 0xbb) {
275 LASSERT(is.get() == 0xbf, /**/);
284 void Lexer::Pimpl::setStream(istream & i)
286 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
287 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
288 "file or stream already set.");
295 void Lexer::Pimpl::setCommentChar(char c)
301 bool Lexer::Pimpl::next(bool esc /* = false */)
303 if (!pushTok.empty()) {
304 // There can have been a whole line pushed so
305 // we extract the first word and leaves the rest
307 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
309 pushTok = split(pushTok, buff, ' ');
321 while (is && !status) {
323 unsigned char c = cc;
325 if (c == commentChar) {
326 // Read rest of line (fast :-)
328 // That is not fast... (Lgb)
332 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
334 // unfortunately ignore is buggy (Lgb)
335 is.ignore(100, '\n');
347 bool escaped = false;
350 if (c == '\r') continue;
352 // escape the next char
355 if (c == '\"' || c == '\\')
358 buff.push_back('\\');
362 if (!escaped && c == '\"')
364 } while (c != '\n' && is);
373 } while (c != '\"' && c != '\n' && is);
378 printError("Missing quote");
383 buff.resize(buff.size() - 1);
389 continue; /* Skip ','s */
391 // using relational operators with chars other
392 // than == and != is not safe. And if it is done
393 // the type _have_ to be unsigned. It usually a
394 // lot better to use the functions from cctype
399 if (esc && c == '\\') {
400 // escape the next char
408 } while (c > ' ' && c != ',' && is);
412 if (c == '\r' && is) {
413 // The Windows support has lead to the
414 // possibility of "\r\n" at the end of
415 // a line. This will stop LyX choking
416 // when it expected to find a '\n'
428 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
434 int Lexer::Pimpl::searchKeyword(char const * const tag) const
436 LexerKeyword search_tag = { tag, 0 };
438 lower_bound(table, table + no_items,
439 search_tag, &compareTags);
440 // use the compare_ascii_no_case instead of compare_no_case,
441 // because in turkish, 'i' is not the lowercase version of 'I',
442 // and thus turkish locale breaks parsing of tags.
443 if (res != table + no_items
444 && !compare_ascii_no_case(res->tag, tag))
450 int Lexer::Pimpl::lex()
452 //NOTE: possible bug.
453 if (next() && status == LEX_TOKEN)
454 return searchKeyword(getString().c_str());
459 bool Lexer::Pimpl::eatLine()
463 unsigned char c = '\0';
465 while (is && c != '\n') {
468 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
475 buff.resize(buff.size() - 1);
478 } else if (buff.length() > 0) { // last line
487 bool Lexer::Pimpl::nextToken()
489 if (!pushTok.empty()) {
490 // There can have been a whole line pushed so
491 // we extract the first word and leaves the rest
493 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
495 pushTok = split(pushTok, buff, ' ');
505 while (is && !status) {
510 if ((c >= ' ' || c == '\t') && is) {
513 if (c == '\\') { // first char == '\\'
518 } while (c > ' ' && c != '\\' && is);
524 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
528 is.putback(c); // put it back
539 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
545 bool Lexer::Pimpl::inputAvailable()
551 void Lexer::Pimpl::pushToken(string const & pt)
559 //////////////////////////////////////////////////////////////////////
563 //////////////////////////////////////////////////////////////////////
566 : pimpl_(new Pimpl(nullptr, 0)), lastReadOk_(false)
570 void Lexer::init(LexerKeyword * tab, int num)
572 pimpl_ = new Pimpl(tab, num);
582 bool Lexer::isOK() const
584 return pimpl_->inputAvailable();
588 void Lexer::setLineNumber(int l)
594 int Lexer::lineNumber() const
596 return pimpl_->lineno;
600 istream & Lexer::getStream()
606 void Lexer::pushTable(LexerKeyword * tab, int num)
608 pimpl_->pushTable(tab, num);
612 void Lexer::popTable()
618 void Lexer::printTable(ostream & os)
620 pimpl_->printTable(os);
624 void Lexer::printError(string const & message) const
626 pimpl_->printError(message);
630 bool Lexer::setFile(FileName const & filename)
632 return pimpl_->setFile(filename);
636 void Lexer::setStream(istream & i)
638 pimpl_->setStream(i);
642 void Lexer::setCommentChar(char c)
644 pimpl_->setCommentChar(c);
650 return pimpl_->lex();
654 int Lexer::getInteger() const
656 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
658 pimpl_->printError("integer token missing");
662 if (isStrInt(pimpl_->getString()))
663 return convert<int>(pimpl_->getString());
666 pimpl_->printError("Bad integer `$$Token'");
671 double Lexer::getFloat() const
673 // replace comma with dot in case the file was written with
674 // the wrong locale (should be rare, but is easy enough to
676 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
678 pimpl_->printError("float token missing");
682 string const str = subst(pimpl_->getString(), ",", ".");
684 return convert<double>(str);
687 pimpl_->printError("Bad float `$$Token'");
692 string const Lexer::getString(bool trim) const
694 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
697 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
703 docstring const Lexer::getDocString(bool trim) const
705 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
708 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
714 // I would prefer to give a tag number instead of an explicit token
715 // here, but it is not possible because Buffer::readDocument uses
716 // explicit tokens (JMarc)
717 docstring Lexer::getLongString(docstring const & endtoken)
721 bool firstline = true;
723 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
725 // blank line in the file being read
727 docstring tmpstr = getDocString();
728 docstring const token = trim(tmpstr, " \t");
730 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
732 // We do a case independent comparison, like searchKeyword does.
733 if (compare_no_case(token, endtoken) == 0)
737 size_t i = tmpstr.find_first_not_of(from_ascii(" \t"));
738 if (i != string::npos)
739 prefix = tmpstr.substr(0, i);
741 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
744 // further lines in long strings may have the same
745 // whitespace prefix as the first line. Remove it.
746 if (!prefix.empty() && prefixIs(tmpstr, prefix))
747 tmpstr.erase(0, prefix.length());
749 str += tmpstr + '\n';
753 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
759 bool Lexer::getBool() const
761 string const s = pimpl_->getString();
762 if (s == "false" || s == "0") {
766 if (s == "true" || s == "1") {
770 pimpl_->printError("Bad boolean `$$Token'. "
771 "Use \"false\" or \"true\"");
777 bool Lexer::eatLine()
779 return pimpl_->eatLine();
783 bool Lexer::next(bool esc)
785 return pimpl_->next(esc);
789 bool Lexer::nextToken()
791 return pimpl_->nextToken();
795 void Lexer::pushToken(string const & pt)
797 pimpl_->pushToken(pt);
801 Lexer::operator void const *() const
803 // This behaviour is NOT the same as the streams which would
804 // use fail() here. However, our implementation of getString() et al.
805 // can cause the eof() and fail() bits to be set, even though we
806 // haven't tried to read 'em.
807 return lastReadOk_? this : nullptr;
811 bool Lexer::operator!() const
817 Lexer & Lexer::operator>>(string & s)
829 Lexer & Lexer::operator>>(docstring & s)
841 Lexer & Lexer::operator>>(double & s)
853 Lexer & Lexer::operator>>(int & s)
865 Lexer & Lexer::operator>>(unsigned int & s)
877 Lexer & Lexer::operator>>(bool & s)
889 Lexer & Lexer::operator>>(char & c)
899 // quotes a string, e.g. for use in preferences files or as an argument
900 // of the "log" dialog
901 string Lexer::quoteString(string const & arg)
905 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
911 // same for docstring
912 docstring Lexer::quoteString(docstring const & arg)
916 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
917 from_ascii("\""), from_ascii("\\\""));
923 Lexer & Lexer::operator>>(char const * required)
927 if (token != required) {
928 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
929 << ". Got " << token << " instead. Line: " << lineNumber());
936 bool Lexer::checkFor(char const * required)
940 if (token == required)
947 void Lexer::setContext(std::string const & str)
949 pimpl_->context = str;