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"
27 #include <boost/noncopyable.hpp>
36 using namespace lyx::support;
40 //////////////////////////////////////////////////////////////////////
44 //////////////////////////////////////////////////////////////////////
48 class Lexer::Pimpl : boost::noncopyable {
51 Pimpl(keyword_item * 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(keyword_item * 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 search_kw(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.
116 : table_elem(0), table_siz(0) {}
118 PushedTable(keyword_item * ki, int siz)
119 : table_elem(ki), table_siz(siz) {}
121 keyword_item * table_elem;
126 stack<PushedTable> pushed;
134 : public binary_function<keyword_item, keyword_item, bool> {
136 // used by lower_bound, sort and sorted
137 bool operator()(keyword_item const & a, keyword_item const & b) const
139 // we use the ascii version, because in turkish, 'i'
140 // is not the lowercase version of 'I', and thus
141 // turkish locale breaks parsing of tags.
142 return compare_ascii_no_case(a.tag, b.tag) < 0;
146 } // end of anon namespace
149 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
150 : is(&fb_), table(tab), no_items(num),
151 status(0), lineno(0), commentChar('#')
157 string const Lexer::Pimpl::getString() const
163 docstring const Lexer::Pimpl::getDocString() const
165 return from_utf8(buff);
169 void Lexer::Pimpl::printError(string const & message) const
171 string const tmpmsg = subst(message, "$$Token", getString());
172 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
173 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << 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(keyword_item * 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 // Check the format of the file.
235 string const format = filename.guessFormatFromContents();
237 if (format == "gzip" || format == "zip" || format == "compress") {
238 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
239 // The check only outputs a debug message, because it triggers
240 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
241 // a fresh new filebuf. (JMarc)
242 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
243 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
244 "file or stream already set.");
245 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
247 name = filename.absFilename();
249 return gz_.is_open() && is.good();
251 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
253 // The check only outputs a debug message, because it triggers
254 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
255 // a fresh new filebuf. (JMarc)
256 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
257 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
258 "file or stream already set.");
260 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
262 name = filename.absFilename();
264 return fb_.is_open() && is.good();
269 void Lexer::Pimpl::setStream(istream & i)
271 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
272 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
273 "file or stream already set.");
280 void Lexer::Pimpl::setCommentChar(char c)
286 bool Lexer::Pimpl::next(bool esc /* = false */)
288 if (!pushTok.empty()) {
289 // There can have been a whole line pushed so
290 // we extract the first word and leaves the rest
292 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
294 pushTok = split(pushTok, buff, ' ');
303 unsigned char c = 0; // getc() returns an int
306 while (is && !status) {
309 if (c == commentChar) {
310 // Read rest of line (fast :-)
312 // That is not fast... (Lgb)
316 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
318 // unfortunately ignore is buggy (Lgb)
319 is.ignore(100, '\n');
333 } while (c != '\"' && c != '\n' && is);
336 printError("Missing quote");
341 buff.resize(buff.size()-1);
347 continue; /* Skip ','s */
349 // using relational operators with chars other
350 // than == and != is not safe. And if it is done
351 // the type _have_ to be unsigned. It usually a
352 // lot better to use the functions from cctype
360 } while (c > ' ' && c != ',' && is);
365 if (c == '\r' && is) {
366 // The Windows support has lead to the
367 // possibility of "\r\n" at the end of
368 // a line. This will stop LyX choking
369 // when it expected to find a '\n'
381 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
385 unsigned char c = 0; // getc() returns an int
389 while (is && !status) {
397 if (c == commentChar) {
398 // Read rest of line (fast :-)
400 // That is still not fast... (Lgb)
404 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
406 // but ignore is also still buggy (Lgb)
407 // This is fast (Lgb)
408 is.ignore(100, '\n');
418 bool escaped = false;
423 if (c == '\r') continue;
425 // escape the next char
428 if (c == '\"' || c == '\\')
431 buff.push_back('\\');
435 if (!escaped && c == '\"')
437 } while (c != '\n' && is);
440 printError("Missing quote");
445 buff.resize(buff.size() -1);
455 // escape the next char
463 } while (c > ' ' && c != ',' && is);
475 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
482 int Lexer::Pimpl::search_kw(char const * const tag) const
484 keyword_item search_tag = { tag, 0 };
486 lower_bound(table, table + no_items,
487 search_tag, CompareTags());
488 // use the compare_ascii_no_case instead of compare_no_case,
489 // because in turkish, 'i' is not the lowercase version of 'I',
490 // and thus turkish locale breaks parsing of tags.
491 if (res != table + no_items
492 && !compare_ascii_no_case(res->tag, tag))
498 int Lexer::Pimpl::lex()
500 //NOTE: possible bug.
501 if (next() && status == LEX_TOKEN)
502 return search_kw(getString().c_str());
507 bool Lexer::Pimpl::eatLine()
511 unsigned char c = '\0';
513 while (is && c != '\n') {
516 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
523 buff.resize(buff.size() - 1);
526 } else if (buff.length() > 0) { // last line
535 bool Lexer::Pimpl::nextToken()
537 if (!pushTok.empty()) {
538 // There can have been a whole line pushed so
539 // we extract the first word and leaves the rest
541 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
543 pushTok = split(pushTok, buff, ' ');
553 while (is && !status) {
558 if (c >= ' ' && is) {
561 if (c == '\\') { // first char == '\\'
566 } while (c > ' ' && c != '\\' && is);
572 } while (c >= ' ' && c != '\\' && is);
576 is.putback(c); // put it back
587 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
593 bool Lexer::Pimpl::inputAvailable()
599 void Lexer::Pimpl::pushToken(string const & pt)
607 //////////////////////////////////////////////////////////////////////
611 //////////////////////////////////////////////////////////////////////
613 Lexer::Lexer(keyword_item * tab, int num)
614 : pimpl_(new Pimpl(tab, num))
624 bool Lexer::isOK() const
626 return pimpl_->inputAvailable();
630 void Lexer::setLineNo(int l)
636 int Lexer::getLineNo() const
638 return pimpl_->lineno;
642 istream & Lexer::getStream()
648 void Lexer::pushTable(keyword_item * tab, int num)
650 pimpl_->pushTable(tab, num);
654 void Lexer::popTable()
660 void Lexer::printTable(ostream & os)
662 pimpl_->printTable(os);
666 void Lexer::printError(string const & message) const
668 pimpl_->printError(message);
672 bool Lexer::setFile(FileName const & filename)
674 return pimpl_->setFile(filename);
678 void Lexer::setStream(istream & i)
680 pimpl_->setStream(i);
684 void Lexer::setCommentChar(char c)
686 pimpl_->setCommentChar(c);
691 return pimpl_->lex();
695 int Lexer::getInteger() const
697 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
699 pimpl_->printError("integer token missing");
703 if (isStrInt(pimpl_->getString()))
704 return convert<int>(pimpl_->getString());
707 pimpl_->printError("Bad integer `$$Token'");
712 double Lexer::getFloat() const
714 // replace comma with dot in case the file was written with
715 // the wrong locale (should be rare, but is easy enough to
717 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
719 pimpl_->printError("float token missing");
723 string const str = subst(pimpl_->getString(), ",", ".");
725 return convert<double>(str);
728 pimpl_->printError("Bad float `$$Token'");
733 string const Lexer::getString() const
735 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
738 return pimpl_->getString();
744 docstring const Lexer::getDocString() const
746 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
749 return pimpl_->getDocString();
755 // I would prefer to give a tag number instead of an explicit token
756 // here, but it is not possible because Buffer::readDocument uses
757 // explicit tokens (JMarc)
758 string const Lexer::getLongString(string const & endtoken)
761 bool firstline = true;
763 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
765 // blank line in the file being read
768 string const token = trim(getString(), " \t");
770 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
772 // We do a case independent comparison, like search_kw does.
773 if (compare_ascii_no_case(token, endtoken) == 0)
776 string tmpstr = getString();
778 string::size_type i(tmpstr.find_first_not_of(' '));
779 if (i != string::npos)
780 prefix = tmpstr.substr(0, i);
782 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
785 // further lines in long strings may have the same
786 // whitespace prefix as the first line. Remove it.
787 if (prefix.length() && prefixIs(tmpstr, prefix)) {
788 tmpstr.erase(0, prefix.length() - 1);
791 str += ltrim(tmpstr, "\t") + '\n';
795 printError("Long string not ended by `" + endtoken + '\'');
802 bool Lexer::getBool() const
804 if (pimpl_->getString() == "true") {
807 } else if (pimpl_->getString() != "false") {
808 pimpl_->printError("Bad boolean `$$Token'. "
809 "Use \"false\" or \"true\"");
817 bool Lexer::eatLine()
819 return pimpl_->eatLine();
823 bool Lexer::next(bool esc)
825 return pimpl_->next(esc);
829 bool Lexer::nextToken()
831 return pimpl_->nextToken();
835 void Lexer::pushToken(string const & pt)
837 pimpl_->pushToken(pt);
841 Lexer::operator void const *() const
843 // This behaviour is NOT the same as the streams which would
844 // use fail() here. However, our implementation of getString() et al.
845 // can cause the eof() and fail() bits to be set, even though we
846 // haven't tried to read 'em.
847 return lastReadOk_? this : 0;
851 bool Lexer::operator!() const
857 Lexer & Lexer::operator>>(string & s)
869 Lexer & Lexer::operator>>(docstring & s)
881 Lexer & Lexer::operator>>(double & s)
893 Lexer & Lexer::operator>>(int & s)
905 Lexer & Lexer::operator>>(unsigned int & s)
917 Lexer & Lexer::operator>>(bool & s)
929 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
930 string const Lexer::quoteString(string const & arg)
933 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';