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(idocstream & 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 = '|'; }
121 Parser::Parser(idocstream & is)
122 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_iconv_("UTF-8"),
123 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
128 Parser::Parser(string const & s)
129 : lineno_(0), pos_(0),
130 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
131 encoding_iconv_("UTF-8"),
132 theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES)
143 void Parser::setEncoding(std::string const & e, int const & p)
145 // We may (and need to) use unsafe encodings here: Since the text is
146 // converted to unicode while reading from is_, we never see text in
147 // the original encoding of the parser, but operate on utf8 strings
148 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
149 Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
151 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
154 setEncoding(enc->iconvName());
158 void Parser::catInit()
160 if (curr_cat_ == theCatcodesType_)
162 curr_cat_ = theCatcodesType_;
164 fill(theCatcode_, theCatcode_ + 256, catOther);
165 fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
166 fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
168 theCatcode_[int('@')] = catLetter;
170 if (theCatcodesType_ == NORMAL_CATCODES) {
171 theCatcode_[int('\\')] = catEscape;
172 theCatcode_[int('{')] = catBegin;
173 theCatcode_[int('}')] = catEnd;
174 theCatcode_[int('$')] = catMath;
175 theCatcode_[int('&')] = catAlign;
176 theCatcode_[int('\n')] = catNewline;
177 theCatcode_[int('#')] = catParameter;
178 theCatcode_[int('^')] = catSuper;
179 theCatcode_[int('_')] = catSub;
180 theCatcode_[0x7f] = catIgnore;
181 theCatcode_[int(' ')] = catSpace;
182 theCatcode_[int('\t')] = catSpace;
183 theCatcode_[int('\r')] = catNewline;
184 theCatcode_[int('~')] = catActive;
185 theCatcode_[int('%')] = catComment;
189 CatCode Parser::catcode(char_type c) const
192 return theCatcode_[(unsigned char)c];
197 void Parser::setCatcode(char c, CatCode cat)
199 theCatcode_[(unsigned char)c] = cat;
203 void Parser::setCatcodes(cat_type t)
205 theCatcodesType_ = t;
209 void Parser::setEncoding(std::string const & e)
211 //cerr << "setting encoding to " << e << std::endl;
212 is_ << lyx::setEncoding(e);
217 void Parser::push_back(Token const & t)
219 tokens_.push_back(t);
223 // We return a copy here because the tokens_ vector may get reallocated
224 Token const Parser::prev_token() const
226 static const Token dummy;
227 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
231 // We return a copy here because the tokens_ vector may get reallocated
232 Token const Parser::curr_token() const
234 static const Token dummy;
235 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
239 // We return a copy here because the tokens_ vector may get reallocated
240 Token const Parser::next_token()
242 static const Token dummy;
243 return good() ? tokens_[pos_] : dummy;
247 // We return a copy here because the tokens_ vector may get reallocated
248 Token const Parser::next_next_token()
250 static const Token dummy;
251 // If good() has not been called after the last get_token() we need
252 // to tokenize two more tokens.
253 if (pos_ + 1 >= tokens_.size()) {
257 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
261 // We return a copy here because the tokens_ vector may get reallocated
262 Token const Parser::get_token()
264 static const Token dummy;
265 //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
266 return good() ? tokens_[pos_++] : dummy;
270 bool Parser::isParagraph()
272 // A new paragraph in TeX ist started
273 // - either by a newline, following any amount of whitespace
274 // characters (including zero), and another newline
275 // - or the token \par
276 if (curr_token().cat() == catNewline &&
277 (curr_token().cs().size() > 1 ||
278 (next_token().cat() == catSpace &&
279 next_next_token().cat() == catNewline)))
281 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
287 bool Parser::skip_spaces(bool skip_comments)
289 // We just silently return if we have no more tokens.
290 // skip_spaces() should be callable at any time,
291 // the caller must check p::good() anyway.
292 bool skipped = false;
299 if (curr_token().cat() == catSpace ||
300 curr_token().cat() == catNewline) {
304 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
306 if (skip_comments && curr_token().cat() == catComment) {
307 // If positions_ is not empty we are doing some kind
309 if (!positions_.empty())
310 cerr << " Ignoring comment: "
311 << curr_token().asInput();
321 void Parser::unskip_spaces(bool skip_comments)
324 if ( curr_token().cat() == catSpace ||
325 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
327 else if (skip_comments && curr_token().cat() == catComment) {
328 // TODO: Get rid of this
329 // If positions_ is not empty we are doing some kind
331 if (!positions_.empty())
332 cerr << "Unignoring comment: "
333 << curr_token().asInput();
342 void Parser::putback()
348 void Parser::pushPosition()
350 positions_.push_back(pos_);
354 void Parser::popPosition()
356 pos_ = positions_.back();
357 positions_.pop_back();
363 if (pos_ < tokens_.size())
366 return pos_ < tokens_.size();
370 char Parser::getChar()
373 error("The input stream is not well...");
374 return get_token().character();
378 bool Parser::hasOpt()
380 // An optional argument can occur in any of the following forms:
388 // remember current position
389 unsigned int oldpos = pos_;
390 // skip spaces and comments
397 if (curr_token().cat() == catSpace ||
398 curr_token().cat() == catNewline ||
399 curr_token().cat() == catComment)
404 bool const retval = (next_token().asInput() == "[");
410 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
414 // This is needed if a partial file ends with a command without arguments,
417 return make_pair(false, string());
420 Token t = get_token();
422 if (t.cat() == catComment || t.cat() == catEscape ||
423 t.character() != left) {
425 return make_pair(false, string());
427 for (t = get_token(); good(); t = get_token()) {
429 if (t.cat() == catComment) {
431 cerr << "Ignoring comment: " << t.asInput();
434 if (allow_escaping) {
435 if (t.cat() != catEscape && t.character() == right)
438 if (t.character() == right) {
439 if (t.cat() == catEscape)
444 result += t.asInput();
447 return make_pair(true, result);
451 string Parser::getArg(char left, char right, bool allow_escaping)
453 return getFullArg(left, right, allow_escaping).second;
457 string Parser::getFullOpt(bool keepws)
459 Arg arg = getFullArg('[', ']');
461 return '[' + arg.second + ']';
468 string Parser::getOpt(bool keepws)
470 string const res = getArg('[', ']');
476 return '[' + res + ']';
480 string Parser::getFullParentheseArg()
482 Arg arg = getFullArg('(', ')');
484 return '(' + arg.second + ')';
489 string const Parser::ertEnvironment(string const & name)
495 for (Token t = get_token(); good(); t = get_token()) {
496 if (t.cat() == catBegin) {
498 os << '{' << verbatim_item() << '}';
499 } else if (t.asInput() == "\\begin") {
500 string const env = getArg('{', '}');
501 os << "\\begin{" << env << '}'
502 << ertEnvironment(env)
503 << "\\end{" << env << '}';
504 } else if (t.asInput() == "\\end") {
505 string const end = getArg('{', '}');
507 cerr << "\\end{" << end
508 << "} does not match \\begin{" << name
514 cerr << "unexpected end of input" << endl;
519 string const Parser::plainEnvironment(string const & name)
525 for (Token t = get_token(); good(); t = get_token()) {
526 if (t.asInput() == "\\end") {
527 string const end = getArg('{', '}');
531 os << "\\end{" << end << '}';
535 cerr << "unexpected end of input" << endl;
540 string const Parser::plainCommand(char left, char right, string const & name)
544 // check if first token is really the start character
545 Token tok = get_token();
546 if (tok.character() != left) {
547 cerr << "first character does not match start character of command \\" << name << endl;
551 for (Token t = get_token(); good(); t = get_token()) {
552 if (t.character() == right) {
557 cerr << "unexpected end of input" << endl;
562 string const Parser::verbatimStuff(string const & end_string)
568 size_t match_index = 0;
569 setCatcodes(VERBATIM_CATCODES);
570 for (Token t = get_token(); good(); t = get_token()) {
571 // FIXME t.asInput() might be longer than we need ?
572 if (t.asInput() == end_string.substr(match_index,
573 t.asInput().length())) {
574 match_index += t.asInput().length();
575 if (match_index >= end_string.length())
577 } else if (match_index) {
578 oss << end_string.substr(0, match_index) << t.asInput();
583 setCatcodes(NORMAL_CATCODES);
585 cerr << "unexpected end of input" << endl;
590 string const Parser::verbatimEnvironment(string const & name)
592 string s = verbatimStuff("\\end{" + name + "}");
593 // ignore one newline at beginning or end of string
594 if (prefixIs(s, "\n"))
596 if (suffixIs(s, "\n"))
597 s.erase(s.length() - 1,1);
602 void Parser::tokenize_one()
609 switch (catcode(c)) {
612 while (is_.get(c) && catcode(c) == catSpace)
614 if (catcode(c) != catSpace)
616 push_back(Token(s, catSpace));
622 docstring s(1, getNewline(is_, c));
623 while (is_.get(c) && catcode(c) == catNewline) {
625 s += getNewline(is_, c);
627 if (catcode(c) != catNewline)
629 push_back(Token(s, catNewline));
634 // We don't treat "%\n" combinations here specially because
635 // we want to preserve them in the preamble
637 while (is_.get(c) && catcode(c) != catNewline)
639 // handle possible DOS line ending
640 if (catcode(c) == catNewline)
641 c = getNewline(is_, c);
642 // Note: The '%' at the beginning and the '\n' at the end
643 // of the comment are not stored.
645 push_back(Token(s, catComment));
652 error("unexpected end of input");
655 if (catcode(c) == catLetter) {
657 while (is_.get(c) && catcode(c) == catLetter)
659 if (catcode(c) != catLetter)
662 push_back(Token(s, catEscape));
668 cerr << "ignoring a char: " << c << "\n";
673 push_back(Token(docstring(1, c), catcode(c)));
675 //cerr << tokens_.back();
679 void Parser::dump() const
681 cerr << "\nTokens: ";
682 for (unsigned i = 0; i < tokens_.size(); ++i) {
687 cerr << " pos: " << pos_ << "\n";
691 void Parser::error(string const & msg)
693 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;
699 string Parser::verbatimOption()
702 if (next_token().character() == '[') {
703 Token t = get_token();
704 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
705 if (t.cat() == catBegin) {
707 res += '{' + verbatim_item() + '}';
716 string Parser::verbatim_item()
721 if (next_token().cat() == catBegin) {
722 Token t = get_token(); // skip brace
724 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
725 if (t.cat() == catBegin) {
727 res += '{' + verbatim_item() + '}';
734 return get_token().asInput();