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/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>
39 using support::compare_ascii_no_case;
40 using support::FileName;
41 using support::isStrDbl;
42 using support::isStrInt;
44 using support::makeDisplayPath;
45 using support::prefixIs;
52 using std::lower_bound;
60 //////////////////////////////////////////////////////////////////////
64 //////////////////////////////////////////////////////////////////////
68 class Lexer::Pimpl : boost::noncopyable {
71 Pimpl(keyword_item * tab, int num);
73 std::string const getString() const;
75 docstring const getDocString() const;
77 void printError(std::string const & message) const;
79 void printTable(std::ostream & os);
81 void pushTable(keyword_item * tab, int num);
85 bool setFile(support::FileName const & filename);
87 void setStream(std::istream & i);
89 void setCommentChar(char c);
91 bool next(bool esc = false);
93 int search_kw(char const * const tag) const;
100 /// test if there is a pushed token or the stream is ok
101 bool inputAvailable();
103 void pushToken(std::string const &);
104 /// fb_ is only used to open files, the stream is accessed through is.
107 /// gz_ is only used to open files, the stream is accessed through is.
110 /// the stream that we use.
115 keyword_item * table;
136 : table_elem(0), table_siz(0) {}
138 pushed_table(keyword_item * ki, int siz)
139 : table_elem(ki), table_siz(siz) {}
141 keyword_item * table_elem;
146 std::stack<pushed_table> pushed;
154 : public std::binary_function<keyword_item, keyword_item, bool> {
156 // used by lower_bound, sort and sorted
157 bool operator()(keyword_item const & a, keyword_item const & b) const
159 // we use the ascii version, because in turkish, 'i'
160 // is not the lowercase version of 'I', and thus
161 // turkish locale breaks parsing of tags.
162 return compare_ascii_no_case(a.tag, b.tag) < 0;
166 } // end of anon namespace
169 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
170 : is(&fb_), table(tab), no_items(num),
171 status(0), lineno(0), commentChar('#')
177 string const Lexer::Pimpl::getString() const
183 docstring const Lexer::Pimpl::getDocString() const
185 return from_utf8(buff);
189 void Lexer::Pimpl::printError(string const & message) const
191 string const tmpmsg = subst(message, "$$Token", getString());
192 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
193 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
197 void Lexer::Pimpl::printTable(ostream & os)
199 os << "\nNumber of tags: " << no_items << endl;
200 for (int i= 0; i < no_items; ++i)
202 << "]: tag: `" << table[i].tag
203 << "' code:" << table[i].code << '\n';
208 void Lexer::Pimpl::verifyTable()
210 // Check if the table is sorted and if not, sort it.
212 && !lyx::sorted(table, table + no_items, compare_tags())) {
213 lyxerr << "The table passed to Lexer is not sorted!\n"
214 << "Tell the developers to fix it!" << endl;
215 // We sort it anyway to avoid problems.
216 lyxerr << "\nUnsorted:" << endl;
219 sort(table, table + no_items, compare_tags());
220 lyxerr << "\nSorted:" << endl;
226 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
228 pushed_table tmppu(table, no_items);
238 void Lexer::Pimpl::popTable()
240 if (pushed.empty()) {
241 lyxerr << "Lexer error: nothing to pop!" << endl;
245 pushed_table tmp = pushed.top();
247 table = tmp.table_elem;
248 no_items = tmp.table_siz;
252 bool Lexer::Pimpl::setFile(FileName const & filename)
254 // Check the format of the file.
255 string const format = filename.guessFormatFromContents();
257 if (format == "gzip" || format == "zip" || format == "compress") {
258 LYXERR(Debug::LYXLEX) << "lyxlex: compressed" << endl;
259 // The check only outputs a debug message, because it triggers
260 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
261 // a fresh new filebuf. (JMarc)
262 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
263 lyxerr[Debug::LYXLEX] << "Error in LyXLex::setFile: "
264 "file or stream already set." << endl;
265 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
267 name = filename.absFilename();
269 return gz_.is_open() && is.good();
271 LYXERR(Debug::LYXLEX) << "lyxlex: UNcompressed" << endl;
273 // The check only outputs a debug message, because it triggers
274 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
275 // a fresh new filebuf. (JMarc)
276 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
277 LYXERR(Debug::LYXLEX) << "Error in Lexer::setFile: "
278 "file or stream already set." << endl;
280 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
282 name = filename.absFilename();
284 return fb_.is_open() && is.good();
289 void Lexer::Pimpl::setStream(istream & i)
291 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
292 LYXERR(Debug::LYXLEX) << "Error in Lexer::setStream: "
293 "file or stream already set." << endl;
300 void Lexer::Pimpl::setCommentChar(char c)
306 bool Lexer::Pimpl::next(bool esc /* = false */)
308 if (!pushTok.empty()) {
309 // There can have been a whole line pushed so
310 // we extract the first word and leaves the rest
312 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
314 pushTok = split(pushTok, buff, ' ');
323 unsigned char c = 0; // getc() returns an int
326 while (is && !status) {
329 if (c == commentChar) {
330 // Read rest of line (fast :-)
332 // That is not fast... (Lgb)
336 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
337 << dummy << '\'' << endl;
339 // unfortunately ignore is buggy (Lgb)
340 is.ignore(100, '\n');
354 } while (c != '\"' && c != '\n' && is);
357 printError("Missing quote");
362 buff.resize(buff.size()-1);
368 continue; /* Skip ','s */
370 // using relational operators with chars other
371 // than == and != is not safe. And if it is done
372 // the type _have_ to be unsigned. It usually a
373 // lot better to use the functions from cctype
381 } while (c > ' ' && c != ',' && is);
386 if (c == '\r' && is) {
387 // The Windows support has lead to the
388 // possibility of "\r\n" at the end of
389 // a line. This will stop LyX choking
390 // when it expected to find a '\n'
402 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
406 unsigned char c = 0; // getc() returns an int
410 while (is && !status) {
418 if (c == commentChar) {
419 // Read rest of line (fast :-)
421 // That is still not fast... (Lgb)
425 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
426 << dummy << '\'' << endl;
428 // but ignore is also still buggy (Lgb)
429 // This is fast (Lgb)
430 is.ignore(100, '\n');
440 bool escaped = false;
445 if (c == '\r') continue;
447 // escape the next char
450 if (c == '\"' || c == '\\')
453 buff.push_back('\\');
457 if (!escaped && c == '\"')
459 } while (c != '\n' && is);
462 printError("Missing quote");
467 buff.resize(buff.size() -1);
477 // escape the next char
485 } while (c > ' ' && c != ',' && is);
497 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
504 int Lexer::Pimpl::search_kw(char const * const tag) const
506 keyword_item search_tag = { tag, 0 };
508 lower_bound(table, table + no_items,
509 search_tag, compare_tags());
510 // use the compare_ascii_no_case instead of compare_no_case,
511 // because in turkish, 'i' is not the lowercase version of 'I',
512 // and thus turkish locale breaks parsing of tags.
513 if (res != table + no_items
514 && !compare_ascii_no_case(res->tag, tag))
520 int Lexer::Pimpl::lex()
522 //NOTE: possible bug.
523 if (next() && status == LEX_TOKEN)
524 return search_kw(getString().c_str());
529 bool Lexer::Pimpl::eatLine()
533 unsigned char c = '\0';
535 while (is && c != '\n') {
538 //LYXERR(Debug::LYXLEX) << "Lexer::EatLine read char: `"
539 // << c << '\'' << endl;
546 buff.resize(buff.size() - 1);
549 } else if (buff.length() > 0) { // last line
558 bool Lexer::Pimpl::nextToken()
560 if (!pushTok.empty()) {
561 // There can have been a whole line pushed so
562 // we extract the first word and leaves the rest
564 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
566 pushTok = split(pushTok, buff, ' ');
576 while (is && !status) {
581 if (c >= ' ' && is) {
584 if (c == '\\') { // first char == '\\'
589 } while (c > ' ' && c != '\\' && is);
595 } while (c >= ' ' && c != '\\' && is);
598 if (c == '\\') is.putback(c); // put it back
609 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
615 bool Lexer::Pimpl::inputAvailable()
621 void Lexer::Pimpl::pushToken(string const & pt)
629 //////////////////////////////////////////////////////////////////////
633 //////////////////////////////////////////////////////////////////////
635 Lexer::Lexer(keyword_item * tab, int num)
636 : pimpl_(new Pimpl(tab, num))
646 bool Lexer::isOK() const
648 return pimpl_->inputAvailable();
652 void Lexer::setLineNo(int l)
658 int Lexer::getLineNo() const
660 return pimpl_->lineno;
664 istream & Lexer::getStream()
670 void Lexer::pushTable(keyword_item * tab, int num)
672 pimpl_->pushTable(tab, num);
676 void Lexer::popTable()
682 void Lexer::printTable(ostream & os)
684 pimpl_->printTable(os);
688 void Lexer::printError(string const & message) const
690 pimpl_->printError(message);
694 bool Lexer::setFile(support::FileName const & filename)
696 return pimpl_->setFile(filename);
700 void Lexer::setStream(istream & i)
702 pimpl_->setStream(i);
706 void Lexer::setCommentChar(char c)
708 pimpl_->setCommentChar(c);
713 return pimpl_->lex();
717 int Lexer::getInteger() const
719 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
721 pimpl_->printError("integer token missing");
725 if (isStrInt(pimpl_->getString()))
726 return convert<int>(pimpl_->getString());
729 pimpl_->printError("Bad integer `$$Token'");
734 double Lexer::getFloat() const
736 // replace comma with dot in case the file was written with
737 // the wrong locale (should be rare, but is easy enough to
739 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
741 pimpl_->printError("float token missing");
745 string const str = subst(pimpl_->getString(), ",", ".");
747 return convert<double>(str);
750 pimpl_->printError("Bad float `$$Token'");
755 string const Lexer::getString() const
757 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
760 return pimpl_->getString();
766 docstring const Lexer::getDocString() const
768 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
771 return pimpl_->getDocString();
777 // I would prefer to give a tag number instead of an explicit token
778 // here, but it is not possible because Buffer::readDocument uses
779 // explicit tokens (JMarc)
780 string const Lexer::getLongString(string const & endtoken)
783 bool firstline = true;
785 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
787 // blank line in the file being read
790 string const token = trim(getString(), " \t");
792 LYXERR(Debug::PARSER) << "LongString: `"
793 << getString() << '\'' << endl;
795 // We do a case independent comparison, like search_kw does.
796 if (compare_ascii_no_case(token, endtoken) == 0)
799 string tmpstr = getString();
801 string::size_type i(tmpstr.find_first_not_of(' '));
802 if (i != string::npos)
803 prefix = tmpstr.substr(0, i);
805 LYXERR(Debug::PARSER)
806 << "Prefix = `" << prefix << "\'" << endl;
809 // further lines in long strings may have the same
810 // whitespace prefix as the first line. Remove it.
811 if (prefix.length() && prefixIs(tmpstr, prefix)) {
812 tmpstr.erase(0, prefix.length() - 1);
815 str += ltrim(tmpstr, "\t") + '\n';
819 printError("Long string not ended by `" + endtoken + '\'');
826 bool Lexer::getBool() const
828 if (pimpl_->getString() == "true") {
831 } else if (pimpl_->getString() != "false") {
832 pimpl_->printError("Bad boolean `$$Token'. "
833 "Use \"false\" or \"true\"");
841 bool Lexer::eatLine()
843 return pimpl_->eatLine();
847 bool Lexer::next(bool esc)
849 return pimpl_->next(esc);
853 bool Lexer::nextToken()
855 return pimpl_->nextToken();
859 void Lexer::pushToken(string const & pt)
861 pimpl_->pushToken(pt);
865 Lexer::operator void const *() const
867 // This behaviour is NOT the same as the std::streams which would
868 // use fail() here. However, our implementation of getString() et al.
869 // can cause the eof() and fail() bits to be set, even though we
870 // haven't tried to read 'em.
871 return lastReadOk_? this : 0;
875 bool Lexer::operator!() const
881 Lexer & Lexer::operator>>(std::string & s)
893 Lexer & Lexer::operator>>(docstring & s)
905 Lexer & Lexer::operator>>(double & s)
917 Lexer & Lexer::operator>>(int & s)
929 Lexer & Lexer::operator>>(unsigned int & s)
941 Lexer & Lexer::operator>>(bool & s)
953 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
954 string const Lexer::quoteString(string const & arg)
956 std::ostringstream os;
957 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';