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/convert.h"
19 #include "support/debug.h"
20 #include "support/FileName.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"
33 using namespace lyx::support;
37 //////////////////////////////////////////////////////////////////////
41 //////////////////////////////////////////////////////////////////////
48 Pimpl(keyword_item * tab, int num);
50 string const getString() const;
52 docstring const getDocString() const;
54 void printError(string const & message) const;
56 void printTable(ostream & os);
58 void pushTable(keyword_item * tab, int num);
62 bool setFile(FileName const & filename);
64 void setStream(istream & i);
66 void setCommentChar(char c);
68 bool next(bool esc = false);
70 int search_kw(char const * const tag) const;
77 /// test if there is a pushed token or the stream is ok
78 bool inputAvailable();
80 void pushToken(string const &);
81 /// fb_ is only used to open files, the stream is accessed through is.
84 /// gz_ is only used to open files, the stream is accessed through is.
87 /// the stream that we use.
107 Pimpl(Pimpl const &);
108 void operator=(Pimpl const &);
117 : table_elem(0), table_siz(0) {}
119 PushedTable(keyword_item * ki, int siz)
120 : table_elem(ki), table_siz(siz) {}
122 keyword_item * table_elem;
127 stack<PushedTable> pushed;
135 : public binary_function<keyword_item, keyword_item, bool> {
137 // used by lower_bound, sort and sorted
138 bool operator()(keyword_item const & a, keyword_item const & b) const
140 // we use the ascii version, because in turkish, 'i'
141 // is not the lowercase version of 'I', and thus
142 // turkish locale breaks parsing of tags.
143 return compare_ascii_no_case(a.tag, b.tag) < 0;
147 } // end of anon namespace
150 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
151 : is(&fb_), table(tab), no_items(num),
152 status(0), lineno(0), commentChar('#')
158 string const Lexer::Pimpl::getString() const
164 docstring const Lexer::Pimpl::getDocString() const
166 return from_utf8(buff);
170 void Lexer::Pimpl::printError(string const & message) const
172 string const tmpmsg = subst(message, "$$Token", getString());
173 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
174 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
178 void Lexer::Pimpl::printTable(ostream & os)
180 os << "\nNumber of tags: " << no_items << endl;
181 for (int i= 0; i < no_items; ++i)
183 << "]: tag: `" << table[i].tag
184 << "' code:" << table[i].code << '\n';
189 void Lexer::Pimpl::verifyTable()
191 // Check if the table is sorted and if not, sort it.
193 && !lyx::sorted(table, table + no_items, CompareTags())) {
194 lyxerr << "The table passed to Lexer is not sorted!\n"
195 << "Tell the developers to fix it!" << endl;
196 // We sort it anyway to avoid problems.
197 lyxerr << "\nUnsorted:" << endl;
200 sort(table, table + no_items, CompareTags());
201 lyxerr << "\nSorted:" << endl;
207 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
209 PushedTable tmppu(table, no_items);
219 void Lexer::Pimpl::popTable()
221 if (pushed.empty()) {
222 lyxerr << "Lexer error: nothing to pop!" << endl;
226 PushedTable tmp = pushed.top();
228 table = tmp.table_elem;
229 no_items = tmp.table_siz;
233 bool Lexer::Pimpl::setFile(FileName const & filename)
235 // Check the format of the file.
236 string const format = filename.guessFormatFromContents();
238 if (format == "gzip" || format == "zip" || format == "compress") {
239 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
240 // The check only outputs a debug message, because it triggers
241 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
242 // a fresh new filebuf. (JMarc)
243 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
244 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
245 "file or stream already set.");
246 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
248 name = filename.absFilename();
250 return gz_.is_open() && is.good();
252 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
254 // The check only outputs a debug message, because it triggers
255 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
256 // a fresh new filebuf. (JMarc)
257 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
258 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
259 "file or stream already set.");
261 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
263 name = filename.absFilename();
265 return fb_.is_open() && is.good();
270 void Lexer::Pimpl::setStream(istream & i)
272 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
273 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
274 "file or stream already set.");
281 void Lexer::Pimpl::setCommentChar(char c)
287 bool Lexer::Pimpl::next(bool esc /* = false */)
289 if (!pushTok.empty()) {
290 // There can have been a whole line pushed so
291 // we extract the first word and leaves the rest
293 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
295 pushTok = split(pushTok, buff, ' ');
304 unsigned char c = 0; // getc() returns an int
307 while (is && !status) {
310 if (c == commentChar) {
311 // Read rest of line (fast :-)
313 // That is not fast... (Lgb)
317 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
319 // unfortunately ignore is buggy (Lgb)
320 is.ignore(100, '\n');
334 } while (c != '\"' && c != '\n' && is);
337 printError("Missing quote");
342 buff.resize(buff.size()-1);
348 continue; /* Skip ','s */
350 // using relational operators with chars other
351 // than == and != is not safe. And if it is done
352 // the type _have_ to be unsigned. It usually a
353 // lot better to use the functions from cctype
361 } while (c > ' ' && c != ',' && is);
366 if (c == '\r' && is) {
367 // The Windows support has lead to the
368 // possibility of "\r\n" at the end of
369 // a line. This will stop LyX choking
370 // when it expected to find a '\n'
382 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
386 unsigned char c = 0; // getc() returns an int
390 while (is && !status) {
398 if (c == commentChar) {
399 // Read rest of line (fast :-)
401 // That is still not fast... (Lgb)
405 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
407 // but ignore is also still buggy (Lgb)
408 // This is fast (Lgb)
409 is.ignore(100, '\n');
419 bool escaped = false;
424 if (c == '\r') continue;
426 // escape the next char
429 if (c == '\"' || c == '\\')
432 buff.push_back('\\');
436 if (!escaped && c == '\"')
438 } while (c != '\n' && is);
441 printError("Missing quote");
446 buff.resize(buff.size() -1);
456 // escape the next char
464 } while (c > ' ' && c != ',' && is);
476 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
483 int Lexer::Pimpl::search_kw(char const * const tag) const
485 keyword_item search_tag = { tag, 0 };
487 lower_bound(table, table + no_items,
488 search_tag, CompareTags());
489 // use the compare_ascii_no_case instead of compare_no_case,
490 // because in turkish, 'i' is not the lowercase version of 'I',
491 // and thus turkish locale breaks parsing of tags.
492 if (res != table + no_items
493 && !compare_ascii_no_case(res->tag, tag))
499 int Lexer::Pimpl::lex()
501 //NOTE: possible bug.
502 if (next() && status == LEX_TOKEN)
503 return search_kw(getString().c_str());
508 bool Lexer::Pimpl::eatLine()
512 unsigned char c = '\0';
514 while (is && c != '\n') {
517 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
524 buff.resize(buff.size() - 1);
527 } else if (buff.length() > 0) { // last line
536 bool Lexer::Pimpl::nextToken()
538 if (!pushTok.empty()) {
539 // There can have been a whole line pushed so
540 // we extract the first word and leaves the rest
542 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
544 pushTok = split(pushTok, buff, ' ');
554 while (is && !status) {
559 if (c >= ' ' && is) {
562 if (c == '\\') { // first char == '\\'
567 } while (c > ' ' && c != '\\' && is);
573 } while (c >= ' ' && c != '\\' && is);
577 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)
763 bool firstline = true;
765 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
767 // blank line in the file being read
770 string const token = trim(getString(), " \t");
772 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
774 // We do a case independent comparison, like search_kw does.
775 if (compare_ascii_no_case(token, endtoken) == 0)
778 string tmpstr = getString();
780 size_t i = tmpstr.find_first_not_of(' ');
781 if (i != string::npos)
782 prefix = tmpstr.substr(0, i);
784 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
787 // further lines in long strings may have the same
788 // whitespace prefix as the first line. Remove it.
789 if (prefix.length() && prefixIs(tmpstr, prefix))
790 tmpstr.erase(0, prefix.length() - 1);
792 str += ltrim(tmpstr, "\t") + '\n';
796 printError("Long string not ended by `" + endtoken + '\'');
802 bool Lexer::getBool() const
804 if (pimpl_->getString() == "true") {
807 } else if (pimpl_->getString() != "false") {
808 pimpl_->printError("Bad boolean `$$Token'. "
809 "Use \"false\" or \"true\"");
817 bool Lexer::eatLine()
819 return pimpl_->eatLine();
823 bool Lexer::next(bool esc)
825 return pimpl_->next(esc);
829 bool Lexer::nextToken()
831 return pimpl_->nextToken();
835 void Lexer::pushToken(string const & pt)
837 pimpl_->pushToken(pt);
841 Lexer::operator void const *() const
843 // This behaviour is NOT the same as the streams which would
844 // use fail() here. However, our implementation of getString() et al.
845 // can cause the eof() and fail() bits to be set, even though we
846 // haven't tried to read 'em.
847 return lastReadOk_? this : 0;
851 bool Lexer::operator!() const
857 Lexer & Lexer::operator>>(string & s)
869 Lexer & Lexer::operator>>(docstring & s)
881 Lexer & Lexer::operator>>(double & s)
893 Lexer & Lexer::operator>>(int & s)
905 Lexer & Lexer::operator>>(unsigned int & s)
917 Lexer & Lexer::operator>>(bool & s)
929 // quotes a string, e.g. for use in preferences files or as an argument
930 // of the "log" dialog
931 string const Lexer::quoteString(string const & arg)
935 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");