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>
40 using support::compare_ascii_no_case;
41 using support::FileName;
42 using support::isStrDbl;
43 using support::isStrInt;
45 using support::makeDisplayPath;
46 using support::prefixIs;
52 //////////////////////////////////////////////////////////////////////
56 //////////////////////////////////////////////////////////////////////
60 class Lexer::Pimpl : boost::noncopyable {
63 Pimpl(keyword_item * tab, int num);
65 std::string const getString() const;
67 docstring const getDocString() const;
69 void printError(std::string const & message) const;
71 void printTable(std::ostream & os);
73 void pushTable(keyword_item * tab, int num);
77 bool setFile(support::FileName const & filename);
79 void setStream(std::istream & i);
81 void setCommentChar(char c);
83 bool next(bool esc = false);
85 int search_kw(char const * const tag) const;
92 /// test if there is a pushed token or the stream is ok
93 bool inputAvailable();
95 void pushToken(std::string const &);
96 /// fb_ is only used to open files, the stream is accessed through is.
99 /// gz_ is only used to open files, the stream is accessed through is.
102 /// the stream that we use.
107 keyword_item * table;
128 : table_elem(0), table_siz(0) {}
130 pushed_table(keyword_item * ki, int siz)
131 : table_elem(ki), table_siz(siz) {}
133 keyword_item * table_elem;
138 std::stack<pushed_table> pushed;
146 : public std::binary_function<keyword_item, keyword_item, bool> {
148 // used by lower_bound, sort and sorted
149 bool operator()(keyword_item const & a, keyword_item const & b) const
151 // we use the ascii version, because in turkish, 'i'
152 // is not the lowercase version of 'I', and thus
153 // turkish locale breaks parsing of tags.
154 return compare_ascii_no_case(a.tag, b.tag) < 0;
158 } // end of anon namespace
161 Lexer::Pimpl::Pimpl(keyword_item * tab, int num)
162 : is(&fb_), table(tab), no_items(num),
163 status(0), lineno(0), commentChar('#')
169 string const Lexer::Pimpl::getString() const
175 docstring const Lexer::Pimpl::getDocString() const
177 return from_utf8(buff);
181 void Lexer::Pimpl::printError(string const & message) const
183 string const tmpmsg = subst(message, "$$Token", getString());
184 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
185 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << endl;
189 void Lexer::Pimpl::printTable(ostream & os)
191 os << "\nNumber of tags: " << no_items << endl;
192 for (int i= 0; i < no_items; ++i)
194 << "]: tag: `" << table[i].tag
195 << "' code:" << table[i].code << '\n';
200 void Lexer::Pimpl::verifyTable()
202 // Check if the table is sorted and if not, sort it.
204 && !lyx::sorted(table, table + no_items, compare_tags())) {
205 lyxerr << "The table passed to Lexer is not sorted!\n"
206 << "Tell the developers to fix it!" << endl;
207 // We sort it anyway to avoid problems.
208 lyxerr << "\nUnsorted:" << endl;
211 sort(table, table + no_items, compare_tags());
212 lyxerr << "\nSorted:" << endl;
218 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
220 pushed_table tmppu(table, no_items);
230 void Lexer::Pimpl::popTable()
232 if (pushed.empty()) {
233 lyxerr << "Lexer error: nothing to pop!" << endl;
237 pushed_table tmp = pushed.top();
239 table = tmp.table_elem;
240 no_items = tmp.table_siz;
244 bool Lexer::Pimpl::setFile(FileName const & filename)
246 // Check the format of the file.
247 string const format = filename.guessFormatFromContents();
249 if (format == "gzip" || format == "zip" || format == "compress") {
250 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
251 // The check only outputs a debug message, because it triggers
252 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
253 // a fresh new filebuf. (JMarc)
254 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
255 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
256 "file or stream already set.");
257 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
259 name = filename.absFilename();
261 return gz_.is_open() && is.good();
263 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
265 // The check only outputs a debug message, because it triggers
266 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
267 // a fresh new filebuf. (JMarc)
268 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
269 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
270 "file or stream already set.");
272 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
274 name = filename.absFilename();
276 return fb_.is_open() && is.good();
281 void Lexer::Pimpl::setStream(istream & i)
283 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
284 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
285 "file or stream already set.");
292 void Lexer::Pimpl::setCommentChar(char c)
298 bool Lexer::Pimpl::next(bool esc /* = false */)
300 if (!pushTok.empty()) {
301 // There can have been a whole line pushed so
302 // we extract the first word and leaves the rest
304 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
306 pushTok = split(pushTok, buff, ' ');
315 unsigned char c = 0; // getc() returns an int
318 while (is && !status) {
321 if (c == commentChar) {
322 // Read rest of line (fast :-)
324 // That is not fast... (Lgb)
328 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
330 // unfortunately ignore is buggy (Lgb)
331 is.ignore(100, '\n');
345 } while (c != '\"' && c != '\n' && is);
348 printError("Missing quote");
353 buff.resize(buff.size()-1);
359 continue; /* Skip ','s */
361 // using relational operators with chars other
362 // than == and != is not safe. And if it is done
363 // the type _have_ to be unsigned. It usually a
364 // lot better to use the functions from cctype
372 } while (c > ' ' && c != ',' && is);
377 if (c == '\r' && is) {
378 // The Windows support has lead to the
379 // possibility of "\r\n" at the end of
380 // a line. This will stop LyX choking
381 // when it expected to find a '\n'
393 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
397 unsigned char c = 0; // getc() returns an int
401 while (is && !status) {
409 if (c == commentChar) {
410 // Read rest of line (fast :-)
412 // That is still not fast... (Lgb)
416 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
418 // but ignore is also still buggy (Lgb)
419 // This is fast (Lgb)
420 is.ignore(100, '\n');
430 bool escaped = false;
435 if (c == '\r') continue;
437 // escape the next char
440 if (c == '\"' || c == '\\')
443 buff.push_back('\\');
447 if (!escaped && c == '\"')
449 } while (c != '\n' && is);
452 printError("Missing quote");
457 buff.resize(buff.size() -1);
467 // escape the next char
475 } while (c > ' ' && c != ',' && is);
487 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
494 int Lexer::Pimpl::search_kw(char const * const tag) const
496 keyword_item search_tag = { tag, 0 };
498 lower_bound(table, table + no_items,
499 search_tag, compare_tags());
500 // use the compare_ascii_no_case instead of compare_no_case,
501 // because in turkish, 'i' is not the lowercase version of 'I',
502 // and thus turkish locale breaks parsing of tags.
503 if (res != table + no_items
504 && !compare_ascii_no_case(res->tag, tag))
510 int Lexer::Pimpl::lex()
512 //NOTE: possible bug.
513 if (next() && status == LEX_TOKEN)
514 return search_kw(getString().c_str());
519 bool Lexer::Pimpl::eatLine()
523 unsigned char c = '\0';
525 while (is && c != '\n') {
528 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
535 buff.resize(buff.size() - 1);
538 } else if (buff.length() > 0) { // last line
547 bool Lexer::Pimpl::nextToken()
549 if (!pushTok.empty()) {
550 // There can have been a whole line pushed so
551 // we extract the first word and leaves the rest
553 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
555 pushTok = split(pushTok, buff, ' ');
565 while (is && !status) {
570 if (c >= ' ' && is) {
573 if (c == '\\') { // first char == '\\'
578 } while (c > ' ' && c != '\\' && is);
584 } while (c >= ' ' && c != '\\' && is);
587 if (c == '\\') is.putback(c); // put it back
598 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
604 bool Lexer::Pimpl::inputAvailable()
610 void Lexer::Pimpl::pushToken(string const & pt)
618 //////////////////////////////////////////////////////////////////////
622 //////////////////////////////////////////////////////////////////////
624 Lexer::Lexer(keyword_item * tab, int num)
625 : pimpl_(new Pimpl(tab, num))
635 bool Lexer::isOK() const
637 return pimpl_->inputAvailable();
641 void Lexer::setLineNo(int l)
647 int Lexer::getLineNo() const
649 return pimpl_->lineno;
653 istream & Lexer::getStream()
659 void Lexer::pushTable(keyword_item * tab, int num)
661 pimpl_->pushTable(tab, num);
665 void Lexer::popTable()
671 void Lexer::printTable(ostream & os)
673 pimpl_->printTable(os);
677 void Lexer::printError(string const & message) const
679 pimpl_->printError(message);
683 bool Lexer::setFile(support::FileName const & filename)
685 return pimpl_->setFile(filename);
689 void Lexer::setStream(istream & i)
691 pimpl_->setStream(i);
695 void Lexer::setCommentChar(char c)
697 pimpl_->setCommentChar(c);
702 return pimpl_->lex();
706 int Lexer::getInteger() const
708 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
710 pimpl_->printError("integer token missing");
714 if (isStrInt(pimpl_->getString()))
715 return convert<int>(pimpl_->getString());
718 pimpl_->printError("Bad integer `$$Token'");
723 double Lexer::getFloat() const
725 // replace comma with dot in case the file was written with
726 // the wrong locale (should be rare, but is easy enough to
728 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
730 pimpl_->printError("float token missing");
734 string const str = subst(pimpl_->getString(), ",", ".");
736 return convert<double>(str);
739 pimpl_->printError("Bad float `$$Token'");
744 string const Lexer::getString() const
746 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
749 return pimpl_->getString();
755 docstring const Lexer::getDocString() const
757 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
760 return pimpl_->getDocString();
766 // I would prefer to give a tag number instead of an explicit token
767 // here, but it is not possible because Buffer::readDocument uses
768 // explicit tokens (JMarc)
769 string const Lexer::getLongString(string const & endtoken)
772 bool firstline = true;
774 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
776 // blank line in the file being read
779 string const token = trim(getString(), " \t");
781 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
783 // We do a case independent comparison, like search_kw does.
784 if (compare_ascii_no_case(token, endtoken) == 0)
787 string tmpstr = getString();
789 string::size_type i(tmpstr.find_first_not_of(' '));
790 if (i != string::npos)
791 prefix = tmpstr.substr(0, i);
793 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
796 // further lines in long strings may have the same
797 // whitespace prefix as the first line. Remove it.
798 if (prefix.length() && prefixIs(tmpstr, prefix)) {
799 tmpstr.erase(0, prefix.length() - 1);
802 str += ltrim(tmpstr, "\t") + '\n';
806 printError("Long string not ended by `" + endtoken + '\'');
813 bool Lexer::getBool() const
815 if (pimpl_->getString() == "true") {
818 } else if (pimpl_->getString() != "false") {
819 pimpl_->printError("Bad boolean `$$Token'. "
820 "Use \"false\" or \"true\"");
828 bool Lexer::eatLine()
830 return pimpl_->eatLine();
834 bool Lexer::next(bool esc)
836 return pimpl_->next(esc);
840 bool Lexer::nextToken()
842 return pimpl_->nextToken();
846 void Lexer::pushToken(string const & pt)
848 pimpl_->pushToken(pt);
852 Lexer::operator void const *() const
854 // This behaviour is NOT the same as the std::streams which would
855 // use fail() here. However, our implementation of getString() et al.
856 // can cause the eof() and fail() bits to be set, even though we
857 // haven't tried to read 'em.
858 return lastReadOk_? this : 0;
862 bool Lexer::operator!() const
868 Lexer & Lexer::operator>>(std::string & s)
880 Lexer & Lexer::operator>>(docstring & s)
892 Lexer & Lexer::operator>>(double & s)
904 Lexer & Lexer::operator>>(int & s)
916 Lexer & Lexer::operator>>(unsigned int & s)
928 Lexer & Lexer::operator>>(bool & s)
940 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
941 string const Lexer::quoteString(string const & arg)
943 std::ostringstream os;
944 os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';