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) {
319 if (c == commentChar) {
320 // Read rest of line (fast :-)
322 // That is not fast... (Lgb)
326 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
328 // unfortunately ignore is buggy (Lgb)
329 is.ignore(100, '\n');
340 bool escaped = false;
345 if (c == '\r') continue;
347 // escape the next char
350 if (c == '\"' || c == '\\')
353 buff.push_back('\\');
357 if (!escaped && c == '\"')
359 } while (c != '\n' && is);
368 } while (c != '\"' && c != '\n' && is);
373 printError("Missing quote");
378 buff.resize(buff.size() - 1);
383 if (!esc && c == ',')
384 continue; /* Skip ','s */
386 // using relational operators with chars other
387 // than == and != is not safe. And if it is done
388 // the type _have_ to be unsigned. It usually a
389 // lot better to use the functions from cctype
394 if (esc && c == '\\') {
395 // escape the next char
403 } while (c > ' ' && c != ',' && is);
407 if (!esc && c == '\r' && is) {
408 // The Windows support has lead to the
409 // possibility of "\r\n" at the end of
410 // a line. This will stop LyX choking
411 // when it expected to find a '\n'
423 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
429 int Lexer::Pimpl::searchKeyword(char const * const tag) const
431 LexerKeyword search_tag = { tag, 0 };
433 lower_bound(table, table + no_items,
434 search_tag, CompareTags());
435 // use the compare_ascii_no_case instead of compare_no_case,
436 // because in turkish, 'i' is not the lowercase version of 'I',
437 // and thus turkish locale breaks parsing of tags.
438 if (res != table + no_items
439 && !compare_ascii_no_case(res->tag, tag))
445 int Lexer::Pimpl::lex()
447 //NOTE: possible bug.
448 if (next() && status == LEX_TOKEN)
449 return searchKeyword(getString().c_str());
454 bool Lexer::Pimpl::eatLine()
458 unsigned char c = '\0';
460 while (is && c != '\n') {
463 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
470 buff.resize(buff.size() - 1);
473 } else if (buff.length() > 0) { // last line
482 bool Lexer::Pimpl::nextToken()
484 if (!pushTok.empty()) {
485 // There can have been a whole line pushed so
486 // we extract the first word and leaves the rest
488 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
490 pushTok = split(pushTok, buff, ' ');
500 while (is && !status) {
505 if (c >= ' ' && is) {
508 if (c == '\\') { // first char == '\\'
513 } while (c > ' ' && c != '\\' && is);
519 } while (c >= ' ' && c != '\\' && is);
523 is.putback(c); // put it back
534 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
540 bool Lexer::Pimpl::inputAvailable()
546 void Lexer::Pimpl::pushToken(string const & pt)
554 //////////////////////////////////////////////////////////////////////
558 //////////////////////////////////////////////////////////////////////
561 : pimpl_(new Pimpl(0, 0))
565 void Lexer::init(LexerKeyword * tab, int num)
567 pimpl_ = new Pimpl(tab, num);
577 bool Lexer::isOK() const
579 return pimpl_->inputAvailable();
583 void Lexer::setLineNumber(int l)
589 int Lexer::lineNumber() const
591 return pimpl_->lineno;
595 istream & Lexer::getStream()
601 void Lexer::pushTable(LexerKeyword * tab, int num)
603 pimpl_->pushTable(tab, num);
607 void Lexer::popTable()
613 void Lexer::printTable(ostream & os)
615 pimpl_->printTable(os);
619 void Lexer::printError(string const & message) const
621 pimpl_->printError(message);
625 bool Lexer::setFile(FileName const & filename)
627 return pimpl_->setFile(filename);
631 void Lexer::setStream(istream & i)
633 pimpl_->setStream(i);
637 void Lexer::setCommentChar(char c)
639 pimpl_->setCommentChar(c);
644 return pimpl_->lex();
648 int Lexer::getInteger() const
650 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
652 pimpl_->printError("integer token missing");
656 if (isStrInt(pimpl_->getString()))
657 return convert<int>(pimpl_->getString());
660 pimpl_->printError("Bad integer `$$Token'");
665 double Lexer::getFloat() const
667 // replace comma with dot in case the file was written with
668 // the wrong locale (should be rare, but is easy enough to
670 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
672 pimpl_->printError("float token missing");
676 string const str = subst(pimpl_->getString(), ",", ".");
678 return convert<double>(str);
681 pimpl_->printError("Bad float `$$Token'");
686 string const Lexer::getString() const
688 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
691 return pimpl_->getString();
697 docstring const Lexer::getDocString() const
699 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
702 return pimpl_->getDocString();
708 // I would prefer to give a tag number instead of an explicit token
709 // here, but it is not possible because Buffer::readDocument uses
710 // explicit tokens (JMarc)
711 string const Lexer::getLongString(string const & endtoken)
715 bool firstline = true;
717 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
719 // blank line in the file being read
722 string const token = trim(getString(), " \t");
724 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
726 // We do a case independent comparison, like searchKeyword does.
727 if (compare_ascii_no_case(token, endtoken) == 0)
730 string tmpstr = getString();
732 size_t i = tmpstr.find_first_not_of(' ');
733 if (i != string::npos)
734 prefix = tmpstr.substr(0, i);
736 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
739 // further lines in long strings may have the same
740 // whitespace prefix as the first line. Remove it.
741 if (prefix.length() && prefixIs(tmpstr, prefix))
742 tmpstr.erase(0, prefix.length() - 1);
744 str += ltrim(tmpstr, "\t") + '\n';
748 printError("Long string not ended by `" + endtoken + '\'');
754 bool Lexer::getBool() const
756 if (pimpl_->getString() == "true") {
759 } else if (pimpl_->getString() != "false") {
760 pimpl_->printError("Bad boolean `$$Token'. "
761 "Use \"false\" or \"true\"");
769 bool Lexer::eatLine()
771 return pimpl_->eatLine();
775 bool Lexer::next(bool esc)
777 return pimpl_->next(esc);
781 bool Lexer::nextToken()
783 return pimpl_->nextToken();
787 void Lexer::pushToken(string const & pt)
789 pimpl_->pushToken(pt);
793 Lexer::operator void const *() const
795 // This behaviour is NOT the same as the streams which would
796 // use fail() here. However, our implementation of getString() et al.
797 // can cause the eof() and fail() bits to be set, even though we
798 // haven't tried to read 'em.
799 return lastReadOk_? this : 0;
803 bool Lexer::operator!() const
809 Lexer & Lexer::operator>>(string & s)
821 Lexer & Lexer::operator>>(docstring & s)
833 Lexer & Lexer::operator>>(double & s)
845 Lexer & Lexer::operator>>(int & s)
857 Lexer & Lexer::operator>>(unsigned int & s)
869 Lexer & Lexer::operator>>(bool & s)
881 // quotes a string, e.g. for use in preferences files or as an argument
882 // of the "log" dialog
883 string Lexer::quoteString(string const & arg)
887 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
893 Lexer & Lexer::operator>>(char const * required)
897 if (token != required) {
898 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context);
905 void Lexer::setContext(std::string const & str)
907 pimpl_->context = str;