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(LexerKeyword * 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(LexerKeyword * 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(LexerKeyword * ki, int siz)
120 : table_elem(ki), table_siz(siz) {}
122 LexerKeyword * table_elem;
127 stack<PushedTable> pushed;
135 : public binary_function<LexerKeyword, LexerKeyword, bool> {
137 // used by lower_bound, sort and sorted
138 bool operator()(LexerKeyword const & a, LexerKeyword 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(LexerKeyword * 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(LexerKeyword * 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 LexerKeyword 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 //////////////////////////////////////////////////////////////////////
615 : pimpl_(new Pimpl(0, 0))
619 void Lexer::init(LexerKeyword * tab, int num)
621 pimpl_ = new Pimpl(tab, num);
631 bool Lexer::isOK() const
633 return pimpl_->inputAvailable();
637 void Lexer::setLineNumber(int l)
643 int Lexer::lineNumber() const
645 return pimpl_->lineno;
649 istream & Lexer::getStream()
655 void Lexer::pushTable(LexerKeyword * tab, int num)
657 pimpl_->pushTable(tab, num);
661 void Lexer::popTable()
667 void Lexer::printTable(ostream & os)
669 pimpl_->printTable(os);
673 void Lexer::printError(string const & message) const
675 pimpl_->printError(message);
679 bool Lexer::setFile(FileName const & filename)
681 return pimpl_->setFile(filename);
685 void Lexer::setStream(istream & i)
687 pimpl_->setStream(i);
691 void Lexer::setCommentChar(char c)
693 pimpl_->setCommentChar(c);
698 return pimpl_->lex();
702 int Lexer::getInteger() const
704 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
706 pimpl_->printError("integer token missing");
710 if (isStrInt(pimpl_->getString()))
711 return convert<int>(pimpl_->getString());
714 pimpl_->printError("Bad integer `$$Token'");
719 double Lexer::getFloat() const
721 // replace comma with dot in case the file was written with
722 // the wrong locale (should be rare, but is easy enough to
724 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
726 pimpl_->printError("float token missing");
730 string const str = subst(pimpl_->getString(), ",", ".");
732 return convert<double>(str);
735 pimpl_->printError("Bad float `$$Token'");
740 string const Lexer::getString() const
742 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
745 return pimpl_->getString();
751 docstring const Lexer::getDocString() const
753 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
756 return pimpl_->getDocString();
762 // I would prefer to give a tag number instead of an explicit token
763 // here, but it is not possible because Buffer::readDocument uses
764 // explicit tokens (JMarc)
765 string const Lexer::getLongString(string const & endtoken)
769 bool firstline = true;
771 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
773 // blank line in the file being read
776 string const token = trim(getString(), " \t");
778 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
780 // We do a case independent comparison, like search_kw does.
781 if (compare_ascii_no_case(token, endtoken) == 0)
784 string tmpstr = getString();
786 size_t i = tmpstr.find_first_not_of(' ');
787 if (i != string::npos)
788 prefix = tmpstr.substr(0, i);
790 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
793 // further lines in long strings may have the same
794 // whitespace prefix as the first line. Remove it.
795 if (prefix.length() && prefixIs(tmpstr, prefix))
796 tmpstr.erase(0, prefix.length() - 1);
798 str += ltrim(tmpstr, "\t") + '\n';
802 printError("Long string not ended by `" + endtoken + '\'');
808 bool Lexer::getBool() const
810 if (pimpl_->getString() == "true") {
813 } else if (pimpl_->getString() != "false") {
814 pimpl_->printError("Bad boolean `$$Token'. "
815 "Use \"false\" or \"true\"");
823 bool Lexer::eatLine()
825 return pimpl_->eatLine();
829 bool Lexer::next(bool esc)
831 return pimpl_->next(esc);
835 bool Lexer::nextToken()
837 return pimpl_->nextToken();
841 void Lexer::pushToken(string const & pt)
843 pimpl_->pushToken(pt);
847 Lexer::operator void const *() const
849 // This behaviour is NOT the same as the streams which would
850 // use fail() here. However, our implementation of getString() et al.
851 // can cause the eof() and fail() bits to be set, even though we
852 // haven't tried to read 'em.
853 return lastReadOk_? this : 0;
857 bool Lexer::operator!() const
863 Lexer & Lexer::operator>>(string & s)
875 Lexer & Lexer::operator>>(docstring & s)
887 Lexer & Lexer::operator>>(double & s)
899 Lexer & Lexer::operator>>(int & s)
911 Lexer & Lexer::operator>>(unsigned int & s)
923 Lexer & Lexer::operator>>(bool & s)
935 // quotes a string, e.g. for use in preferences files or as an argument
936 // of the "log" dialog
937 string const Lexer::quoteString(string const & arg)
941 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");