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, std::string const & fixedenc)
158 : lineno_(0), pos_(0), iss_(0), is_(is),
159 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
160 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
161 fixed_enc_(!fixedenc.empty())
164 is_.setEncoding(fixedenc);
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),
173 // An idocstringstream can not change the encoding
185 void Parser::deparse()
188 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
189 s += tokens_[i].asInput();
191 is_.putback(from_utf8(s));
192 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
193 // make sure that next token is read
198 bool Parser::setEncoding(std::string const & e, int const & p)
200 // We may (and need to) use unsafe encodings here: Since the text is
201 // converted to unicode while reading from is_, we never see text in
202 // the original encoding of the parser, but operate on utf8 strings
203 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
204 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
206 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
209 return setEncoding(enc->iconvName());
213 void Parser::catInit()
215 if (curr_cat_ == theCatcodesType_)
217 curr_cat_ = theCatcodesType_;
219 fill(theCatcode_, theCatcode_ + 256, catOther);
220 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
221 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
223 theCatcode_[int('@')] = catLetter;
225 if (theCatcodesType_ == NORMAL_CATCODES) {
226 theCatcode_[int('\\')] = catEscape;
227 theCatcode_[int('{')] = catBegin;
228 theCatcode_[int('}')] = catEnd;
229 theCatcode_[int('$')] = catMath;
230 theCatcode_[int('&')] = catAlign;
231 theCatcode_[int('\n')] = catNewline;
232 theCatcode_[int('#')] = catParameter;
233 theCatcode_[int('^')] = catSuper;
234 theCatcode_[int('_')] = catSub;
235 theCatcode_[0x7f] = catIgnore;
236 theCatcode_[int(' ')] = catSpace;
237 theCatcode_[int('\t')] = catSpace;
238 theCatcode_[int('\r')] = catNewline;
239 theCatcode_[int('~')] = catActive;
240 theCatcode_[int('%')] = catComment;
244 CatCode Parser::catcode(char_type c) const
247 return theCatcode_[(unsigned char)c];
252 void Parser::setCatcode(char c, CatCode cat)
254 theCatcode_[(unsigned char)c] = cat;
259 void Parser::setCatcodes(cat_type t)
261 theCatcodesType_ = t;
266 bool Parser::setEncoding(std::string const & e)
268 //cerr << "setting encoding to " << e << std::endl;
270 // If the encoding is fixed, we must not change the stream encoding
271 // (because the whole input uses that encoding, e.g. if it comes from
272 // the clipboard). We still need to track the original encoding in
273 // encoding_iconv_, so that the generated output is correct.
280 void Parser::push_back(Token const & t)
282 tokens_.push_back(t);
286 // We return a copy here because the tokens_ vector may get reallocated
287 Token const Parser::prev_token() const
289 static const Token dummy;
290 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
294 // We return a copy here because the tokens_ vector may get reallocated
295 Token const Parser::curr_token() const
297 static const Token dummy;
298 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
302 // We return a copy here because the tokens_ vector may get reallocated
303 Token const Parser::next_token()
305 static const Token dummy;
308 if (pos_ >= tokens_.size())
310 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
314 // We return a copy here because the tokens_ vector may get reallocated
315 Token const Parser::next_next_token()
317 static const Token dummy;
320 // If tokenize_one() has not been called after the last get_token() we
321 // need to tokenize two more tokens.
322 if (pos_ >= tokens_.size())
324 if (pos_ + 1 >= tokens_.size())
326 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
330 // We return a copy here because the tokens_ vector may get reallocated
331 Token const Parser::get_token()
333 static const Token dummy;
336 if (pos_ >= tokens_.size()) {
338 if (pos_ >= tokens_.size())
341 // cerr << "looking at token " << tokens_[pos_]
342 // << " pos: " << pos_ << '\n';
343 return tokens_[pos_++];
347 bool Parser::isParagraph()
349 // A new paragraph in TeX ist started
350 // - either by a newline, following any amount of whitespace
351 // characters (including zero), and another newline
352 // - or the token \par
353 if (curr_token().cat() == catNewline &&
354 (curr_token().cs().size() > 1 ||
355 (next_token().cat() == catSpace &&
356 next_next_token().cat() == catNewline)))
358 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
364 bool Parser::skip_spaces(bool skip_comments)
366 // We just silently return if we have no more tokens.
367 // skip_spaces() should be callable at any time,
368 // the caller must check p::good() anyway.
369 bool skipped = false;
376 if (curr_token().cat() == catSpace ||
377 curr_token().cat() == catNewline) {
381 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
383 if (skip_comments && curr_token().cat() == catComment) {
384 // If positions_ is not empty we are doing some kind
386 if (!positions_.empty())
387 cerr << " Ignoring comment: "
388 << curr_token().asInput();
398 void Parser::unskip_spaces(bool skip_comments)
401 if ( curr_token().cat() == catSpace ||
402 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
404 else if (skip_comments && curr_token().cat() == catComment) {
405 // TODO: Get rid of this
406 // If positions_ is not empty we are doing some kind
408 if (!positions_.empty())
409 cerr << "Unignoring comment: "
410 << curr_token().asInput();
419 void Parser::putback()
425 void Parser::pushPosition()
427 positions_.push_back(pos_);
431 void Parser::popPosition()
433 pos_ = positions_.back();
434 positions_.pop_back();
439 void Parser::dropPosition()
441 positions_.pop_back();
447 if (pos_ < tokens_.size())
451 return is_.peek() != idocstream::traits_type::eof();
455 bool Parser::hasOpt()
457 // An optional argument can occur in any of the following forms:
465 // remember current position
466 unsigned int oldpos = pos_;
467 // skip spaces and comments
474 if (curr_token().cat() == catSpace ||
475 curr_token().cat() == catNewline ||
476 curr_token().cat() == catComment)
481 bool const retval = (next_token().asInput() == "[");
487 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
491 // This is needed if a partial file ends with a command without arguments,
494 return make_pair(false, string());
497 Token t = get_token();
499 if (t.cat() == catComment || t.cat() == catEscape ||
500 t.character() != left) {
502 return make_pair(false, string());
507 if (t.cat() == catComment) {
509 cerr << "Ignoring comment: " << t.asInput();
512 if (allow_escaping) {
513 if (t.cat() != catEscape && t.character() == right)
516 if (t.character() == right) {
517 if (t.cat() == catEscape)
522 result += t.asInput();
525 return make_pair(true, result);
529 string Parser::getArg(char left, char right, bool allow_escaping)
531 return getFullArg(left, right, allow_escaping).second;
535 string Parser::getFullOpt(bool keepws)
537 Arg arg = getFullArg('[', ']');
539 return '[' + arg.second + ']';
546 string Parser::getOpt(bool keepws)
548 string const res = getArg('[', ']');
554 return '[' + res + ']';
558 string Parser::getFullParentheseArg()
560 Arg arg = getFullArg('(', ')');
562 return '(' + arg.second + ')';
567 string const Parser::ertEnvironment(string const & name)
573 for (Token t = get_token(); good(); t = get_token()) {
574 if (t.cat() == catBegin) {
576 os << '{' << verbatim_item() << '}';
577 } else if (t.asInput() == "\\begin") {
578 string const env = getArg('{', '}');
579 os << "\\begin{" << env << '}'
580 << ertEnvironment(env)
581 << "\\end{" << env << '}';
582 } else if (t.asInput() == "\\end") {
583 string const end = getArg('{', '}');
585 cerr << "\\end{" << end
586 << "} does not match \\begin{" << name
592 cerr << "unexpected end of input" << endl;
597 string const Parser::plainEnvironment(string const & name)
603 for (Token t = get_token(); good(); t = get_token()) {
604 if (t.asInput() == "\\end") {
605 string const end = getArg('{', '}');
609 os << "\\end{" << end << '}';
613 cerr << "unexpected end of input" << endl;
618 string const Parser::plainCommand(char left, char right, string const & name)
622 // check if first token is really the start character
623 Token tok = get_token();
624 if (tok.character() != left) {
625 cerr << "first character does not match start character of command \\" << name << endl;
629 for (Token t = get_token(); good(); t = get_token()) {
630 if (t.character() == right) {
635 cerr << "unexpected end of input" << endl;
640 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
643 return Arg(false, string());
647 size_t match_index = 0;
648 setCatcodes(VERBATIM_CATCODES);
649 for (Token t = get_token(); good(); t = get_token()) {
650 // FIXME t.asInput() might be longer than we need ?
651 if (t.asInput() == end_string.substr(match_index,
652 t.asInput().length())) {
653 match_index += t.asInput().length();
654 if (match_index >= end_string.length())
657 if (!allow_linebreak && t.asInput() == "\n") {
658 cerr << "unexpected end of input" << endl;
660 setCatcodes(NORMAL_CATCODES);
661 return Arg(false, string());
664 oss << end_string.substr(0, match_index)
673 cerr << "unexpected end of input" << endl;
675 setCatcodes(NORMAL_CATCODES);
676 return Arg(false, string());
678 setCatcodes(NORMAL_CATCODES);
680 return Arg(true, oss.str());
684 string const Parser::verbatimEnvironment(string const & name)
686 //FIXME: do something if endstring is not found
687 string s = verbatimStuff("\\end{" + name + "}").second;
688 // ignore one newline at beginning or end of string
689 if (prefixIs(s, "\n"))
691 if (suffixIs(s, "\n"))
692 s.erase(s.length() - 1,1);
697 string Parser::verbatimOption()
700 if (next_token().character() == '[') {
701 Token t = get_token();
702 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
703 if (t.cat() == catBegin) {
705 res += '{' + verbatim_item() + '}';
714 string Parser::verbatim_item()
719 if (next_token().cat() == catBegin) {
720 Token t = get_token(); // skip brace
722 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
723 if (t.cat() == catBegin) {
725 res += '{' + verbatim_item() + '}';
732 return get_token().asInput();
736 void Parser::tokenize_one()
743 switch (catcode(c)) {
746 while (is_.get(c) && catcode(c) == catSpace)
748 if (catcode(c) != catSpace)
750 push_back(Token(s, catSpace));
756 docstring s(1, getNewline(is_, c));
757 while (is_.get(c) && catcode(c) == catNewline) {
759 s += getNewline(is_, c);
761 if (catcode(c) != catNewline)
763 push_back(Token(s, catNewline));
768 // We don't treat "%\n" combinations here specially because
769 // we want to preserve them in the preamble
771 while (is_.get(c) && catcode(c) != catNewline)
773 // handle possible DOS line ending
774 if (catcode(c) == catNewline)
775 c = getNewline(is_, c);
776 // Note: The '%' at the beginning and the '\n' at the end
777 // of the comment are not stored.
779 push_back(Token(s, catComment));
786 error("unexpected end of input");
789 if (catcode(c) == catLetter) {
791 while (is_.get(c) && catcode(c) == catLetter)
793 if (catcode(c) != catLetter)
796 push_back(Token(s, catEscape));
802 cerr << "ignoring a char: " << c << "\n";
807 push_back(Token(docstring(1, c), catcode(c)));
809 //cerr << tokens_.back();
813 void Parser::dump() const
815 cerr << "\nTokens: ";
816 for (unsigned i = 0; i < tokens_.size(); ++i) {
821 cerr << " pos: " << pos_ << "\n";
825 void Parser::error(string const & msg)
827 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;