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/lstrings.h"
16 #include "support/textutils.h"
21 using namespace lyx::support;
28 * Translate a line ending to '\n'.
29 * \p c must have catcode catNewline, and it must be the last character read
32 char_type getNewline(iparserdocstream & is, char_type c)
34 // we have to handle 3 different line endings:
41 if (is.get(wc) && wc != '\n') {
57 ostream & operator<<(ostream & os, Token const & t)
59 if (t.cat() == catComment)
60 os << '%' << t.cs() << '\n';
61 else if (t.cat() == catSpace)
63 else if (t.cat() == catEscape)
64 os << '\\' << t.cs() << ' ';
65 else if (t.cat() == catLetter)
67 else if (t.cat() == catNewline)
68 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
70 os << '[' << t.cs() << ',' << t.cat() << ']';
75 string Token::asInput() const
77 if (cat_ == catComment)
78 return '%' + cs_ + '\n';
79 if (cat_ == catEscape)
85 bool Token::isAlnumASCII() const
87 return cat_ == catLetter ||
88 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
93 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
96 os << "t: " << t << " flags: " << flags;
97 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
98 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
99 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
100 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
101 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
102 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
103 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
104 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
105 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
106 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
107 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
108 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
109 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
110 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
120 void iparserdocstream::setEncoding(std::string const & e)
122 is_ << lyx::setEncoding(e);
126 void iparserdocstream::putback(char_type c)
132 void iparserdocstream::putback(docstring s)
138 iparserdocstream & iparserdocstream::get(char_type &c)
143 //cerr << "unparsed: " << to_utf8(s_) <<endl;
156 Parser::Parser(idocstream & is, std::string const & fixedenc)
157 : lineno_(0), pos_(0), iss_(0), is_(is),
158 encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
159 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
160 fixed_enc_(!fixedenc.empty())
163 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
186 void Parser::deparse()
189 for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
190 s += tokens_[i].asInput();
192 is_.putback(from_utf8(s));
193 tokens_.erase(tokens_.begin() + pos_, tokens_.end());
194 // make sure that next token is read
199 bool Parser::setEncoding(std::string const & e, int const & p)
201 // We may (and need to) use unsafe encodings here: Since the text is
202 // converted to unicode while reading from is_, we never see text in
203 // the original encoding of the parser, but operate on utf8 strings
204 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
205 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
207 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
210 return setEncoding(enc->iconvName());
214 void Parser::catInit()
216 if (curr_cat_ == theCatcodesType_)
218 curr_cat_ = theCatcodesType_;
220 fill(theCatcode_, theCatcode_ + 256, catOther);
221 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
222 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
224 theCatcode_[int('@')] = catLetter;
226 if (theCatcodesType_ == NORMAL_CATCODES) {
227 theCatcode_[int('\\')] = catEscape;
228 theCatcode_[int('{')] = catBegin;
229 theCatcode_[int('}')] = catEnd;
230 theCatcode_[int('$')] = catMath;
231 theCatcode_[int('&')] = catAlign;
232 theCatcode_[int('\n')] = catNewline;
233 theCatcode_[int('#')] = catParameter;
234 theCatcode_[int('^')] = catSuper;
235 theCatcode_[int('_')] = catSub;
236 theCatcode_[0x7f] = catIgnore;
237 theCatcode_[int(' ')] = catSpace;
238 theCatcode_[int('\t')] = catSpace;
239 theCatcode_[int('\r')] = catNewline;
240 theCatcode_[int('~')] = catActive;
241 theCatcode_[int('%')] = catComment;
245 CatCode Parser::catcode(char_type c) const
248 return theCatcode_[(unsigned char)c];
253 void Parser::setCatcode(char c, CatCode cat)
255 theCatcode_[(unsigned char)c] = cat;
260 void Parser::setCatcodes(cat_type t)
262 theCatcodesType_ = t;
267 bool Parser::setEncoding(std::string const & e)
269 //cerr << "setting encoding to " << e << std::endl;
271 // If the encoding is fixed, we must not change the stream encoding
272 // (because the whole input uses that encoding, e.g. if it comes from
273 // the clipboard). We still need to track the original encoding in
274 // encoding_iconv_, so that the generated output is correct.
281 void Parser::push_back(Token const & t)
283 tokens_.push_back(t);
287 // We return a copy here because the tokens_ vector may get reallocated
288 Token const Parser::prev_token() const
290 static const Token dummy;
291 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
295 // We return a copy here because the tokens_ vector may get reallocated
296 Token const Parser::curr_token() const
298 static const Token dummy;
299 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
303 // We return a copy here because the tokens_ vector may get reallocated
304 Token const Parser::next_token()
306 static const Token dummy;
309 if (pos_ >= tokens_.size())
311 return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
315 // We return a copy here because the tokens_ vector may get reallocated
316 Token const Parser::next_next_token()
318 static const Token dummy;
321 // If tokenize_one() has not been called after the last get_token() we
322 // need to tokenize two more tokens.
323 if (pos_ >= tokens_.size())
325 if (pos_ + 1 >= tokens_.size())
327 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
331 // We return a copy here because the tokens_ vector may get reallocated
332 Token const Parser::get_token()
334 static const Token dummy;
337 if (pos_ >= tokens_.size()) {
339 if (pos_ >= tokens_.size())
342 // cerr << "looking at token " << tokens_[pos_]
343 // << " pos: " << pos_ << '\n';
344 return tokens_[pos_++];
348 bool Parser::isParagraph()
350 // A new paragraph in TeX ist started
351 // - either by a newline, following any amount of whitespace
352 // characters (including zero), and another newline
353 // - or the token \par
354 if (curr_token().cat() == catNewline &&
355 (curr_token().cs().size() > 1 ||
356 (next_token().cat() == catSpace &&
357 next_next_token().cat() == catNewline)))
359 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
365 bool Parser::skip_spaces(bool skip_comments)
367 // We just silently return if we have no more tokens.
368 // skip_spaces() should be callable at any time,
369 // the caller must check p::good() anyway.
370 bool skipped = false;
377 if (curr_token().cat() == catSpace ||
378 curr_token().cat() == catNewline) {
382 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
384 if (skip_comments && curr_token().cat() == catComment) {
385 // If positions_ is not empty we are doing some kind
387 if (!positions_.empty())
388 cerr << " Ignoring comment: "
389 << curr_token().asInput();
399 void Parser::unskip_spaces(bool skip_comments)
402 if ( curr_token().cat() == catSpace ||
403 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
405 else if (skip_comments && curr_token().cat() == catComment) {
406 // TODO: Get rid of this
407 // If positions_ is not empty we are doing some kind
409 if (!positions_.empty())
410 cerr << "Unignoring comment: "
411 << curr_token().asInput();
420 void Parser::putback()
426 void Parser::pushPosition()
428 positions_.push_back(pos_);
432 void Parser::popPosition()
434 pos_ = positions_.back();
435 positions_.pop_back();
440 void Parser::dropPosition()
442 positions_.pop_back();
448 if (pos_ < tokens_.size())
452 return is_.peek() != idocstream::traits_type::eof();
456 bool Parser::hasOpt(string const l)
458 // An optional argument can occur in any of the following forms:
466 // remember current position
467 unsigned int oldpos = pos_;
468 // skip spaces and comments
475 if (curr_token().cat() == catSpace ||
476 curr_token().cat() == catNewline ||
477 curr_token().cat() == catComment)
482 bool const retval = (next_token().asInput() == l);
488 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
492 // This is needed if a partial file ends with a command without arguments,
495 return make_pair(false, string());
499 Token t = get_token();
501 if (t.cat() == catComment || t.cat() == catEscape ||
502 t.character() != left) {
504 return make_pair(false, string());
509 if (left != '{' && t.cat() == catBegin) {
513 if (left != '{' && t.cat() == catEnd) {
518 if (t.cat() == catComment) {
520 cerr << "Ignoring comment: " << t.asInput();
523 if (allow_escaping) {
524 if (t.cat() != catEscape && t.character() == right
528 if (t.character() == right) {
529 if (t.cat() == catEscape)
531 if (group_level == 0)
535 result += t.asInput();
538 return make_pair(true, result);
542 string Parser::getArg(char left, char right, bool allow_escaping)
544 return getFullArg(left, right, allow_escaping).second;
548 string Parser::getFullOpt(bool keepws, char left, char right)
550 Arg arg = getFullArg(left, right);
552 return left + arg.second + right;
559 string Parser::getOpt(bool keepws)
561 string const res = getArg('[', ']');
567 return '[' + res + ']';
571 string Parser::getFullParentheseArg()
573 Arg arg = getFullArg('(', ')');
575 return '(' + arg.second + ')';
580 bool Parser::hasListPreamble(string const itemcmd)
582 // remember current position
583 unsigned int oldpos = pos_;
584 // jump over arguments
589 // and swallow spaces and comments
591 // we have a list preamble if the next thing
592 // that follows is not the \item command
593 bool res = next_token().cs() != itemcmd;
594 // back to orig position
600 string const Parser::ertEnvironment(string const & name)
606 for (Token t = get_token(); good(); t = get_token()) {
607 if (t.cat() == catBegin) {
609 os << '{' << verbatim_item() << '}';
610 } else if (t.asInput() == "\\begin") {
611 string const env = getArg('{', '}');
612 os << "\\begin{" << env << '}'
613 << ertEnvironment(env)
614 << "\\end{" << env << '}';
615 } else if (t.asInput() == "\\end") {
616 string const end = getArg('{', '}');
618 cerr << "\\end{" << end
619 << "} does not match \\begin{" << name
625 cerr << "unexpected end of input" << endl;
630 string const Parser::plainEnvironment(string const & name)
636 for (Token t = get_token(); good(); t = get_token()) {
637 if (t.asInput() == "\\end") {
638 string const end = getArg('{', '}');
642 os << "\\end{" << end << '}';
646 cerr << "unexpected end of input" << endl;
651 string const Parser::plainCommand(char left, char right, string const & name)
655 // check if first token is really the start character
656 Token tok = get_token();
657 if (tok.character() != left) {
658 cerr << "first character does not match start character of command \\" << name << endl;
662 for (Token t = get_token(); good(); t = get_token()) {
663 if (t.character() == right) {
668 cerr << "unexpected end of input" << endl;
673 string const Parser::getCommandLatexParam()
680 if (pos_ + offset >= tokens_.size())
682 if (pos_ + offset >= tokens_.size())
684 Token t = tokens_[pos_ + offset];
685 if (t.cat() == catBegin)
694 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
697 return Arg(false, string());
701 size_t match_index = 0;
702 setCatcodes(VERBATIM_CATCODES);
703 for (Token t = get_token(); good(); t = get_token()) {
704 // FIXME t.asInput() might be longer than we need ?
705 if (t.asInput() == end_string.substr(match_index,
706 t.asInput().length())) {
707 match_index += t.asInput().length();
708 if (match_index >= end_string.length())
711 if (!allow_linebreak && t.asInput() == "\n") {
712 cerr << "unexpected end of input" << endl;
714 setCatcodes(NORMAL_CATCODES);
715 return Arg(false, string());
718 oss << end_string.substr(0, match_index)
727 cerr << "unexpected end of input" << endl;
729 setCatcodes(NORMAL_CATCODES);
730 return Arg(false, string());
732 setCatcodes(NORMAL_CATCODES);
734 return Arg(true, oss.str());
738 string const Parser::verbatimEnvironment(string const & name)
740 //FIXME: do something if endstring is not found
741 string s = verbatimStuff("\\end{" + name + "}").second;
742 // ignore one newline at beginning or end of string
743 if (prefixIs(s, "\n"))
745 if (suffixIs(s, "\n"))
746 s.erase(s.length() - 1,1);
751 string Parser::verbatimOption()
754 if (next_token().character() == '[') {
755 Token t = get_token();
756 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
757 if (t.cat() == catBegin) {
759 res += '{' + verbatim_item() + '}';
768 string Parser::verbatim_item()
773 if (next_token().cat() == catBegin) {
774 Token t = get_token(); // skip brace
776 for (t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
777 if (t.cat() == catBegin) {
779 res += '{' + verbatim_item() + '}';
786 return get_token().asInput();
790 void Parser::tokenize_one()
797 switch (catcode(c)) {
800 while (is_.get(c) && catcode(c) == catSpace)
802 if (catcode(c) != catSpace)
804 push_back(Token(s, catSpace));
810 docstring s(1, getNewline(is_, c));
811 while (is_.get(c) && catcode(c) == catNewline) {
813 s += getNewline(is_, c);
815 if (catcode(c) != catNewline)
817 push_back(Token(s, catNewline));
822 // We don't treat "%\n" combinations here specially because
823 // we want to preserve them in the preamble
825 while (is_.get(c) && catcode(c) != catNewline)
827 // handle possible DOS line ending
828 if (catcode(c) == catNewline)
829 c = getNewline(is_, c);
830 // Note: The '%' at the beginning and the '\n' at the end
831 // of the comment are not stored.
833 push_back(Token(s, catComment));
840 error("unexpected end of input");
843 if (catcode(c) == catLetter) {
845 while (is_.get(c) && catcode(c) == catLetter)
847 if (catcode(c) != catLetter)
850 push_back(Token(s, catEscape));
856 cerr << "ignoring a char: " << c << "\n";
861 push_back(Token(docstring(1, c), catcode(c)));
863 //cerr << tokens_.back();
867 void Parser::dump() const
869 cerr << "\nTokens: ";
870 for (unsigned i = 0; i < tokens_.size(); ++i) {
875 cerr << " pos: " << pos_ << "\n";
879 void Parser::error(string const & msg)
881 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;