3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
15 #include "support/foreach.h"
16 #include "support/lstrings.h"
17 #include "support/textutils.h"
22 using namespace lyx::support;
29 * Translate a line ending to '\n'.
30 * \p c must have catcode catNewline, and it must be the last character read
33 char_type getNewline(iparserdocstream & is, char_type c)
35 // we have to handle 3 different line endings:
42 if (is.get(wc) && wc != '\n') {
58 ostream & operator<<(ostream & os, Token const & t)
60 if (t.cat() == catComment)
61 os << '%' << t.cs() << '\n';
62 else if (t.cat() == catSpace)
64 else if (t.cat() == catEscape)
65 os << '\\' << t.cs() << ' ';
66 else if (t.cat() == catLetter)
68 else if (t.cat() == catNewline)
69 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
71 os << '[' << t.cs() << ',' << t.cat() << ']';
76 string Token::asInput() const
78 if (cat_ == catComment)
79 return '%' + cs_ + '\n';
80 if (cat_ == catEscape)
86 bool Token::isAlnumASCII() const
88 return cat_ == catLetter ||
89 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
94 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
97 os << "t: " << t << " flags: " << flags;
98 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
99 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
100 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
101 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
102 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
103 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
104 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
105 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
106 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
107 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
108 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
109 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
110 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
111 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
121 bool iparserdocstream::setEncoding(std::string const & e)
123 is_ << lyx::setEncoding(e);
126 cerr << "Setting encoding " << e << " too late. The encoding of `"
127 << to_utf8(s_) << "´ is wrong." << std::endl;
132 void iparserdocstream::putback(char_type c)
138 void iparserdocstream::putback(docstring s)
144 iparserdocstream & iparserdocstream::get(char_type &c)
149 //cerr << "unparsed: " << to_utf8(s_) <<endl;
162 Parser::Parser(idocstream & is)
163 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_iconv_("UTF-8"),
164 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
169 Parser::Parser(string const & s)
170 : lineno_(0), pos_(0),
171 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
172 encoding_iconv_("UTF-8"),
173 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
184 void Parser::deparse()
187 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
188 s += tokens_[i].asInput();
190 is_.putback(from_utf8(s));
191 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
192 // make sure that next token is read
197 bool Parser::setEncoding(std::string const & e, int const & p)
199 // We may (and need to) use unsafe encodings here: Since the text is
200 // converted to unicode while reading from is_, we never see text in
201 // the original encoding of the parser, but operate on utf8 strings
202 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
203 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
205 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
208 return setEncoding(enc->iconvName());
212 void Parser::catInit()
214 if (curr_cat_ == theCatcodesType_)
216 curr_cat_ = theCatcodesType_;
218 fill(theCatcode_, theCatcode_ + 256, catOther);
219 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
220 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
222 theCatcode_[int('@')] = catLetter;
224 if (theCatcodesType_ == NORMAL_CATCODES) {
225 theCatcode_[int('\\')] = catEscape;
226 theCatcode_[int('{')] = catBegin;
227 theCatcode_[int('}')] = catEnd;
228 theCatcode_[int('$')] = catMath;
229 theCatcode_[int('&')] = catAlign;
230 theCatcode_[int('\n')] = catNewline;
231 theCatcode_[int('#')] = catParameter;
232 theCatcode_[int('^')] = catSuper;
233 theCatcode_[int('_')] = catSub;
234 theCatcode_[0x7f] = catIgnore;
235 theCatcode_[int(' ')] = catSpace;
236 theCatcode_[int('\t')] = catSpace;
237 theCatcode_[int('\r')] = catNewline;
238 theCatcode_[int('~')] = catActive;
239 theCatcode_[int('%')] = catComment;
243 CatCode Parser::catcode(char_type c) const
246 return theCatcode_[(unsigned char)c];
251 void Parser::setCatcode(char c, CatCode cat)
253 theCatcode_[(unsigned char)c] = cat;
258 void Parser::setCatcodes(cat_type t)
260 theCatcodesType_ = t;
265 bool Parser::setEncoding(std::string const & e)
267 //cerr << "setting encoding to " << e << std::endl;
269 return is_.setEncoding(e);
273 void Parser::push_back(Token const & t)
275 tokens_.push_back(t);
279 // We return a copy here because the tokens_ vector may get reallocated
280 Token const Parser::prev_token() const
282 static const Token dummy;
283 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
287 // We return a copy here because the tokens_ vector may get reallocated
288 Token const Parser::curr_token() const
290 static const Token dummy;
291 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
295 // We return a copy here because the tokens_ vector may get reallocated
296 Token const Parser::next_token()
298 static const Token dummy;
301 if (pos_ >= tokens_.size())
303 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
307 // We return a copy here because the tokens_ vector may get reallocated
308 Token const Parser::next_next_token()
310 static const Token dummy;
313 // If tokenize_one() has not been called after the last get_token() we
314 // need to tokenize two more tokens.
315 if (pos_ >= tokens_.size()) {
317 if (pos_ + 1 >= tokens_.size())
320 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
324 // We return a copy here because the tokens_ vector may get reallocated
325 Token const Parser::get_token()
327 static const Token dummy;
330 if (pos_ >= tokens_.size()) {
332 if (pos_ >= tokens_.size())
335 // cerr << "looking at token " << tokens_[pos_]
336 // << " pos: " << pos_ << '\n';
337 return tokens_[pos_++];
341 bool Parser::isParagraph()
343 // A new paragraph in TeX ist started
344 // - either by a newline, following any amount of whitespace
345 // characters (including zero), and another newline
346 // - or the token \par
347 if (curr_token().cat() == catNewline &&
348 (curr_token().cs().size() > 1 ||
349 (next_token().cat() == catSpace &&
350 next_next_token().cat() == catNewline)))
352 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
358 bool Parser::skip_spaces(bool skip_comments)
360 // We just silently return if we have no more tokens.
361 // skip_spaces() should be callable at any time,
362 // the caller must check p::good() anyway.
363 bool skipped = false;
370 if (curr_token().cat() == catSpace ||
371 curr_token().cat() == catNewline) {
375 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
377 if (skip_comments && curr_token().cat() == catComment) {
378 // If positions_ is not empty we are doing some kind
380 if (!positions_.empty())
381 cerr << " Ignoring comment: "
382 << curr_token().asInput();
392 void Parser::unskip_spaces(bool skip_comments)
395 if ( curr_token().cat() == catSpace ||
396 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
398 else if (skip_comments && curr_token().cat() == catComment) {
399 // TODO: Get rid of this
400 // If positions_ is not empty we are doing some kind
402 if (!positions_.empty())
403 cerr << "Unignoring comment: "
404 << curr_token().asInput();
413 void Parser::putback()
419 void Parser::pushPosition()
421 positions_.push_back(pos_);
425 void Parser::popPosition()
427 pos_ = positions_.back();
428 positions_.pop_back();
433 void Parser::dropPosition()
435 positions_.pop_back();
441 if (pos_ < tokens_.size())
445 return is_.peek() != idocstream::traits_type::eof();
449 bool Parser::hasOpt()
451 // An optional argument can occur in any of the following forms:
459 // remember current position
460 unsigned int oldpos = pos_;
461 // skip spaces and comments
468 if (curr_token().cat() == catSpace ||
469 curr_token().cat() == catNewline ||
470 curr_token().cat() == catComment)
475 bool const retval = (next_token().asInput() == "[");
481 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
485 // This is needed if a partial file ends with a command without arguments,
488 return make_pair(false, string());
491 Token t = get_token();
493 if (t.cat() == catComment || t.cat() == catEscape ||
494 t.character() != left) {
496 return make_pair(false, string());
501 if (t.cat() == catComment) {
503 cerr << "Ignoring comment: " << t.asInput();
506 if (allow_escaping) {
507 if (t.cat() != catEscape && t.character() == right)
510 if (t.character() == right) {
511 if (t.cat() == catEscape)
516 result += t.asInput();
519 return make_pair(true, result);
523 string Parser::getArg(char left, char right, bool allow_escaping)
525 return getFullArg(left, right, allow_escaping).second;
529 string Parser::getFullOpt(bool keepws)
531 Arg arg = getFullArg('[', ']');
533 return '[' + arg.second + ']';
540 string Parser::getOpt(bool keepws)
542 string const res = getArg('[', ']');
548 return '[' + res + ']';
552 string Parser::getFullParentheseArg()
554 Arg arg = getFullArg('(', ')');
556 return '(' + arg.second + ')';
561 string const Parser::ertEnvironment(string const & name)
567 for (Token t = get_token(); good(); t = get_token()) {
568 if (t.cat() == catBegin) {
570 os << '{' << verbatim_item() << '}';
571 } else if (t.asInput() == "\\begin") {
572 string const env = getArg('{', '}');
573 os << "\\begin{" << env << '}'
574 << ertEnvironment(env)
575 << "\\end{" << env << '}';
576 } else if (t.asInput() == "\\end") {
577 string const end = getArg('{', '}');
579 cerr << "\\end{" << end
580 << "} does not match \\begin{" << name
586 cerr << "unexpected end of input" << endl;
591 string const Parser::plainEnvironment(string const & name)
597 for (Token t = get_token(); good(); t = get_token()) {
598 if (t.asInput() == "\\end") {
599 string const end = getArg('{', '}');
603 os << "\\end{" << end << '}';
607 cerr << "unexpected end of input" << endl;
612 string const Parser::plainCommand(char left, char right, string const & name)
616 // check if first token is really the start character
617 Token tok = get_token();
618 if (tok.character() != left) {
619 cerr << "first character does not match start character of command \\" << name << endl;
623 for (Token t = get_token(); good(); t = get_token()) {
624 if (t.character() == right) {
629 cerr << "unexpected end of input" << endl;
634 string const Parser::verbatimStuff(string const & end_string)
640 size_t match_index = 0;
641 setCatcodes(VERBATIM_CATCODES);
642 for (Token t = get_token(); good(); t = get_token()) {
643 // FIXME t.asInput() might be longer than we need ?
644 if (t.asInput() == end_string.substr(match_index,
645 t.asInput().length())) {
646 match_index += t.asInput().length();
647 if (match_index >= end_string.length())
649 } else if (match_index) {
650 oss << end_string.substr(0, match_index) << t.asInput();
655 setCatcodes(NORMAL_CATCODES);
657 cerr << "unexpected end of input" << endl;
662 string const Parser::verbatimEnvironment(string const & name)
664 string s = verbatimStuff("\\end{" + name + "}");
665 // ignore one newline at beginning or end of string
666 if (prefixIs(s, "\n"))
668 if (suffixIs(s, "\n"))
669 s.erase(s.length() - 1,1);
674 string Parser::verbatimOption()
677 if (next_token().character() == '[') {
678 Token t = get_token();
679 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
680 if (t.cat() == catBegin) {
682 res += '{' + verbatim_item() + '}';
691 string Parser::verbatim_item()
696 if (next_token().cat() == catBegin) {
697 Token t = get_token(); // skip brace
699 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
700 if (t.cat() == catBegin) {
702 res += '{' + verbatim_item() + '}';
709 return get_token().asInput();
713 void Parser::tokenize_one()
720 switch (catcode(c)) {
723 while (is_.get(c) && catcode(c) == catSpace)
725 if (catcode(c) != catSpace)
727 push_back(Token(s, catSpace));
733 docstring s(1, getNewline(is_, c));
734 while (is_.get(c) && catcode(c) == catNewline) {
736 s += getNewline(is_, c);
738 if (catcode(c) != catNewline)
740 push_back(Token(s, catNewline));
745 // We don't treat "%\n" combinations here specially because
746 // we want to preserve them in the preamble
748 while (is_.get(c) && catcode(c) != catNewline)
750 // handle possible DOS line ending
751 if (catcode(c) == catNewline)
752 c = getNewline(is_, c);
753 // Note: The '%' at the beginning and the '\n' at the end
754 // of the comment are not stored.
756 push_back(Token(s, catComment));
763 error("unexpected end of input");
766 if (catcode(c) == catLetter) {
768 while (is_.get(c) && catcode(c) == catLetter)
770 if (catcode(c) != catLetter)
773 push_back(Token(s, catEscape));
779 cerr << "ignoring a char: " << c << "\n";
784 push_back(Token(docstring(1, c), catcode(c)));
786 //cerr << tokens_.back();
790 void Parser::dump() const
792 cerr << "\nTokens: ";
793 for (unsigned i = 0; i < tokens_.size(); ++i) {
798 cerr << " pos: " << pos_ << "\n";
802 void Parser::error(string const & msg)
804 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;