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 void iparserdocstream::setEncoding(std::string const & e)
123 is_ << lyx::setEncoding(e);
127 void iparserdocstream::putback(char_type c)
133 void iparserdocstream::putback(docstring s)
139 iparserdocstream & iparserdocstream::get(char_type &c)
144 //cerr << "unparsed: " << to_utf8(s_) <<endl;
157 Parser::Parser(idocstream & is)
158 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_iconv_("UTF-8"),
159 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
164 Parser::Parser(string const & s)
165 : lineno_(0), pos_(0),
166 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
167 encoding_iconv_("UTF-8"),
168 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
179 void Parser::deparse()
182 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
183 s += tokens_[i].asInput();
185 is_.putback(from_utf8(s));
186 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
187 // make sure that next token is read
192 bool Parser::setEncoding(std::string const & e, int const & p)
194 // We may (and need to) use unsafe encodings here: Since the text is
195 // converted to unicode while reading from is_, we never see text in
196 // the original encoding of the parser, but operate on utf8 strings
197 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
198 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
200 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
203 return setEncoding(enc->iconvName());
207 void Parser::catInit()
209 if (curr_cat_ == theCatcodesType_)
211 curr_cat_ = theCatcodesType_;
213 fill(theCatcode_, theCatcode_ + 256, catOther);
214 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
215 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
217 theCatcode_[int('@')] = catLetter;
219 if (theCatcodesType_ == NORMAL_CATCODES) {
220 theCatcode_[int('\\')] = catEscape;
221 theCatcode_[int('{')] = catBegin;
222 theCatcode_[int('}')] = catEnd;
223 theCatcode_[int('$')] = catMath;
224 theCatcode_[int('&')] = catAlign;
225 theCatcode_[int('\n')] = catNewline;
226 theCatcode_[int('#')] = catParameter;
227 theCatcode_[int('^')] = catSuper;
228 theCatcode_[int('_')] = catSub;
229 theCatcode_[0x7f] = catIgnore;
230 theCatcode_[int(' ')] = catSpace;
231 theCatcode_[int('\t')] = catSpace;
232 theCatcode_[int('\r')] = catNewline;
233 theCatcode_[int('~')] = catActive;
234 theCatcode_[int('%')] = catComment;
238 CatCode Parser::catcode(char_type c) const
241 return theCatcode_[(unsigned char)c];
246 void Parser::setCatcode(char c, CatCode cat)
248 theCatcode_[(unsigned char)c] = cat;
253 void Parser::setCatcodes(cat_type t)
255 theCatcodesType_ = t;
260 bool Parser::setEncoding(std::string const & e)
262 //cerr << "setting encoding to " << e << std::endl;
269 void Parser::push_back(Token const & t)
271 tokens_.push_back(t);
275 // We return a copy here because the tokens_ vector may get reallocated
276 Token const Parser::prev_token() const
278 static const Token dummy;
279 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
283 // We return a copy here because the tokens_ vector may get reallocated
284 Token const Parser::curr_token() const
286 static const Token dummy;
287 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
291 // We return a copy here because the tokens_ vector may get reallocated
292 Token const Parser::next_token()
294 static const Token dummy;
297 if (pos_ >= tokens_.size())
299 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
303 // We return a copy here because the tokens_ vector may get reallocated
304 Token const Parser::next_next_token()
306 static const Token dummy;
309 // If tokenize_one() has not been called after the last get_token() we
310 // need to tokenize two more tokens.
311 if (pos_ >= tokens_.size()) {
313 if (pos_ + 1 >= tokens_.size())
316 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
320 // We return a copy here because the tokens_ vector may get reallocated
321 Token const Parser::get_token()
323 static const Token dummy;
326 if (pos_ >= tokens_.size()) {
328 if (pos_ >= tokens_.size())
331 // cerr << "looking at token " << tokens_[pos_]
332 // << " pos: " << pos_ << '\n';
333 return tokens_[pos_++];
337 bool Parser::isParagraph()
339 // A new paragraph in TeX ist started
340 // - either by a newline, following any amount of whitespace
341 // characters (including zero), and another newline
342 // - or the token \par
343 if (curr_token().cat() == catNewline &&
344 (curr_token().cs().size() > 1 ||
345 (next_token().cat() == catSpace &&
346 next_next_token().cat() == catNewline)))
348 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
354 bool Parser::skip_spaces(bool skip_comments)
356 // We just silently return if we have no more tokens.
357 // skip_spaces() should be callable at any time,
358 // the caller must check p::good() anyway.
359 bool skipped = false;
366 if (curr_token().cat() == catSpace ||
367 curr_token().cat() == catNewline) {
371 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
373 if (skip_comments && curr_token().cat() == catComment) {
374 // If positions_ is not empty we are doing some kind
376 if (!positions_.empty())
377 cerr << " Ignoring comment: "
378 << curr_token().asInput();
388 void Parser::unskip_spaces(bool skip_comments)
391 if ( curr_token().cat() == catSpace ||
392 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
394 else if (skip_comments && curr_token().cat() == catComment) {
395 // TODO: Get rid of this
396 // If positions_ is not empty we are doing some kind
398 if (!positions_.empty())
399 cerr << "Unignoring comment: "
400 << curr_token().asInput();
409 void Parser::putback()
415 void Parser::pushPosition()
417 positions_.push_back(pos_);
421 void Parser::popPosition()
423 pos_ = positions_.back();
424 positions_.pop_back();
429 void Parser::dropPosition()
431 positions_.pop_back();
437 if (pos_ < tokens_.size())
441 return is_.peek() != idocstream::traits_type::eof();
445 bool Parser::hasOpt()
447 // An optional argument can occur in any of the following forms:
455 // remember current position
456 unsigned int oldpos = pos_;
457 // skip spaces and comments
464 if (curr_token().cat() == catSpace ||
465 curr_token().cat() == catNewline ||
466 curr_token().cat() == catComment)
471 bool const retval = (next_token().asInput() == "[");
477 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
481 // This is needed if a partial file ends with a command without arguments,
484 return make_pair(false, string());
487 Token t = get_token();
489 if (t.cat() == catComment || t.cat() == catEscape ||
490 t.character() != left) {
492 return make_pair(false, string());
497 if (t.cat() == catComment) {
499 cerr << "Ignoring comment: " << t.asInput();
502 if (allow_escaping) {
503 if (t.cat() != catEscape && t.character() == right)
506 if (t.character() == right) {
507 if (t.cat() == catEscape)
512 result += t.asInput();
515 return make_pair(true, result);
519 string Parser::getArg(char left, char right, bool allow_escaping)
521 return getFullArg(left, right, allow_escaping).second;
525 string Parser::getFullOpt(bool keepws)
527 Arg arg = getFullArg('[', ']');
529 return '[' + arg.second + ']';
536 string Parser::getOpt(bool keepws)
538 string const res = getArg('[', ']');
544 return '[' + res + ']';
548 string Parser::getFullParentheseArg()
550 Arg arg = getFullArg('(', ')');
552 return '(' + arg.second + ')';
557 string const Parser::ertEnvironment(string const & name)
563 for (Token t = get_token(); good(); t = get_token()) {
564 if (t.cat() == catBegin) {
566 os << '{' << verbatim_item() << '}';
567 } else if (t.asInput() == "\\begin") {
568 string const env = getArg('{', '}');
569 os << "\\begin{" << env << '}'
570 << ertEnvironment(env)
571 << "\\end{" << env << '}';
572 } else if (t.asInput() == "\\end") {
573 string const end = getArg('{', '}');
575 cerr << "\\end{" << end
576 << "} does not match \\begin{" << name
582 cerr << "unexpected end of input" << endl;
587 string const Parser::plainEnvironment(string const & name)
593 for (Token t = get_token(); good(); t = get_token()) {
594 if (t.asInput() == "\\end") {
595 string const end = getArg('{', '}');
599 os << "\\end{" << end << '}';
603 cerr << "unexpected end of input" << endl;
608 string const Parser::plainCommand(char left, char right, string const & name)
612 // check if first token is really the start character
613 Token tok = get_token();
614 if (tok.character() != left) {
615 cerr << "first character does not match start character of command \\" << name << endl;
619 for (Token t = get_token(); good(); t = get_token()) {
620 if (t.character() == right) {
625 cerr << "unexpected end of input" << endl;
630 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
633 return Arg(false, string());
637 size_t match_index = 0;
638 setCatcodes(VERBATIM_CATCODES);
639 for (Token t = get_token(); good(); t = get_token()) {
640 // FIXME t.asInput() might be longer than we need ?
641 if (t.asInput() == end_string.substr(match_index,
642 t.asInput().length())) {
643 match_index += t.asInput().length();
644 if (match_index >= end_string.length())
647 if (!allow_linebreak && t.asInput() == "\n") {
648 cerr << "unexpected end of input" << endl;
650 setCatcodes(NORMAL_CATCODES);
651 return Arg(false, string());
654 oss << end_string.substr(0, match_index)
663 cerr << "unexpected end of input" << endl;
665 setCatcodes(NORMAL_CATCODES);
666 return Arg(false, string());
668 setCatcodes(NORMAL_CATCODES);
670 return Arg(true, oss.str());
674 string const Parser::verbatimEnvironment(string const & name)
676 //FIXME: do something if endstring is not found
677 string s = verbatimStuff("\\end{" + name + "}").second;
678 // ignore one newline at beginning or end of string
679 if (prefixIs(s, "\n"))
681 if (suffixIs(s, "\n"))
682 s.erase(s.length() - 1,1);
687 string Parser::verbatimOption()
690 if (next_token().character() == '[') {
691 Token t = get_token();
692 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
693 if (t.cat() == catBegin) {
695 res += '{' + verbatim_item() + '}';
704 string Parser::verbatim_item()
709 if (next_token().cat() == catBegin) {
710 Token t = get_token(); // skip brace
712 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
713 if (t.cat() == catBegin) {
715 res += '{' + verbatim_item() + '}';
722 return get_token().asInput();
726 void Parser::tokenize_one()
733 switch (catcode(c)) {
736 while (is_.get(c) && catcode(c) == catSpace)
738 if (catcode(c) != catSpace)
740 push_back(Token(s, catSpace));
746 docstring s(1, getNewline(is_, c));
747 while (is_.get(c) && catcode(c) == catNewline) {
749 s += getNewline(is_, c);
751 if (catcode(c) != catNewline)
753 push_back(Token(s, catNewline));
758 // We don't treat "%\n" combinations here specially because
759 // we want to preserve them in the preamble
761 while (is_.get(c) && catcode(c) != catNewline)
763 // handle possible DOS line ending
764 if (catcode(c) == catNewline)
765 c = getNewline(is_, c);
766 // Note: The '%' at the beginning and the '\n' at the end
767 // of the comment are not stored.
769 push_back(Token(s, catComment));
776 error("unexpected end of input");
779 if (catcode(c) == catLetter) {
781 while (is_.get(c) && catcode(c) == catLetter)
783 if (catcode(c) != catLetter)
786 push_back(Token(s, catEscape));
792 cerr << "ignoring a char: " << c << "\n";
797 push_back(Token(docstring(1, c), catcode(c)));
799 //cerr << tokens_.back();
803 void Parser::dump() const
805 cerr << "\nTokens: ";
806 for (unsigned i = 0; i < tokens_.size(); ++i) {
811 cerr << " pos: " << pos_ << "\n";
815 void Parser::error(string const & msg)
817 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;