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 search_kw(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.
107 Pimpl(Pimpl const &);
108 void operator=(Pimpl const &);
117 : table_elem(0), table_siz(0) {}
119 PushedTable(LexerKeyword * ki, int siz)
120 : table_elem(ki), table_siz(siz) {}
122 LexerKeyword * table_elem;
127 stack<PushedTable> pushed;
135 : public binary_function<LexerKeyword, LexerKeyword, bool> {
137 // used by lower_bound, sort and sorted
138 bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
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;
147 } // end of anon namespace
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)) << ']' << endl;
178 void Lexer::Pimpl::printTable(ostream & os)
180 os << "\nNumber of tags: " << no_items << endl;
181 for (int i= 0; i < no_items; ++i)
183 << "]: tag: `" << table[i].tag
184 << "' code:" << table[i].code << '\n';
189 void Lexer::Pimpl::verifyTable()
191 // Check if the table is sorted and if not, sort it.
193 && !lyx::sorted(table, table + no_items, CompareTags())) {
194 lyxerr << "The table passed to Lexer is not sorted!\n"
195 << "Tell the developers to fix it!" << endl;
196 // We sort it anyway to avoid problems.
197 lyxerr << "\nUnsorted:" << endl;
200 sort(table, table + no_items, CompareTags());
201 lyxerr << "\nSorted:" << endl;
207 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
209 PushedTable tmppu(table, no_items);
219 void Lexer::Pimpl::popTable()
221 if (pushed.empty()) {
222 lyxerr << "Lexer error: nothing to pop!" << endl;
226 PushedTable tmp = pushed.top();
228 table = tmp.table_elem;
229 no_items = tmp.table_siz;
233 bool Lexer::Pimpl::setFile(FileName const & filename)
235 // Check the format of the file.
236 string const format = filename.guessFormatFromContents();
238 if (format == "gzip" || format == "zip" || format == "compress") {
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 return gz_.is_open() && is.good();
252 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
254 // The check only outputs a debug message, because it triggers
255 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
256 // a fresh new filebuf. (JMarc)
257 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
258 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
259 "file or stream already set.");
261 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
263 name = filename.absFilename();
265 return fb_.is_open() && is.good();
270 void Lexer::Pimpl::setStream(istream & i)
272 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
273 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
274 "file or stream already set.");
281 void Lexer::Pimpl::setCommentChar(char c)
287 bool Lexer::Pimpl::next(bool esc /* = false */)
289 if (!pushTok.empty()) {
290 // There can have been a whole line pushed so
291 // we extract the first word and leaves the rest
293 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
295 pushTok = split(pushTok, buff, ' ');
305 unsigned char c = 0; // getc() returns an int
308 while (is && !status) {
317 if (c == commentChar) {
318 // Read rest of line (fast :-)
320 // That is not fast... (Lgb)
324 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
326 // unfortunately ignore is buggy (Lgb)
327 is.ignore(100, '\n');
338 bool escaped = false;
343 if (c == '\r') continue;
345 // escape the next char
348 if (c == '\"' || c == '\\')
351 buff.push_back('\\');
355 if (!escaped && c == '\"')
357 } while (c != '\n' && is);
366 } while (c != '\"' && c != '\n' && is);
371 printError("Missing quote");
376 buff.resize(buff.size() - 1);
381 if (!esc && c == ',')
382 continue; /* Skip ','s */
384 // using relational operators with chars other
385 // than == and != is not safe. And if it is done
386 // the type _have_ to be unsigned. It usually a
387 // lot better to use the functions from cctype
392 if (esc && c == '\\') {
393 // escape the next char
401 } while (c > ' ' && c != ',' && is);
405 if (!esc && c == '\r' && is) {
406 // The Windows support has lead to the
407 // possibility of "\r\n" at the end of
408 // a line. This will stop LyX choking
409 // when it expected to find a '\n'
421 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
427 int Lexer::Pimpl::search_kw(char const * const tag) const
429 LexerKeyword search_tag = { tag, 0 };
431 lower_bound(table, table + no_items,
432 search_tag, CompareTags());
433 // use the compare_ascii_no_case instead of compare_no_case,
434 // because in turkish, 'i' is not the lowercase version of 'I',
435 // and thus turkish locale breaks parsing of tags.
436 if (res != table + no_items
437 && !compare_ascii_no_case(res->tag, tag))
443 int Lexer::Pimpl::lex()
445 //NOTE: possible bug.
446 if (next() && status == LEX_TOKEN)
447 return search_kw(getString().c_str());
452 bool Lexer::Pimpl::eatLine()
456 unsigned char c = '\0';
458 while (is && c != '\n') {
461 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
468 buff.resize(buff.size() - 1);
471 } else if (buff.length() > 0) { // last line
480 bool Lexer::Pimpl::nextToken()
482 if (!pushTok.empty()) {
483 // There can have been a whole line pushed so
484 // we extract the first word and leaves the rest
486 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
488 pushTok = split(pushTok, buff, ' ');
498 while (is && !status) {
503 if (c >= ' ' && is) {
506 if (c == '\\') { // first char == '\\'
511 } while (c > ' ' && c != '\\' && is);
517 } while (c >= ' ' && c != '\\' && is);
521 is.putback(c); // put it back
532 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
538 bool Lexer::Pimpl::inputAvailable()
544 void Lexer::Pimpl::pushToken(string const & pt)
552 //////////////////////////////////////////////////////////////////////
556 //////////////////////////////////////////////////////////////////////
559 : pimpl_(new Pimpl(0, 0))
563 void Lexer::init(LexerKeyword * tab, int num)
565 pimpl_ = new Pimpl(tab, num);
575 bool Lexer::isOK() const
577 return pimpl_->inputAvailable();
581 void Lexer::setLineNumber(int l)
587 int Lexer::lineNumber() const
589 return pimpl_->lineno;
593 istream & Lexer::getStream()
599 void Lexer::pushTable(LexerKeyword * tab, int num)
601 pimpl_->pushTable(tab, num);
605 void Lexer::popTable()
611 void Lexer::printTable(ostream & os)
613 pimpl_->printTable(os);
617 void Lexer::printError(string const & message) const
619 pimpl_->printError(message);
623 bool Lexer::setFile(FileName const & filename)
625 return pimpl_->setFile(filename);
629 void Lexer::setStream(istream & i)
631 pimpl_->setStream(i);
635 void Lexer::setCommentChar(char c)
637 pimpl_->setCommentChar(c);
642 return pimpl_->lex();
646 int Lexer::getInteger() const
648 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
650 pimpl_->printError("integer token missing");
654 if (isStrInt(pimpl_->getString()))
655 return convert<int>(pimpl_->getString());
658 pimpl_->printError("Bad integer `$$Token'");
663 double Lexer::getFloat() const
665 // replace comma with dot in case the file was written with
666 // the wrong locale (should be rare, but is easy enough to
668 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
670 pimpl_->printError("float token missing");
674 string const str = subst(pimpl_->getString(), ",", ".");
676 return convert<double>(str);
679 pimpl_->printError("Bad float `$$Token'");
684 string const Lexer::getString() const
686 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
689 return pimpl_->getString();
695 docstring const Lexer::getDocString() const
697 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
700 return pimpl_->getDocString();
706 // I would prefer to give a tag number instead of an explicit token
707 // here, but it is not possible because Buffer::readDocument uses
708 // explicit tokens (JMarc)
709 string const Lexer::getLongString(string const & endtoken)
713 bool firstline = true;
715 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
717 // blank line in the file being read
720 string const token = trim(getString(), " \t");
722 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
724 // We do a case independent comparison, like search_kw does.
725 if (compare_ascii_no_case(token, endtoken) == 0)
728 string tmpstr = getString();
730 size_t i = tmpstr.find_first_not_of(' ');
731 if (i != string::npos)
732 prefix = tmpstr.substr(0, i);
734 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
737 // further lines in long strings may have the same
738 // whitespace prefix as the first line. Remove it.
739 if (prefix.length() && prefixIs(tmpstr, prefix))
740 tmpstr.erase(0, prefix.length() - 1);
742 str += ltrim(tmpstr, "\t") + '\n';
746 printError("Long string not ended by `" + endtoken + '\'');
752 bool Lexer::getBool() const
754 if (pimpl_->getString() == "true") {
757 } else if (pimpl_->getString() != "false") {
758 pimpl_->printError("Bad boolean `$$Token'. "
759 "Use \"false\" or \"true\"");
767 bool Lexer::eatLine()
769 return pimpl_->eatLine();
773 bool Lexer::next(bool esc)
775 return pimpl_->next(esc);
779 bool Lexer::nextToken()
781 return pimpl_->nextToken();
785 void Lexer::pushToken(string const & pt)
787 pimpl_->pushToken(pt);
791 Lexer::operator void const *() const
793 // This behaviour is NOT the same as the streams which would
794 // use fail() here. However, our implementation of getString() et al.
795 // can cause the eof() and fail() bits to be set, even though we
796 // haven't tried to read 'em.
797 return lastReadOk_? this : 0;
801 bool Lexer::operator!() const
807 Lexer & Lexer::operator>>(string & s)
819 Lexer & Lexer::operator>>(docstring & s)
831 Lexer & Lexer::operator>>(double & s)
843 Lexer & Lexer::operator>>(int & s)
855 Lexer & Lexer::operator>>(unsigned int & s)
867 Lexer & Lexer::operator>>(bool & s)
879 // quotes a string, e.g. for use in preferences files or as an argument
880 // of the "log" dialog
881 string const Lexer::quoteString(string const & arg)
885 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");