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/FileName.h"
22 #include "support/filetools.h"
23 #include "support/gzstream.h"
24 #include "support/lstrings.h"
25 #include "support/lyxalgo.h"
26 #include "support/types.h"
27 #include "support/unicode.h"
29 #include <boost/noncopyable.hpp>
38 using namespace lyx::support;
42 //////////////////////////////////////////////////////////////////////
46 //////////////////////////////////////////////////////////////////////
50 class Lexer::Pimpl : boost::noncopyable {
53 Pimpl(keyword_item * tab, int num);
55 string const getString() const;
57 docstring const getDocString() const;
59 void printError(string const & message) const;
61 void printTable(ostream & os);
63 void pushTable(keyword_item * tab, int num);
67 bool setFile(FileName const & filename);
69 void setStream(istream & i);
71 void setCommentChar(char c);
73 bool next(bool esc = false);
75 int search_kw(char const * const tag) const;
82 /// test if there is a pushed token or the stream is ok
83 bool inputAvailable();
85 void pushToken(string const &);
86 /// fb_ is only used to open files, the stream is accessed through is.
89 /// gz_ is only used to open files, the stream is accessed through is.
92 /// the stream that we use.
118 : table_elem(0), table_siz(0) {}
120 pushed_table(keyword_item * ki, int siz)
121 : table_elem(ki), table_siz(siz) {}
123 keyword_item * table_elem;
128 stack<pushed_table> pushed;
136 : public binary_function<keyword_item, keyword_item, bool> {
138 // used by lower_bound, sort and sorted
139 bool operator()(keyword_item const & a, keyword_item const & b) const
141 // we use the ascii version, because in turkish, 'i'
142 // is not the lowercase version of 'I', and thus
143 // turkish locale breaks parsing of tags.
144 return compare_ascii_no_case(a.tag, b.tag) < 0;
148 } // end of anon namespace
151 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
152 : is(&fb_), table(tab), no_items(num),
153 status(0), lineno(0), commentChar('#')
159 string const Lexer::Pimpl::getString() const
165 docstring const Lexer::Pimpl::getDocString() const
167 return from_utf8(buff);
171 void Lexer::Pimpl::printError(string const & message) const
173 string const tmpmsg = subst(message, "$$Token", getString());
174 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
175 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
179 void Lexer::Pimpl::printTable(ostream & os)
181 os << "\nNumber of tags: " << no_items << endl;
182 for (int i= 0; i < no_items; ++i)
184 << "]: tag: `" << table[i].tag
185 << "' code:" << table[i].code << '\n';
190 void Lexer::Pimpl::verifyTable()
192 // Check if the table is sorted and if not, sort it.
194 && !lyx::sorted(table, table + no_items, compare_tags())) {
195 lyxerr << "The table passed to Lexer is not sorted!\n"
196 << "Tell the developers to fix it!" << endl;
197 // We sort it anyway to avoid problems.
198 lyxerr << "\nUnsorted:" << endl;
201 sort(table, table + no_items, compare_tags());
202 lyxerr << "\nSorted:" << endl;
208 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
210 pushed_table tmppu(table, no_items);
220 void Lexer::Pimpl::popTable()
222 if (pushed.empty()) {
223 lyxerr << "Lexer error: nothing to pop!" << endl;
227 pushed_table tmp = pushed.top();
229 table = tmp.table_elem;
230 no_items = tmp.table_siz;
234 bool Lexer::Pimpl::setFile(FileName const & filename)
236 // Check the format of the file.
237 string const format = filename.guessFormatFromContents();
239 if (format == "gzip" || format == "zip" || format == "compress") {
240 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
241 // The check only outputs a debug message, because it triggers
242 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
243 // a fresh new filebuf. (JMarc)
244 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
245 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
246 "file or stream already set.");
247 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
249 name = filename.absFilename();
251 return gz_.is_open() && is.good();
253 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
255 // The check only outputs a debug message, because it triggers
256 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
257 // a fresh new filebuf. (JMarc)
258 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
259 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
260 "file or stream already set.");
262 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
264 name = filename.absFilename();
266 return fb_.is_open() && is.good();
271 void Lexer::Pimpl::setStream(istream & i)
273 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
274 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
275 "file or stream already set.");
282 void Lexer::Pimpl::setCommentChar(char c)
288 bool Lexer::Pimpl::next(bool esc /* = false */)
290 if (!pushTok.empty()) {
291 // There can have been a whole line pushed so
292 // we extract the first word and leaves the rest
294 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
296 pushTok = split(pushTok, buff, ' ');
305 unsigned char c = 0; // getc() returns an int
308 while (is && !status) {
311 if (c == commentChar) {
312 // Read rest of line (fast :-)
314 // That is not fast... (Lgb)
318 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
320 // unfortunately ignore is buggy (Lgb)
321 is.ignore(100, '\n');
335 } while (c != '\"' && c != '\n' && is);
338 printError("Missing quote");
343 buff.resize(buff.size()-1);
349 continue; /* Skip ','s */
351 // using relational operators with chars other
352 // than == and != is not safe. And if it is done
353 // the type _have_ to be unsigned. It usually a
354 // lot better to use the functions from cctype
362 } while (c > ' ' && c != ',' && is);
367 if (c == '\r' && is) {
368 // The Windows support has lead to the
369 // possibility of "\r\n" at the end of
370 // a line. This will stop LyX choking
371 // when it expected to find a '\n'
383 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
387 unsigned char c = 0; // getc() returns an int
391 while (is && !status) {
399 if (c == commentChar) {
400 // Read rest of line (fast :-)
402 // That is still not fast... (Lgb)
406 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
408 // but ignore is also still buggy (Lgb)
409 // This is fast (Lgb)
410 is.ignore(100, '\n');
420 bool escaped = false;
425 if (c == '\r') continue;
427 // escape the next char
430 if (c == '\"' || c == '\\')
433 buff.push_back('\\');
437 if (!escaped && c == '\"')
439 } while (c != '\n' && is);
442 printError("Missing quote");
447 buff.resize(buff.size() -1);
457 // escape the next char
465 } while (c > ' ' && c != ',' && is);
477 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
484 int Lexer::Pimpl::search_kw(char const * const tag) const
486 keyword_item search_tag = { tag, 0 };
488 lower_bound(table, table + no_items,
489 search_tag, compare_tags());
490 // use the compare_ascii_no_case instead of compare_no_case,
491 // because in turkish, 'i' is not the lowercase version of 'I',
492 // and thus turkish locale breaks parsing of tags.
493 if (res != table + no_items
494 && !compare_ascii_no_case(res->tag, tag))
500 int Lexer::Pimpl::lex()
502 //NOTE: possible bug.
503 if (next() && status == LEX_TOKEN)
504 return search_kw(getString().c_str());
509 bool Lexer::Pimpl::eatLine()
513 unsigned char c = '\0';
515 while (is && c != '\n') {
518 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
525 buff.resize(buff.size() - 1);
528 } else if (buff.length() > 0) { // last line
537 bool Lexer::Pimpl::nextToken()
539 if (!pushTok.empty()) {
540 // There can have been a whole line pushed so
541 // we extract the first word and leaves the rest
543 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
545 pushTok = split(pushTok, buff, ' ');
555 while (is && !status) {
560 if (c >= ' ' && is) {
563 if (c == '\\') { // first char == '\\'
568 } while (c > ' ' && c != '\\' && is);
574 } while (c >= ' ' && c != '\\' && is);
577 if (c == '\\') is.putback(c); // put it back
588 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
594 bool Lexer::Pimpl::inputAvailable()
600 void Lexer::Pimpl::pushToken(string const & pt)
608 //////////////////////////////////////////////////////////////////////
612 //////////////////////////////////////////////////////////////////////
614 Lexer::Lexer(keyword_item * tab, int num)
615 : pimpl_(new Pimpl(tab, num))
625 bool Lexer::isOK() const
627 return pimpl_->inputAvailable();
631 void Lexer::setLineNo(int l)
637 int Lexer::getLineNo() const
639 return pimpl_->lineno;
643 istream & Lexer::getStream()
649 void Lexer::pushTable(keyword_item * tab, int num)
651 pimpl_->pushTable(tab, num);
655 void Lexer::popTable()
661 void Lexer::printTable(ostream & os)
663 pimpl_->printTable(os);
667 void Lexer::printError(string const & message) const
669 pimpl_->printError(message);
673 bool Lexer::setFile(FileName const & filename)
675 return pimpl_->setFile(filename);
679 void Lexer::setStream(istream & i)
681 pimpl_->setStream(i);
685 void Lexer::setCommentChar(char c)
687 pimpl_->setCommentChar(c);
692 return pimpl_->lex();
696 int Lexer::getInteger() const
698 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
700 pimpl_->printError("integer token missing");
704 if (isStrInt(pimpl_->getString()))
705 return convert<int>(pimpl_->getString());
708 pimpl_->printError("Bad integer `$$Token'");
713 double Lexer::getFloat() const
715 // replace comma with dot in case the file was written with
716 // the wrong locale (should be rare, but is easy enough to
718 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
720 pimpl_->printError("float token missing");
724 string const str = subst(pimpl_->getString(), ",", ".");
726 return convert<double>(str);
729 pimpl_->printError("Bad float `$$Token'");
734 string const Lexer::getString() const
736 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
739 return pimpl_->getString();
745 docstring const Lexer::getDocString() const
747 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
750 return pimpl_->getDocString();
756 // I would prefer to give a tag number instead of an explicit token
757 // here, but it is not possible because Buffer::readDocument uses
758 // explicit tokens (JMarc)
759 string const Lexer::getLongString(string const & endtoken)
762 bool firstline = true;
764 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
766 // blank line in the file being read
769 string const token = trim(getString(), " \t");
771 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
773 // We do a case independent comparison, like search_kw does.
774 if (compare_ascii_no_case(token, endtoken) == 0)
777 string tmpstr = getString();
779 string::size_type i(tmpstr.find_first_not_of(' '));
780 if (i != string::npos)
781 prefix = tmpstr.substr(0, i);
783 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
786 // further lines in long strings may have the same
787 // whitespace prefix as the first line. Remove it.
788 if (prefix.length() && prefixIs(tmpstr, prefix)) {
789 tmpstr.erase(0, prefix.length() - 1);
792 str += ltrim(tmpstr, "\t") + '\n';
796 printError("Long string not ended by `" + endtoken + '\'');
803 bool Lexer::getBool() const
805 if (pimpl_->getString() == "true") {
808 } else if (pimpl_->getString() != "false") {
809 pimpl_->printError("Bad boolean `$$Token'. "
810 "Use \"false\" or \"true\"");
818 bool Lexer::eatLine()
820 return pimpl_->eatLine();
824 bool Lexer::next(bool esc)
826 return pimpl_->next(esc);
830 bool Lexer::nextToken()
832 return pimpl_->nextToken();
836 void Lexer::pushToken(string const & pt)
838 pimpl_->pushToken(pt);
842 Lexer::operator void const *() const
844 // This behaviour is NOT the same as the streams which would
845 // use fail() here. However, our implementation of getString() et al.
846 // can cause the eof() and fail() bits to be set, even though we
847 // haven't tried to read 'em.
848 return lastReadOk_? this : 0;
852 bool Lexer::operator!() const
858 Lexer & Lexer::operator>>(string & s)
870 Lexer & Lexer::operator>>(docstring & s)
882 Lexer & Lexer::operator>>(double & s)
894 Lexer & Lexer::operator>>(int & s)
906 Lexer & Lexer::operator>>(unsigned int & s)
918 Lexer & Lexer::operator>>(bool & s)
930 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
931 string const Lexer::quoteString(string const & arg)
934 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';