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::putback(char_type c)
127 void iparserdocstream::put_almost_back(docstring s)
133 iparserdocstream & iparserdocstream::get(char_type &c)
150 Parser::Parser(idocstream & is)
151 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_iconv_("UTF-8"),
152 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
157 Parser::Parser(string const & s)
158 : lineno_(0), pos_(0),
159 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
160 encoding_iconv_("UTF-8"),
161 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
172 void Parser::deparse()
175 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
176 s += tokens_[i].asInput();
178 is_.put_almost_back(from_utf8(s));
179 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
180 // make sure that next token is read
185 void Parser::setEncoding(std::string const & e, int const & p)
187 // We may (and need to) use unsafe encodings here: Since the text is
188 // converted to unicode while reading from is_, we never see text in
189 // the original encoding of the parser, but operate on utf8 strings
190 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
191 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
193 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
196 setEncoding(enc->iconvName());
200 void Parser::catInit()
202 if (curr_cat_ == theCatcodesType_)
204 curr_cat_ = theCatcodesType_;
206 fill(theCatcode_, theCatcode_ + 256, catOther);
207 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
208 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
210 theCatcode_[int('@')] = catLetter;
212 if (theCatcodesType_ == NORMAL_CATCODES) {
213 theCatcode_[int('\\')] = catEscape;
214 theCatcode_[int('{')] = catBegin;
215 theCatcode_[int('}')] = catEnd;
216 theCatcode_[int('$')] = catMath;
217 theCatcode_[int('&')] = catAlign;
218 theCatcode_[int('\n')] = catNewline;
219 theCatcode_[int('#')] = catParameter;
220 theCatcode_[int('^')] = catSuper;
221 theCatcode_[int('_')] = catSub;
222 theCatcode_[0x7f] = catIgnore;
223 theCatcode_[int(' ')] = catSpace;
224 theCatcode_[int('\t')] = catSpace;
225 theCatcode_[int('\r')] = catNewline;
226 theCatcode_[int('~')] = catActive;
227 theCatcode_[int('%')] = catComment;
231 CatCode Parser::catcode(char_type c) const
234 return theCatcode_[(unsigned char)c];
239 void Parser::setCatcode(char c, CatCode cat)
241 theCatcode_[(unsigned char)c] = cat;
246 void Parser::setCatcodes(cat_type t)
248 theCatcodesType_ = t;
253 void Parser::setEncoding(std::string const & e)
255 //cerr << "setting encoding to " << e << std::endl;
256 is_.docstream() << lyx::setEncoding(e);
261 void Parser::push_back(Token const & t)
263 tokens_.push_back(t);
267 // We return a copy here because the tokens_ vector may get reallocated
268 Token const Parser::prev_token() const
270 static const Token dummy;
271 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
275 // We return a copy here because the tokens_ vector may get reallocated
276 Token const Parser::curr_token() const
278 static const Token dummy;
279 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
283 // We return a copy here because the tokens_ vector may get reallocated
284 Token const Parser::next_token()
286 static const Token dummy;
287 return good() ? tokens_[pos_] : dummy;
291 // We return a copy here because the tokens_ vector may get reallocated
292 Token const Parser::next_next_token()
294 static const Token dummy;
295 // If good() has not been called after the last get_token() we need
296 // to tokenize two more tokens.
297 if (pos_ + 1 >= tokens_.size()) {
301 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
305 // We return a copy here because the tokens_ vector may get reallocated
306 Token const Parser::get_token()
308 static const Token dummy;
310 // cerr << "looking at token " << tokens_[pos_]
311 // << " pos: " << pos_ << '\n';
312 return good() ? tokens_[pos_++] : dummy;
316 bool Parser::isParagraph()
318 // A new paragraph in TeX ist started
319 // - either by a newline, following any amount of whitespace
320 // characters (including zero), and another newline
321 // - or the token \par
322 if (curr_token().cat() == catNewline &&
323 (curr_token().cs().size() > 1 ||
324 (next_token().cat() == catSpace &&
325 next_next_token().cat() == catNewline)))
327 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
333 bool Parser::skip_spaces(bool skip_comments)
335 // We just silently return if we have no more tokens.
336 // skip_spaces() should be callable at any time,
337 // the caller must check p::good() anyway.
338 bool skipped = false;
345 if (curr_token().cat() == catSpace ||
346 curr_token().cat() == catNewline) {
350 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
352 if (skip_comments && curr_token().cat() == catComment) {
353 // If positions_ is not empty we are doing some kind
355 if (!positions_.empty())
356 cerr << " Ignoring comment: "
357 << curr_token().asInput();
367 void Parser::unskip_spaces(bool skip_comments)
370 if ( curr_token().cat() == catSpace ||
371 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
373 else if (skip_comments && curr_token().cat() == catComment) {
374 // TODO: Get rid of this
375 // If positions_ is not empty we are doing some kind
377 if (!positions_.empty())
378 cerr << "Unignoring comment: "
379 << curr_token().asInput();
388 void Parser::putback()
394 void Parser::pushPosition()
396 positions_.push_back(pos_);
400 void Parser::popPosition()
402 pos_ = positions_.back();
403 positions_.pop_back();
409 if (pos_ < tokens_.size())
412 return pos_ < tokens_.size();
416 bool Parser::hasOpt()
418 // An optional argument can occur in any of the following forms:
426 // remember current position
427 unsigned int oldpos = pos_;
428 // skip spaces and comments
435 if (curr_token().cat() == catSpace ||
436 curr_token().cat() == catNewline ||
437 curr_token().cat() == catComment)
442 bool const retval = (next_token().asInput() == "[");
448 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
452 // This is needed if a partial file ends with a command without arguments,
455 return make_pair(false, string());
458 Token t = get_token();
460 if (t.cat() == catComment || t.cat() == catEscape ||
461 t.character() != left) {
463 return make_pair(false, string());
465 for (t = get_token(); good(); t = get_token()) {
467 if (t.cat() == catComment) {
469 cerr << "Ignoring comment: " << t.asInput();
472 if (allow_escaping) {
473 if (t.cat() != catEscape && t.character() == right)
476 if (t.character() == right) {
477 if (t.cat() == catEscape)
482 result += t.asInput();
485 return make_pair(true, result);
489 string Parser::getArg(char left, char right, bool allow_escaping)
491 return getFullArg(left, right, allow_escaping).second;
495 string Parser::getFullOpt(bool keepws)
497 Arg arg = getFullArg('[', ']');
499 return '[' + arg.second + ']';
506 string Parser::getOpt(bool keepws)
508 string const res = getArg('[', ']');
514 return '[' + res + ']';
518 string Parser::getFullParentheseArg()
520 Arg arg = getFullArg('(', ')');
522 return '(' + arg.second + ')';
527 string const Parser::ertEnvironment(string const & name)
533 for (Token t = get_token(); good(); t = get_token()) {
534 if (t.cat() == catBegin) {
536 os << '{' << verbatim_item() << '}';
537 } else if (t.asInput() == "\\begin") {
538 string const env = getArg('{', '}');
539 os << "\\begin{" << env << '}'
540 << ertEnvironment(env)
541 << "\\end{" << env << '}';
542 } else if (t.asInput() == "\\end") {
543 string const end = getArg('{', '}');
545 cerr << "\\end{" << end
546 << "} does not match \\begin{" << name
552 cerr << "unexpected end of input" << endl;
557 string const Parser::plainEnvironment(string const & name)
563 for (Token t = get_token(); good(); t = get_token()) {
564 if (t.asInput() == "\\end") {
565 string const end = getArg('{', '}');
569 os << "\\end{" << end << '}';
573 cerr << "unexpected end of input" << endl;
578 string const Parser::plainCommand(char left, char right, string const & name)
582 // check if first token is really the start character
583 Token tok = get_token();
584 if (tok.character() != left) {
585 cerr << "first character does not match start character of command \\" << name << endl;
589 for (Token t = get_token(); good(); t = get_token()) {
590 if (t.character() == right) {
595 cerr << "unexpected end of input" << endl;
600 string const Parser::verbatimStuff(string const & end_string)
606 size_t match_index = 0;
607 setCatcodes(VERBATIM_CATCODES);
608 for (Token t = get_token(); good(); t = get_token()) {
609 // FIXME t.asInput() might be longer than we need ?
610 if (t.asInput() == end_string.substr(match_index,
611 t.asInput().length())) {
612 match_index += t.asInput().length();
613 if (match_index >= end_string.length())
615 } else if (match_index) {
616 oss << end_string.substr(0, match_index) << t.asInput();
621 setCatcodes(NORMAL_CATCODES);
623 cerr << "unexpected end of input" << endl;
628 string const Parser::verbatimEnvironment(string const & name)
630 string s = verbatimStuff("\\end{" + name + "}");
631 // ignore one newline at beginning or end of string
632 if (prefixIs(s, "\n"))
634 if (suffixIs(s, "\n"))
635 s.erase(s.length() - 1,1);
640 string Parser::verbatimOption()
643 if (next_token().character() == '[') {
644 Token t = get_token();
645 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
646 if (t.cat() == catBegin) {
648 res += '{' + verbatim_item() + '}';
657 string Parser::verbatim_item()
662 if (next_token().cat() == catBegin) {
663 Token t = get_token(); // skip brace
665 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
666 if (t.cat() == catBegin) {
668 res += '{' + verbatim_item() + '}';
675 return get_token().asInput();
679 void Parser::tokenize_one()
686 switch (catcode(c)) {
689 while (is_.get(c) && catcode(c) == catSpace)
691 if (catcode(c) != catSpace)
693 push_back(Token(s, catSpace));
699 docstring s(1, getNewline(is_, c));
700 while (is_.get(c) && catcode(c) == catNewline) {
702 s += getNewline(is_, c);
704 if (catcode(c) != catNewline)
706 push_back(Token(s, catNewline));
711 // We don't treat "%\n" combinations here specially because
712 // we want to preserve them in the preamble
714 while (is_.get(c) && catcode(c) != catNewline)
716 // handle possible DOS line ending
717 if (catcode(c) == catNewline)
718 c = getNewline(is_, c);
719 // Note: The '%' at the beginning and the '\n' at the end
720 // of the comment are not stored.
722 push_back(Token(s, catComment));
729 error("unexpected end of input");
732 if (catcode(c) == catLetter) {
734 while (is_.get(c) && catcode(c) == catLetter)
736 if (catcode(c) != catLetter)
739 push_back(Token(s, catEscape));
745 cerr << "ignoring a char: " << c << "\n";
750 push_back(Token(docstring(1, c), catcode(c)));
752 //cerr << tokens_.back();
756 void Parser::dump() const
758 cerr << "\nTokens: ";
759 for (unsigned i = 0; i < tokens_.size(); ++i) {
764 cerr << " pos: " << pos_ << "\n";
768 void Parser::error(string const & msg)
770 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;