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>
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");
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.");
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");
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.");
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.");
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 << dummy << '\'');
338 // unfortunately ignore is buggy (Lgb)
339 is.ignore(100, '\n');
353 } while (c != '\"' && c != '\n' && is);
356 printError("Missing quote");
361 buff.resize(buff.size()-1);
367 continue; /* Skip ','s */
369 // using relational operators with chars other
370 // than == and != is not safe. And if it is done
371 // the type _have_ to be unsigned. It usually a
372 // lot better to use the functions from cctype
380 } while (c > ' ' && c != ',' && is);
385 if (c == '\r' && is) {
386 // The Windows support has lead to the
387 // possibility of "\r\n" at the end of
388 // a line. This will stop LyX choking
389 // when it expected to find a '\n'
401 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
405 unsigned char c = 0; // getc() returns an int
409 while (is && !status) {
417 if (c == commentChar) {
418 // Read rest of line (fast :-)
420 // That is still not fast... (Lgb)
424 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
426 // but ignore is also still buggy (Lgb)
427 // This is fast (Lgb)
428 is.ignore(100, '\n');
438 bool escaped = false;
443 if (c == '\r') continue;
445 // escape the next char
448 if (c == '\"' || c == '\\')
451 buff.push_back('\\');
455 if (!escaped && c == '\"')
457 } while (c != '\n' && is);
460 printError("Missing quote");
465 buff.resize(buff.size() -1);
475 // escape the next char
483 } while (c > ' ' && c != ',' && is);
495 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
502 int Lexer::Pimpl::search_kw(char const * const tag) const
504 keyword_item search_tag = { tag, 0 };
506 lower_bound(table, table + no_items,
507 search_tag, compare_tags());
508 // use the compare_ascii_no_case instead of compare_no_case,
509 // because in turkish, 'i' is not the lowercase version of 'I',
510 // and thus turkish locale breaks parsing of tags.
511 if (res != table + no_items
512 && !compare_ascii_no_case(res->tag, tag))
518 int Lexer::Pimpl::lex()
520 //NOTE: possible bug.
521 if (next() && status == LEX_TOKEN)
522 return search_kw(getString().c_str());
527 bool Lexer::Pimpl::eatLine()
531 unsigned char c = '\0';
533 while (is && c != '\n') {
536 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
543 buff.resize(buff.size() - 1);
546 } else if (buff.length() > 0) { // last line
555 bool Lexer::Pimpl::nextToken()
557 if (!pushTok.empty()) {
558 // There can have been a whole line pushed so
559 // we extract the first word and leaves the rest
561 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
563 pushTok = split(pushTok, buff, ' ');
573 while (is && !status) {
578 if (c >= ' ' && is) {
581 if (c == '\\') { // first char == '\\'
586 } while (c > ' ' && c != '\\' && is);
592 } while (c >= ' ' && c != '\\' && is);
595 if (c == '\\') is.putback(c); // put it back
606 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
612 bool Lexer::Pimpl::inputAvailable()
618 void Lexer::Pimpl::pushToken(string const & pt)
626 //////////////////////////////////////////////////////////////////////
630 //////////////////////////////////////////////////////////////////////
632 Lexer::Lexer(keyword_item * tab, int num)
633 : pimpl_(new Pimpl(tab, num))
643 bool Lexer::isOK() const
645 return pimpl_->inputAvailable();
649 void Lexer::setLineNo(int l)
655 int Lexer::getLineNo() const
657 return pimpl_->lineno;
661 istream & Lexer::getStream()
667 void Lexer::pushTable(keyword_item * tab, int num)
669 pimpl_->pushTable(tab, num);
673 void Lexer::popTable()
679 void Lexer::printTable(ostream & os)
681 pimpl_->printTable(os);
685 void Lexer::printError(string const & message) const
687 pimpl_->printError(message);
691 bool Lexer::setFile(support::FileName const & filename)
693 return pimpl_->setFile(filename);
697 void Lexer::setStream(istream & i)
699 pimpl_->setStream(i);
703 void Lexer::setCommentChar(char c)
705 pimpl_->setCommentChar(c);
710 return pimpl_->lex();
714 int Lexer::getInteger() const
716 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
718 pimpl_->printError("integer token missing");
722 if (isStrInt(pimpl_->getString()))
723 return convert<int>(pimpl_->getString());
726 pimpl_->printError("Bad integer `$$Token'");
731 double Lexer::getFloat() const
733 // replace comma with dot in case the file was written with
734 // the wrong locale (should be rare, but is easy enough to
736 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
738 pimpl_->printError("float token missing");
742 string const str = subst(pimpl_->getString(), ",", ".");
744 return convert<double>(str);
747 pimpl_->printError("Bad float `$$Token'");
752 string const Lexer::getString() const
754 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
757 return pimpl_->getString();
763 docstring const Lexer::getDocString() const
765 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
768 return pimpl_->getDocString();
774 // I would prefer to give a tag number instead of an explicit token
775 // here, but it is not possible because Buffer::readDocument uses
776 // explicit tokens (JMarc)
777 string const Lexer::getLongString(string const & endtoken)
780 bool firstline = true;
782 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
784 // blank line in the file being read
787 string const token = trim(getString(), " \t");
789 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
791 // We do a case independent comparison, like search_kw does.
792 if (compare_ascii_no_case(token, endtoken) == 0)
795 string tmpstr = getString();
797 string::size_type i(tmpstr.find_first_not_of(' '));
798 if (i != string::npos)
799 prefix = tmpstr.substr(0, i);
801 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
804 // further lines in long strings may have the same
805 // whitespace prefix as the first line. Remove it.
806 if (prefix.length() && prefixIs(tmpstr, prefix)) {
807 tmpstr.erase(0, prefix.length() - 1);
810 str += ltrim(tmpstr, "\t") + '\n';
814 printError("Long string not ended by `" + endtoken + '\'');
821 bool Lexer::getBool() const
823 if (pimpl_->getString() == "true") {
826 } else if (pimpl_->getString() != "false") {
827 pimpl_->printError("Bad boolean `$$Token'. "
828 "Use \"false\" or \"true\"");
836 bool Lexer::eatLine()
838 return pimpl_->eatLine();
842 bool Lexer::next(bool esc)
844 return pimpl_->next(esc);
848 bool Lexer::nextToken()
850 return pimpl_->nextToken();
854 void Lexer::pushToken(string const & pt)
856 pimpl_->pushToken(pt);
860 Lexer::operator void const *() const
862 // This behaviour is NOT the same as the std::streams which would
863 // use fail() here. However, our implementation of getString() et al.
864 // can cause the eof() and fail() bits to be set, even though we
865 // haven't tried to read 'em.
866 return lastReadOk_? this : 0;
870 bool Lexer::operator!() const
876 Lexer & Lexer::operator>>(std::string & s)
888 Lexer & Lexer::operator>>(docstring & s)
900 Lexer & Lexer::operator>>(double & s)
912 Lexer & Lexer::operator>>(int & s)
924 Lexer & Lexer::operator>>(unsigned int & s)
936 Lexer & Lexer::operator>>(bool & s)
948 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
949 string const Lexer::quoteString(string const & arg)
951 std::ostringstream os;
952 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';