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::put_almost_back(docstring s)
144 iparserdocstream & iparserdocstream::get(char_type &c)
161 Parser::Parser(idocstream & is)
162 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_iconv_("UTF-8"),
163 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
168 Parser::Parser(string const & s)
169 : lineno_(0), pos_(0),
170 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
171 encoding_iconv_("UTF-8"),
172 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
183 void Parser::deparse()
186 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
187 s += tokens_[i].asInput();
189 is_.put_almost_back(from_utf8(s));
190 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
191 // make sure that next token is read
196 bool Parser::setEncoding(std::string const & e, int const & p)
198 // We may (and need to) use unsafe encodings here: Since the text is
199 // converted to unicode while reading from is_, we never see text in
200 // the original encoding of the parser, but operate on utf8 strings
201 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
202 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
204 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
207 return setEncoding(enc->iconvName());
211 void Parser::catInit()
213 if (curr_cat_ == theCatcodesType_)
215 curr_cat_ = theCatcodesType_;
217 fill(theCatcode_, theCatcode_ + 256, catOther);
218 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
219 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
221 theCatcode_[int('@')] = catLetter;
223 if (theCatcodesType_ == NORMAL_CATCODES) {
224 theCatcode_[int('\\')] = catEscape;
225 theCatcode_[int('{')] = catBegin;
226 theCatcode_[int('}')] = catEnd;
227 theCatcode_[int('$')] = catMath;
228 theCatcode_[int('&')] = catAlign;
229 theCatcode_[int('\n')] = catNewline;
230 theCatcode_[int('#')] = catParameter;
231 theCatcode_[int('^')] = catSuper;
232 theCatcode_[int('_')] = catSub;
233 theCatcode_[0x7f] = catIgnore;
234 theCatcode_[int(' ')] = catSpace;
235 theCatcode_[int('\t')] = catSpace;
236 theCatcode_[int('\r')] = catNewline;
237 theCatcode_[int('~')] = catActive;
238 theCatcode_[int('%')] = catComment;
242 CatCode Parser::catcode(char_type c) const
245 return theCatcode_[(unsigned char)c];
250 void Parser::setCatcode(char c, CatCode cat)
252 theCatcode_[(unsigned char)c] = cat;
257 void Parser::setCatcodes(cat_type t)
259 theCatcodesType_ = t;
264 bool Parser::setEncoding(std::string const & e)
266 //cerr << "setting encoding to " << e << std::endl;
268 return is_.setEncoding(e);
272 void Parser::push_back(Token const & t)
274 tokens_.push_back(t);
278 // We return a copy here because the tokens_ vector may get reallocated
279 Token const Parser::prev_token() const
281 static const Token dummy;
282 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
286 // We return a copy here because the tokens_ vector may get reallocated
287 Token const Parser::curr_token() const
289 static const Token dummy;
290 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
294 // We return a copy here because the tokens_ vector may get reallocated
295 Token const Parser::next_token()
297 static const Token dummy;
300 if (pos_ >= tokens_.size())
302 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
306 // We return a copy here because the tokens_ vector may get reallocated
307 Token const Parser::next_next_token()
309 static const Token dummy;
312 // If tokenize_one() has not been called after the last get_token() we
313 // need to tokenize two more tokens.
314 if (pos_ >= tokens_.size()) {
316 if (pos_ + 1 >= tokens_.size())
319 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
323 // We return a copy here because the tokens_ vector may get reallocated
324 Token const Parser::get_token()
326 static const Token dummy;
329 if (pos_ >= tokens_.size()) {
331 if (pos_ >= tokens_.size())
334 // cerr << "looking at token " << tokens_[pos_]
335 // << " pos: " << pos_ << '\n';
336 return tokens_[pos_++];
340 bool Parser::isParagraph()
342 // A new paragraph in TeX ist started
343 // - either by a newline, following any amount of whitespace
344 // characters (including zero), and another newline
345 // - or the token \par
346 if (curr_token().cat() == catNewline &&
347 (curr_token().cs().size() > 1 ||
348 (next_token().cat() == catSpace &&
349 next_next_token().cat() == catNewline)))
351 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
357 bool Parser::skip_spaces(bool skip_comments)
359 // We just silently return if we have no more tokens.
360 // skip_spaces() should be callable at any time,
361 // the caller must check p::good() anyway.
362 bool skipped = false;
369 if (curr_token().cat() == catSpace ||
370 curr_token().cat() == catNewline) {
374 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
376 if (skip_comments && curr_token().cat() == catComment) {
377 // If positions_ is not empty we are doing some kind
379 if (!positions_.empty())
380 cerr << " Ignoring comment: "
381 << curr_token().asInput();
391 void Parser::unskip_spaces(bool skip_comments)
394 if ( curr_token().cat() == catSpace ||
395 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
397 else if (skip_comments && curr_token().cat() == catComment) {
398 // TODO: Get rid of this
399 // If positions_ is not empty we are doing some kind
401 if (!positions_.empty())
402 cerr << "Unignoring comment: "
403 << curr_token().asInput();
412 void Parser::putback()
418 void Parser::pushPosition()
420 positions_.push_back(pos_);
424 void Parser::popPosition()
426 pos_ = positions_.back();
427 positions_.pop_back();
433 if (pos_ < tokens_.size())
437 return is_.peek() != idocstream::traits_type::eof();
441 bool Parser::hasOpt()
443 // An optional argument can occur in any of the following forms:
451 // remember current position
452 unsigned int oldpos = pos_;
453 // skip spaces and comments
460 if (curr_token().cat() == catSpace ||
461 curr_token().cat() == catNewline ||
462 curr_token().cat() == catComment)
467 bool const retval = (next_token().asInput() == "[");
473 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
477 // This is needed if a partial file ends with a command without arguments,
480 return make_pair(false, string());
483 Token t = get_token();
485 if (t.cat() == catComment || t.cat() == catEscape ||
486 t.character() != left) {
488 return make_pair(false, string());
493 if (t.cat() == catComment) {
495 cerr << "Ignoring comment: " << t.asInput();
498 if (allow_escaping) {
499 if (t.cat() != catEscape && t.character() == right)
502 if (t.character() == right) {
503 if (t.cat() == catEscape)
508 result += t.asInput();
511 return make_pair(true, result);
515 string Parser::getArg(char left, char right, bool allow_escaping)
517 return getFullArg(left, right, allow_escaping).second;
521 string Parser::getFullOpt(bool keepws)
523 Arg arg = getFullArg('[', ']');
525 return '[' + arg.second + ']';
532 string Parser::getOpt(bool keepws)
534 string const res = getArg('[', ']');
540 return '[' + res + ']';
544 string Parser::getFullParentheseArg()
546 Arg arg = getFullArg('(', ')');
548 return '(' + arg.second + ')';
553 string const Parser::ertEnvironment(string const & name)
559 for (Token t = get_token(); good(); t = get_token()) {
560 if (t.cat() == catBegin) {
562 os << '{' << verbatim_item() << '}';
563 } else if (t.asInput() == "\\begin") {
564 string const env = getArg('{', '}');
565 os << "\\begin{" << env << '}'
566 << ertEnvironment(env)
567 << "\\end{" << env << '}';
568 } else if (t.asInput() == "\\end") {
569 string const end = getArg('{', '}');
571 cerr << "\\end{" << end
572 << "} does not match \\begin{" << name
578 cerr << "unexpected end of input" << endl;
583 string const Parser::plainEnvironment(string const & name)
589 for (Token t = get_token(); good(); t = get_token()) {
590 if (t.asInput() == "\\end") {
591 string const end = getArg('{', '}');
595 os << "\\end{" << end << '}';
599 cerr << "unexpected end of input" << endl;
604 string const Parser::plainCommand(char left, char right, string const & name)
608 // check if first token is really the start character
609 Token tok = get_token();
610 if (tok.character() != left) {
611 cerr << "first character does not match start character of command \\" << name << endl;
615 for (Token t = get_token(); good(); t = get_token()) {
616 if (t.character() == right) {
621 cerr << "unexpected end of input" << endl;
626 string const Parser::verbatimStuff(string const & end_string)
632 size_t match_index = 0;
633 setCatcodes(VERBATIM_CATCODES);
634 for (Token t = get_token(); good(); t = get_token()) {
635 // FIXME t.asInput() might be longer than we need ?
636 if (t.asInput() == end_string.substr(match_index,
637 t.asInput().length())) {
638 match_index += t.asInput().length();
639 if (match_index >= end_string.length())
641 } else if (match_index) {
642 oss << end_string.substr(0, match_index) << t.asInput();
647 setCatcodes(NORMAL_CATCODES);
649 cerr << "unexpected end of input" << endl;
654 string const Parser::verbatimEnvironment(string const & name)
656 string s = verbatimStuff("\\end{" + name + "}");
657 // ignore one newline at beginning or end of string
658 if (prefixIs(s, "\n"))
660 if (suffixIs(s, "\n"))
661 s.erase(s.length() - 1,1);
666 string Parser::verbatimOption()
669 if (next_token().character() == '[') {
670 Token t = get_token();
671 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
672 if (t.cat() == catBegin) {
674 res += '{' + verbatim_item() + '}';
683 string Parser::verbatim_item()
688 if (next_token().cat() == catBegin) {
689 Token t = get_token(); // skip brace
691 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
692 if (t.cat() == catBegin) {
694 res += '{' + verbatim_item() + '}';
701 return get_token().asInput();
705 void Parser::tokenize_one()
712 switch (catcode(c)) {
715 while (is_.get(c) && catcode(c) == catSpace)
717 if (catcode(c) != catSpace)
719 push_back(Token(s, catSpace));
725 docstring s(1, getNewline(is_, c));
726 while (is_.get(c) && catcode(c) == catNewline) {
728 s += getNewline(is_, c);
730 if (catcode(c) != catNewline)
732 push_back(Token(s, catNewline));
737 // We don't treat "%\n" combinations here specially because
738 // we want to preserve them in the preamble
740 while (is_.get(c) && catcode(c) != catNewline)
742 // handle possible DOS line ending
743 if (catcode(c) == catNewline)
744 c = getNewline(is_, c);
745 // Note: The '%' at the beginning and the '\n' at the end
746 // of the comment are not stored.
748 push_back(Token(s, catComment));
755 error("unexpected end of input");
758 if (catcode(c) == catLetter) {
760 while (is_.get(c) && catcode(c) == catLetter)
762 if (catcode(c) != catLetter)
765 push_back(Token(s, catEscape));
771 cerr << "ignoring a char: " << c << "\n";
776 push_back(Token(docstring(1, c), catcode(c)));
778 //cerr << tokens_.back();
782 void Parser::dump() const
784 cerr << "\nTokens: ";
785 for (unsigned i = 0; i < tokens_.size(); ++i) {
790 cerr << " pos: " << pos_ << "\n";
794 void Parser::error(string const & msg)
796 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;