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/utility.hpp>
39 using support::compare_ascii_no_case;
40 using support::FileName;
41 using support::getFormatFromContents;
42 using support::isStrDbl;
43 using support::isStrInt;
45 using support::makeDisplayPath;
46 using support::prefixIs;
53 using std::lower_bound;
61 //////////////////////////////////////////////////////////////////////
65 //////////////////////////////////////////////////////////////////////
69 class Lexer::Pimpl : boost::noncopyable {
72 Pimpl(keyword_item * tab, int num);
74 std::string const getString() const;
76 docstring const getDocString() const;
78 void printError(std::string const & message) const;
80 void printTable(std::ostream & os);
82 void pushTable(keyword_item * tab, int num);
86 bool setFile(support::FileName const & filename);
88 void setStream(std::istream & i);
90 void setCommentChar(char c);
92 bool next(bool esc = false);
94 int search_kw(char const * const tag) const;
101 /// test if there is a pushed token or the stream is ok
102 bool inputAvailable();
104 void pushToken(std::string const &);
105 /// fb_ is only used to open files, the stream is accessed through is.
108 /// gz_ is only used to open files, the stream is accessed through is.
111 /// the stream that we use.
116 keyword_item * table;
137 : table_elem(0), table_siz(0) {}
139 pushed_table(keyword_item * ki, int siz)
140 : table_elem(ki), table_siz(siz) {}
142 keyword_item * table_elem;
147 std::stack<pushed_table> pushed;
155 : public std::binary_function<keyword_item, keyword_item, bool> {
157 // used by lower_bound, sort and sorted
158 bool operator()(keyword_item const & a, keyword_item const & b) const
160 // we use the ascii version, because in turkish, 'i'
161 // is not the lowercase version of 'I', and thus
162 // turkish locale breaks parsing of tags.
163 return compare_ascii_no_case(a.tag, b.tag) < 0;
167 } // end of anon namespace
170 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
171 : is(&fb_), table(tab), no_items(num),
172 status(0), lineno(0), commentChar('#')
178 string const Lexer::Pimpl::getString() const
184 docstring const Lexer::Pimpl::getDocString() const
186 return from_utf8(buff);
190 void Lexer::Pimpl::printError(string const & message) const
192 string const tmpmsg = subst(message, "$$Token", getString());
193 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
194 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
198 void Lexer::Pimpl::printTable(ostream & os)
200 os << "\nNumber of tags: " << no_items << endl;
201 for (int i= 0; i < no_items; ++i)
203 << "]: tag: `" << table[i].tag
204 << "' code:" << table[i].code << '\n';
209 void Lexer::Pimpl::verifyTable()
211 // Check if the table is sorted and if not, sort it.
213 && !lyx::sorted(table, table + no_items, compare_tags())) {
214 lyxerr << "The table passed to Lexer is not sorted!\n"
215 << "Tell the developers to fix it!" << endl;
216 // We sort it anyway to avoid problems.
217 lyxerr << "\nUnsorted:" << endl;
220 sort(table, table + no_items, compare_tags());
221 lyxerr << "\nSorted:" << endl;
227 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
229 pushed_table tmppu(table, no_items);
239 void Lexer::Pimpl::popTable()
241 if (pushed.empty()) {
242 lyxerr << "Lexer error: nothing to pop!" << endl;
246 pushed_table tmp = pushed.top();
248 table = tmp.table_elem;
249 no_items = tmp.table_siz;
253 bool Lexer::Pimpl::setFile(FileName const & filename)
255 // Check the format of the file.
256 string const format = getFormatFromContents(filename);
258 if (format == "gzip" || format == "zip" || format == "compress") {
259 LYXERR(Debug::LYXLEX) << "lyxlex: compressed" << endl;
260 // The check only outputs a debug message, because it triggers
261 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
262 // a fresh new filebuf. (JMarc)
263 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
264 lyxerr[Debug::LYXLEX] << "Error in LyXLex::setFile: "
265 "file or stream already set." << endl;
266 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
268 name = filename.absFilename();
270 return gz_.is_open() && is.good();
272 LYXERR(Debug::LYXLEX) << "lyxlex: UNcompressed" << endl;
274 // The check only outputs a debug message, because it triggers
275 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
276 // a fresh new filebuf. (JMarc)
277 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
278 LYXERR(Debug::LYXLEX) << "Error in Lexer::setFile: "
279 "file or stream already set." << endl;
281 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
283 name = filename.absFilename();
285 return fb_.is_open() && is.good();
290 void Lexer::Pimpl::setStream(istream & i)
292 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
293 LYXERR(Debug::LYXLEX) << "Error in Lexer::setStream: "
294 "file or stream already set." << endl;
301 void Lexer::Pimpl::setCommentChar(char c)
307 bool Lexer::Pimpl::next(bool esc /* = false */)
309 if (!pushTok.empty()) {
310 // There can have been a whole line pushed so
311 // we extract the first word and leaves the rest
313 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
315 pushTok = split(pushTok, buff, ' ');
324 unsigned char c = 0; // getc() returns an int
327 while (is && !status) {
330 if (c == commentChar) {
331 // Read rest of line (fast :-)
333 // That is not fast... (Lgb)
337 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
338 << dummy << '\'' << endl;
340 // unfortunately ignore is buggy (Lgb)
341 is.ignore(100, '\n');
355 } while (c != '\"' && c != '\n' && is);
358 printError("Missing quote");
363 buff.resize(buff.size()-1);
369 continue; /* Skip ','s */
371 // using relational operators with chars other
372 // than == and != is not safe. And if it is done
373 // the type _have_ to be unsigned. It usually a
374 // lot better to use the functions from cctype
382 } while (c > ' ' && c != ',' && is);
387 if (c == '\r' && is) {
388 // The Windows support has lead to the
389 // possibility of "\r\n" at the end of
390 // a line. This will stop LyX choking
391 // when it expected to find a '\n'
403 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
407 unsigned char c = 0; // getc() returns an int
411 while (is && !status) {
419 if (c == commentChar) {
420 // Read rest of line (fast :-)
422 // That is still not fast... (Lgb)
426 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
427 << dummy << '\'' << endl;
429 // but ignore is also still buggy (Lgb)
430 // This is fast (Lgb)
431 is.ignore(100, '\n');
441 bool escaped = false;
446 if (c == '\r') continue;
448 // escape the next char
451 if (c == '\"' || c == '\\')
454 buff.push_back('\\');
458 if (!escaped && c == '\"')
460 } while (c != '\n' && is);
463 printError("Missing quote");
468 buff.resize(buff.size() -1);
478 // escape the next char
486 } while (c > ' ' && c != ',' && is);
498 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
505 int Lexer::Pimpl::search_kw(char const * const tag) const
507 keyword_item search_tag = { tag, 0 };
509 lower_bound(table, table + no_items,
510 search_tag, compare_tags());
511 // use the compare_ascii_no_case instead of compare_no_case,
512 // because in turkish, 'i' is not the lowercase version of 'I',
513 // and thus turkish locale breaks parsing of tags.
514 if (res != table + no_items
515 && !compare_ascii_no_case(res->tag, tag))
521 int Lexer::Pimpl::lex()
523 //NOTE: possible bug.
524 if (next() && status == LEX_TOKEN)
525 return search_kw(getString().c_str());
530 bool Lexer::Pimpl::eatLine()
534 unsigned char c = '\0';
536 while (is && c != '\n') {
539 //LYXERR(Debug::LYXLEX) << "Lexer::EatLine read char: `"
540 // << c << '\'' << endl;
547 buff.resize(buff.size() - 1);
550 } else if (buff.length() > 0) { // last line
559 bool Lexer::Pimpl::nextToken()
561 if (!pushTok.empty()) {
562 // There can have been a whole line pushed so
563 // we extract the first word and leaves the rest
565 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
567 pushTok = split(pushTok, buff, ' ');
577 while (is && !status) {
582 if (c >= ' ' && is) {
585 if (c == '\\') { // first char == '\\'
590 } while (c > ' ' && c != '\\' && is);
596 } while (c >= ' ' && c != '\\' && is);
599 if (c == '\\') is.putback(c); // put it back
610 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
616 bool Lexer::Pimpl::inputAvailable()
622 void Lexer::Pimpl::pushToken(string const & pt)
630 //////////////////////////////////////////////////////////////////////
634 //////////////////////////////////////////////////////////////////////
636 Lexer::Lexer(keyword_item * tab, int num)
637 : pimpl_(new Pimpl(tab, num))
647 bool Lexer::isOK() const
649 return pimpl_->inputAvailable();
653 void Lexer::setLineNo(int l)
659 int Lexer::getLineNo() const
661 return pimpl_->lineno;
665 istream & Lexer::getStream()
671 void Lexer::pushTable(keyword_item * tab, int num)
673 pimpl_->pushTable(tab, num);
677 void Lexer::popTable()
683 void Lexer::printTable(ostream & os)
685 pimpl_->printTable(os);
689 void Lexer::printError(string const & message) const
691 pimpl_->printError(message);
695 bool Lexer::setFile(support::FileName const & filename)
697 return pimpl_->setFile(filename);
701 void Lexer::setStream(istream & i)
703 pimpl_->setStream(i);
707 void Lexer::setCommentChar(char c)
709 pimpl_->setCommentChar(c);
714 return pimpl_->lex();
718 int Lexer::getInteger() const
720 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
722 pimpl_->printError("integer token missing");
726 if (isStrInt(pimpl_->getString()))
727 return convert<int>(pimpl_->getString());
730 pimpl_->printError("Bad integer `$$Token'");
735 double Lexer::getFloat() const
737 // replace comma with dot in case the file was written with
738 // the wrong locale (should be rare, but is easy enough to
740 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
742 pimpl_->printError("float token missing");
746 string const str = subst(pimpl_->getString(), ",", ".");
748 return convert<double>(str);
751 pimpl_->printError("Bad float `$$Token'");
756 string const Lexer::getString() const
758 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
761 return pimpl_->getString();
767 docstring const Lexer::getDocString() const
769 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
772 return pimpl_->getDocString();
778 // I would prefer to give a tag number instead of an explicit token
779 // here, but it is not possible because Buffer::readDocument uses
780 // explicit tokens (JMarc)
781 string const Lexer::getLongString(string const & endtoken)
784 bool firstline = true;
786 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
788 // blank line in the file being read
791 string const token = trim(getString(), " \t");
793 LYXERR(Debug::PARSER) << "LongString: `"
794 << getString() << '\'' << endl;
796 // We do a case independent comparison, like search_kw does.
797 if (compare_ascii_no_case(token, endtoken) == 0)
800 string tmpstr = getString();
802 string::size_type i(tmpstr.find_first_not_of(' '));
803 if (i != string::npos)
804 prefix = tmpstr.substr(0, i);
806 LYXERR(Debug::PARSER)
807 << "Prefix = `" << prefix << "\'" << endl;
810 // further lines in long strings may have the same
811 // whitespace prefix as the first line. Remove it.
812 if (prefix.length() && prefixIs(tmpstr, prefix)) {
813 tmpstr.erase(0, prefix.length() - 1);
816 str += ltrim(tmpstr, "\t") + '\n';
820 printError("Long string not ended by `" + endtoken + '\'');
827 bool Lexer::getBool() const
829 if (pimpl_->getString() == "true") {
832 } else if (pimpl_->getString() != "false") {
833 pimpl_->printError("Bad boolean `$$Token'. "
834 "Use \"false\" or \"true\"");
842 bool Lexer::eatLine()
844 return pimpl_->eatLine();
848 bool Lexer::next(bool esc)
850 return pimpl_->next(esc);
854 bool Lexer::nextToken()
856 return pimpl_->nextToken();
860 void Lexer::pushToken(string const & pt)
862 pimpl_->pushToken(pt);
866 Lexer::operator void const *() const
868 // This behaviour is NOT the same as the std::streams which would
869 // use fail() here. However, our implementation of getString() et al.
870 // can cause the eof() and fail() bits to be set, even though we
871 // haven't tried to read 'em.
872 return lastReadOk_? this : 0;
876 bool Lexer::operator!() const
882 Lexer & Lexer::operator>>(std::string & s)
894 Lexer & Lexer::operator>>(docstring & s)
906 Lexer & Lexer::operator>>(double & s)
918 Lexer & Lexer::operator>>(int & s)
930 Lexer & Lexer::operator>>(unsigned int & s)
942 Lexer & Lexer::operator>>(bool & s)
954 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
955 string const Lexer::quoteString(string const & arg)
957 std::ostringstream os;
958 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';