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.
20 #include "support/convert.h"
21 #include "support/filetools.h"
22 #include "support/lstrings.h"
23 #include "support/lyxalgo.h"
24 #include "support/types.h"
25 #include "support/unicode.h"
27 #include <boost/iostreams/filtering_streambuf.hpp>
28 #include <boost/iostreams/filter/gzip.hpp>
29 #include <boost/iostreams/device/file.hpp>
30 #include <boost/utility.hpp>
32 namespace io = boost::iostreams;
43 using support::compare_ascii_no_case;
44 using support::FileName;
45 using support::getFormatFromContents;
46 using support::isStrDbl;
47 using support::isStrInt;
49 using support::makeDisplayPath;
50 using support::prefixIs;
57 using std::lower_bound;
65 //////////////////////////////////////////////////////////////////////
69 //////////////////////////////////////////////////////////////////////
73 class Lexer::Pimpl : boost::noncopyable {
76 Pimpl(keyword_item * tab, int num);
78 std::string const getString() const;
80 docstring const getDocString() const;
82 void printError(std::string const & message) const;
84 void printTable(std::ostream & os);
86 void pushTable(keyword_item * tab, int num);
90 bool setFile(support::FileName const & filename);
92 void setStream(std::istream & i);
94 void setCommentChar(char c);
96 bool next(bool esc = false);
98 int search_kw(char const * const tag) const;
105 /// test if there is a pushed token or the stream is ok
106 bool inputAvailable();
108 void pushToken(std::string const &);
109 /// fb_ is only used to open files, the stream is accessed through is.
112 /// gz_ is only used to open files, the stream is accessed through is.
113 io::filtering_istreambuf gz_;
115 /// the stream that we use.
120 keyword_item * table;
141 : table_elem(0), table_siz(0) {}
143 pushed_table(keyword_item * ki, int siz)
144 : table_elem(ki), table_siz(siz) {}
146 keyword_item * table_elem;
151 std::stack<pushed_table> pushed;
159 : public std::binary_function<keyword_item, keyword_item, bool> {
161 // used by lower_bound, sort and sorted
162 bool operator()(keyword_item const & a, keyword_item const & b) const
164 // we use the ascii version, because in turkish, 'i'
165 // is not the lowercase version of 'I', and thus
166 // turkish locale breaks parsing of tags.
167 return compare_ascii_no_case(a.tag, b.tag) < 0;
171 } // end of anon namespace
174 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
175 : is(&fb_), table(tab), no_items(num),
176 status(0), lineno(0), commentChar('#')
182 string const Lexer::Pimpl::getString() const
188 docstring const Lexer::Pimpl::getDocString() const
190 return from_utf8(buff);
194 void Lexer::Pimpl::printError(string const & message) const
196 string const tmpmsg = subst(message, "$$Token", getString());
197 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
198 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
202 void Lexer::Pimpl::printTable(ostream & os)
204 os << "\nNumber of tags: " << no_items << endl;
205 for (int i= 0; i < no_items; ++i)
207 << "]: tag: `" << table[i].tag
208 << "' code:" << table[i].code << '\n';
213 void Lexer::Pimpl::verifyTable()
215 // Check if the table is sorted and if not, sort it.
217 && !lyx::sorted(table, table + no_items, compare_tags())) {
218 lyxerr << "The table passed to Lexer is not sorted!\n"
219 << "Tell the developers to fix it!" << endl;
220 // We sort it anyway to avoid problems.
221 lyxerr << "\nUnsorted:" << endl;
224 sort(table, table + no_items, compare_tags());
225 lyxerr << "\nSorted:" << endl;
231 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
233 pushed_table tmppu(table, no_items);
243 void Lexer::Pimpl::popTable()
245 if (pushed.empty()) {
246 lyxerr << "Lexer error: nothing to pop!" << endl;
250 pushed_table tmp = pushed.top();
252 table = tmp.table_elem;
253 no_items = tmp.table_siz;
257 bool Lexer::Pimpl::setFile(FileName const & filename)
259 // Check the format of the file.
260 string const format = getFormatFromContents(filename);
262 if (format == "gzip" || format == "zip" || format == "compress") {
263 LYXERR(Debug::LYXLEX) << "lyxlex: compressed" << endl;
265 // The check only outputs a debug message, because it triggers
266 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
267 // a fresh new filebuf. (JMarc)
268 if (!gz_.empty() || istream::off_type(is.tellg()) > -1)
269 LYXERR(Debug::LYXLEX) << "Error in Lexer::setFile: "
270 "file or stream already set." << endl;
271 gz_.push(io::gzip_decompressor());
272 gz_.push(io::file_source(filename.toFilesystemEncoding()));
274 name = filename.absFilename();
276 return gz_.component<io::file_source>(1)->is_open() && is.good();
278 LYXERR(Debug::LYXLEX) << "lyxlex: UNcompressed" << endl;
280 // The check only outputs a debug message, because it triggers
281 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
282 // a fresh new filebuf. (JMarc)
283 if (fb_.is_open() || istream::off_type(is.tellg()) > 0)
284 LYXERR(Debug::LYXLEX) << "Error in Lexer::setFile: "
285 "file or stream already set." << endl;
286 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
288 name = filename.absFilename();
290 return fb_.is_open() && is.good();
295 void Lexer::Pimpl::setStream(istream & i)
297 if (fb_.is_open() || istream::off_type(is.tellg()) > 0)
298 LYXERR(Debug::LYXLEX) << "Error in Lexer::setStream: "
299 "file or stream already set." << endl;
305 void Lexer::Pimpl::setCommentChar(char c)
311 bool Lexer::Pimpl::next(bool esc /* = false */)
313 if (!pushTok.empty()) {
314 // There can have been a whole line pushed so
315 // we extract the first word and leaves the rest
317 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
319 pushTok = split(pushTok, buff, ' ');
328 unsigned char c = 0; // getc() returns an int
331 while (is && !status) {
334 if (c == commentChar) {
335 // Read rest of line (fast :-)
337 // That is not fast... (Lgb)
341 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
342 << dummy << '\'' << endl;
344 // unfortunately ignore is buggy (Lgb)
345 is.ignore(100, '\n');
359 } while (c != '\"' && c != '\n' && is);
362 printError("Missing quote");
367 buff.resize(buff.size()-1);
373 continue; /* Skip ','s */
375 // using relational operators with chars other
376 // than == and != is not safe. And if it is done
377 // the type _have_ to be unsigned. It usually a
378 // lot better to use the functions from cctype
386 } while (c > ' ' && c != ',' && is);
391 if (c == '\r' && is) {
392 // The Windows support has lead to the
393 // possibility of "\r\n" at the end of
394 // a line. This will stop LyX choking
395 // when it expected to find a '\n'
407 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
411 unsigned char c = 0; // getc() returns an int
415 while (is && !status) {
423 if (c == commentChar) {
424 // Read rest of line (fast :-)
426 // That is still not fast... (Lgb)
430 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
431 << dummy << '\'' << endl;
433 // but ignore is also still buggy (Lgb)
434 // This is fast (Lgb)
435 is.ignore(100, '\n');
445 bool escaped = false;
450 if (c == '\r') continue;
452 // escape the next char
455 if (c == '\"' || c == '\\')
458 buff.push_back('\\');
462 if (!escaped && c == '\"')
464 } while (c != '\n' && is);
467 printError("Missing quote");
472 buff.resize(buff.size() -1);
482 // escape the next char
490 } while (c > ' ' && c != ',' && is);
502 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
509 int Lexer::Pimpl::search_kw(char const * const tag) const
511 keyword_item search_tag = { tag, 0 };
513 lower_bound(table, table + no_items,
514 search_tag, compare_tags());
515 // use the compare_ascii_no_case instead of compare_no_case,
516 // because in turkish, 'i' is not the lowercase version of 'I',
517 // and thus turkish locale breaks parsing of tags.
518 if (res != table + no_items
519 && !compare_ascii_no_case(res->tag, tag))
525 int Lexer::Pimpl::lex()
527 //NOTE: possible bug.
528 if (next() && status == LEX_TOKEN)
529 return search_kw(getString().c_str());
534 bool Lexer::Pimpl::eatLine()
538 unsigned char c = '\0';
540 while (is && c != '\n') {
543 //LYXERR(Debug::LYXLEX) << "Lexer::EatLine read char: `"
544 // << c << '\'' << endl;
551 buff.resize(buff.size() - 1);
554 } else if (buff.length() > 0) { // last line
563 bool Lexer::Pimpl::nextToken()
565 if (!pushTok.empty()) {
566 // There can have been a whole line pushed so
567 // we extract the first word and leaves the rest
569 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
571 pushTok = split(pushTok, buff, ' ');
581 while (is && !status) {
586 if (c >= ' ' && is) {
589 if (c == '\\') { // first char == '\\'
594 } while (c > ' ' && c != '\\' && is);
600 } while (c >= ' ' && c != '\\' && is);
603 if (c == '\\') is.putback(c); // put it back
614 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
620 bool Lexer::Pimpl::inputAvailable()
626 void Lexer::Pimpl::pushToken(string const & pt)
634 //////////////////////////////////////////////////////////////////////
638 //////////////////////////////////////////////////////////////////////
640 Lexer::Lexer(keyword_item * tab, int num)
641 : pimpl_(new Pimpl(tab, num))
651 bool Lexer::isOK() const
653 return pimpl_->inputAvailable();
657 void Lexer::setLineNo(int l)
663 int Lexer::getLineNo() const
665 return pimpl_->lineno;
669 istream & Lexer::getStream()
675 void Lexer::pushTable(keyword_item * tab, int num)
677 pimpl_->pushTable(tab, num);
681 void Lexer::popTable()
687 void Lexer::printTable(ostream & os)
689 pimpl_->printTable(os);
693 void Lexer::printError(string const & message) const
695 pimpl_->printError(message);
699 bool Lexer::setFile(support::FileName const & filename)
701 return pimpl_->setFile(filename);
705 void Lexer::setStream(istream & i)
707 pimpl_->setStream(i);
711 void Lexer::setCommentChar(char c)
713 pimpl_->setCommentChar(c);
718 return pimpl_->lex();
722 int Lexer::getInteger() const
724 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
726 pimpl_->printError("integer token missing");
730 if (isStrInt(pimpl_->getString()))
731 return convert<int>(pimpl_->getString());
734 pimpl_->printError("Bad integer `$$Token'");
739 double Lexer::getFloat() const
741 // replace comma with dot in case the file was written with
742 // the wrong locale (should be rare, but is easy enough to
744 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
746 pimpl_->printError("float token missing");
750 string const str = subst(pimpl_->getString(), ",", ".");
752 return convert<double>(str);
755 pimpl_->printError("Bad float `$$Token'");
760 string const Lexer::getString() const
762 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
765 return pimpl_->getString();
771 docstring const Lexer::getDocString() const
773 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
776 return pimpl_->getDocString();
782 // I would prefer to give a tag number instead of an explicit token
783 // here, but it is not possible because Buffer::readDocument uses
784 // explicit tokens (JMarc)
785 string const Lexer::getLongString(string const & endtoken)
788 bool firstline = true;
790 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
792 // blank line in the file being read
795 string const token = trim(getString(), " \t");
797 LYXERR(Debug::PARSER) << "LongString: `"
798 << getString() << '\'' << endl;
800 // We do a case independent comparison, like search_kw does.
801 if (compare_ascii_no_case(token, endtoken) == 0)
804 string tmpstr = getString();
806 string::size_type i(tmpstr.find_first_not_of(' '));
807 if (i != string::npos)
808 prefix = tmpstr.substr(0, i);
810 LYXERR(Debug::PARSER)
811 << "Prefix = `" << prefix << "\'" << endl;
814 // further lines in long strings may have the same
815 // whitespace prefix as the first line. Remove it.
816 if (prefix.length() && prefixIs(tmpstr, prefix)) {
817 tmpstr.erase(0, prefix.length() - 1);
820 str += ltrim(tmpstr, "\t") + '\n';
824 printError("Long string not ended by `" + endtoken + '\'');
831 bool Lexer::getBool() const
833 if (pimpl_->getString() == "true") {
836 } else if (pimpl_->getString() != "false") {
837 pimpl_->printError("Bad boolean `$$Token'. "
838 "Use \"false\" or \"true\"");
846 bool Lexer::eatLine()
848 return pimpl_->eatLine();
852 bool Lexer::next(bool esc)
854 return pimpl_->next(esc);
858 bool Lexer::nextToken()
860 return pimpl_->nextToken();
864 void Lexer::pushToken(string const & pt)
866 pimpl_->pushToken(pt);
870 Lexer::operator void const *() const
872 // This behaviour is NOT the same as the std::streams which would
873 // use fail() here. However, our implementation of getString() et al.
874 // can cause the eof() and fail() bits to be set, even though we
875 // haven't tried to read 'em.
876 return lastReadOk_? this : 0;
880 bool Lexer::operator!() const
886 Lexer & Lexer::operator>>(std::string & s)
898 Lexer & Lexer::operator>>(docstring & s)
910 Lexer & Lexer::operator>>(double & s)
922 Lexer & Lexer::operator>>(int & s)
934 Lexer & Lexer::operator>>(unsigned int & s)
946 Lexer & Lexer::operator>>(bool & s)
958 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
959 string const Lexer::quoteString(string const & arg)
961 std::ostringstream os;
962 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';