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;
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;
299 void Lexer::Pimpl::setCommentChar(char c)
305 bool Lexer::Pimpl::next(bool esc /* = false */)
307 if (!pushTok.empty()) {
308 // There can have been a whole line pushed so
309 // we extract the first word and leaves the rest
311 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
313 pushTok = split(pushTok, buff, ' ');
322 unsigned char c = 0; // getc() returns an int
325 while (is && !status) {
328 if (c == commentChar) {
329 // Read rest of line (fast :-)
331 // That is not fast... (Lgb)
335 LYXERR(Debug::LYXLEX) << "Comment read: `" << c
336 << dummy << '\'' << endl;
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
425 << dummy << '\'' << endl;
427 // but ignore is also still buggy (Lgb)
428 // This is fast (Lgb)
429 is.ignore(100, '\n');
439 bool escaped = false;
444 if (c == '\r') continue;
446 // escape the next char
449 if (c == '\"' || c == '\\')
452 buff.push_back('\\');
456 if (!escaped && c == '\"')
458 } while (c != '\n' && is);
461 printError("Missing quote");
466 buff.resize(buff.size() -1);
476 // escape the next char
484 } while (c > ' ' && c != ',' && is);
496 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
503 int Lexer::Pimpl::search_kw(char const * const tag) const
505 keyword_item search_tag = { tag, 0 };
507 lower_bound(table, table + no_items,
508 search_tag, compare_tags());
509 // use the compare_ascii_no_case instead of compare_no_case,
510 // because in turkish, 'i' is not the lowercase version of 'I',
511 // and thus turkish locale breaks parsing of tags.
512 if (res != table + no_items
513 && !compare_ascii_no_case(res->tag, tag))
519 int Lexer::Pimpl::lex()
521 //NOTE: possible bug.
522 if (next() && status == LEX_TOKEN)
523 return search_kw(getString().c_str());
528 bool Lexer::Pimpl::eatLine()
532 unsigned char c = '\0';
534 while (is && c != '\n') {
537 //LYXERR(Debug::LYXLEX) << "Lexer::EatLine read char: `"
538 // << c << '\'' << endl;
545 buff.resize(buff.size() - 1);
548 } else if (buff.length() > 0) { // last line
557 bool Lexer::Pimpl::nextToken()
559 if (!pushTok.empty()) {
560 // There can have been a whole line pushed so
561 // we extract the first word and leaves the rest
563 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
565 pushTok = split(pushTok, buff, ' ');
575 while (is && !status) {
580 if (c >= ' ' && is) {
583 if (c == '\\') { // first char == '\\'
588 } while (c > ' ' && c != '\\' && is);
594 } while (c >= ' ' && c != '\\' && is);
597 if (c == '\\') is.putback(c); // put it back
608 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
614 bool Lexer::Pimpl::inputAvailable()
620 void Lexer::Pimpl::pushToken(string const & pt)
628 //////////////////////////////////////////////////////////////////////
632 //////////////////////////////////////////////////////////////////////
634 Lexer::Lexer(keyword_item * tab, int num)
635 : pimpl_(new Pimpl(tab, num))
645 bool Lexer::isOK() const
647 return pimpl_->inputAvailable();
651 void Lexer::setLineNo(int l)
657 int Lexer::getLineNo() const
659 return pimpl_->lineno;
663 istream & Lexer::getStream()
669 void Lexer::pushTable(keyword_item * tab, int num)
671 pimpl_->pushTable(tab, num);
675 void Lexer::popTable()
681 void Lexer::printTable(ostream & os)
683 pimpl_->printTable(os);
687 void Lexer::printError(string const & message) const
689 pimpl_->printError(message);
693 bool Lexer::setFile(support::FileName const & filename)
695 return pimpl_->setFile(filename);
699 void Lexer::setStream(istream & i)
701 pimpl_->setStream(i);
705 void Lexer::setCommentChar(char c)
707 pimpl_->setCommentChar(c);
712 return pimpl_->lex();
716 int Lexer::getInteger() const
718 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
720 pimpl_->printError("integer token missing");
724 if (isStrInt(pimpl_->getString()))
725 return convert<int>(pimpl_->getString());
728 pimpl_->printError("Bad integer `$$Token'");
733 double Lexer::getFloat() const
735 // replace comma with dot in case the file was written with
736 // the wrong locale (should be rare, but is easy enough to
738 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
740 pimpl_->printError("float token missing");
744 string const str = subst(pimpl_->getString(), ",", ".");
746 return convert<double>(str);
749 pimpl_->printError("Bad float `$$Token'");
754 string const Lexer::getString() const
756 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
759 return pimpl_->getString();
765 docstring const Lexer::getDocString() const
767 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
770 return pimpl_->getDocString();
776 // I would prefer to give a tag number instead of an explicit token
777 // here, but it is not possible because Buffer::readDocument uses
778 // explicit tokens (JMarc)
779 string const Lexer::getLongString(string const & endtoken)
782 bool firstline = true;
784 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
786 // blank line in the file being read
789 string const token = trim(getString(), " \t");
791 LYXERR(Debug::PARSER) << "LongString: `"
792 << getString() << '\'' << endl;
794 // We do a case independent comparison, like search_kw does.
795 if (compare_ascii_no_case(token, endtoken) == 0)
798 string tmpstr = getString();
800 string::size_type i(tmpstr.find_first_not_of(' '));
801 if (i != string::npos)
802 prefix = tmpstr.substr(0, i);
804 LYXERR(Debug::PARSER)
805 << "Prefix = `" << prefix << "\'" << endl;
808 // further lines in long strings may have the same
809 // whitespace prefix as the first line. Remove it.
810 if (prefix.length() && prefixIs(tmpstr, prefix)) {
811 tmpstr.erase(0, prefix.length() - 1);
814 str += ltrim(tmpstr, "\t") + '\n';
818 printError("Long string not ended by `" + endtoken + '\'');
825 bool Lexer::getBool() const
827 if (pimpl_->getString() == "true") {
830 } else if (pimpl_->getString() != "false") {
831 pimpl_->printError("Bad boolean `$$Token'. "
832 "Use \"false\" or \"true\"");
840 bool Lexer::eatLine()
842 return pimpl_->eatLine();
846 bool Lexer::next(bool esc)
848 return pimpl_->next(esc);
852 bool Lexer::nextToken()
854 return pimpl_->nextToken();
858 void Lexer::pushToken(string const & pt)
860 pimpl_->pushToken(pt);
864 Lexer::operator void const *() const
866 // This behaviour is NOT the same as the std::streams which would
867 // use fail() here. However, our implementation of getString() et al.
868 // can cause the eof() and fail() bits to be set, even though we
869 // haven't tried to read 'em.
870 return lastReadOk_? this : 0;
874 bool Lexer::operator!() const
880 Lexer & Lexer::operator>>(std::string & s)
892 Lexer & Lexer::operator>>(docstring & s)
904 Lexer & Lexer::operator>>(double & s)
916 Lexer & Lexer::operator>>(int & s)
928 Lexer & Lexer::operator>>(unsigned int & s)
940 Lexer & Lexer::operator>>(bool & s)
952 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
953 string const Lexer::quoteString(string const & arg)
955 std::ostringstream os;
956 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';