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/debug.h"
20 #include "support/convert.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"
26 #include "support/unicode.h"
28 #include <boost/noncopyable.hpp>
37 using namespace lyx::support;
41 //////////////////////////////////////////////////////////////////////
45 //////////////////////////////////////////////////////////////////////
49 class Lexer::Pimpl : boost::noncopyable {
52 Pimpl(keyword_item * tab, int num);
54 string const getString() const;
56 docstring const getDocString() const;
58 void printError(string const & message) const;
60 void printTable(ostream & os);
62 void pushTable(keyword_item * tab, int num);
66 bool setFile(FileName const & filename);
68 void setStream(istream & i);
70 void setCommentChar(char c);
72 bool next(bool esc = false);
74 int search_kw(char const * const tag) const;
81 /// test if there is a pushed token or the stream is ok
82 bool inputAvailable();
84 void pushToken(string const &);
85 /// fb_ is only used to open files, the stream is accessed through is.
88 /// gz_ is only used to open files, the stream is accessed through is.
91 /// the stream that we use.
117 : table_elem(0), table_siz(0) {}
119 pushed_table(keyword_item * ki, int siz)
120 : table_elem(ki), table_siz(siz) {}
122 keyword_item * table_elem;
127 stack<pushed_table> pushed;
135 : public binary_function<keyword_item, keyword_item, bool> {
137 // used by lower_bound, sort and sorted
138 bool operator()(keyword_item const & a, keyword_item 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(keyword_item * 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, compare_tags())) {
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, compare_tags());
201 lyxerr << "\nSorted:" << endl;
207 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
209 pushed_table tmppu(table, no_items);
219 void Lexer::Pimpl::popTable()
221 if (pushed.empty()) {
222 lyxerr << "Lexer error: nothing to pop!" << endl;
226 pushed_table 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, ' ');
304 unsigned char c = 0; // getc() returns an int
307 while (is && !status) {
310 if (c == commentChar) {
311 // Read rest of line (fast :-)
313 // That is not fast... (Lgb)
317 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
319 // unfortunately ignore is buggy (Lgb)
320 is.ignore(100, '\n');
334 } while (c != '\"' && c != '\n' && is);
337 printError("Missing quote");
342 buff.resize(buff.size()-1);
348 continue; /* Skip ','s */
350 // using relational operators with chars other
351 // than == and != is not safe. And if it is done
352 // the type _have_ to be unsigned. It usually a
353 // lot better to use the functions from cctype
361 } while (c > ' ' && c != ',' && is);
366 if (c == '\r' && is) {
367 // The Windows support has lead to the
368 // possibility of "\r\n" at the end of
369 // a line. This will stop LyX choking
370 // when it expected to find a '\n'
382 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
386 unsigned char c = 0; // getc() returns an int
390 while (is && !status) {
398 if (c == commentChar) {
399 // Read rest of line (fast :-)
401 // That is still not fast... (Lgb)
405 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
407 // but ignore is also still buggy (Lgb)
408 // This is fast (Lgb)
409 is.ignore(100, '\n');
419 bool escaped = false;
424 if (c == '\r') continue;
426 // escape the next char
429 if (c == '\"' || c == '\\')
432 buff.push_back('\\');
436 if (!escaped && c == '\"')
438 } while (c != '\n' && is);
441 printError("Missing quote");
446 buff.resize(buff.size() -1);
456 // escape the next char
464 } while (c > ' ' && c != ',' && is);
476 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
483 int Lexer::Pimpl::search_kw(char const * const tag) const
485 keyword_item search_tag = { tag, 0 };
487 lower_bound(table, table + no_items,
488 search_tag, compare_tags());
489 // use the compare_ascii_no_case instead of compare_no_case,
490 // because in turkish, 'i' is not the lowercase version of 'I',
491 // and thus turkish locale breaks parsing of tags.
492 if (res != table + no_items
493 && !compare_ascii_no_case(res->tag, tag))
499 int Lexer::Pimpl::lex()
501 //NOTE: possible bug.
502 if (next() && status == LEX_TOKEN)
503 return search_kw(getString().c_str());
508 bool Lexer::Pimpl::eatLine()
512 unsigned char c = '\0';
514 while (is && c != '\n') {
517 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
524 buff.resize(buff.size() - 1);
527 } else if (buff.length() > 0) { // last line
536 bool Lexer::Pimpl::nextToken()
538 if (!pushTok.empty()) {
539 // There can have been a whole line pushed so
540 // we extract the first word and leaves the rest
542 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
544 pushTok = split(pushTok, buff, ' ');
554 while (is && !status) {
559 if (c >= ' ' && is) {
562 if (c == '\\') { // first char == '\\'
567 } while (c > ' ' && c != '\\' && is);
573 } while (c >= ' ' && c != '\\' && is);
576 if (c == '\\') 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, "\\", "\\\\"), "\"", "\\\"") << '"';