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/textutils.h"
25 CatCode theCatcode[256];
29 static bool init_done = false;
34 fill(theCatcode, theCatcode + 256, catOther);
35 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
36 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
38 theCatcode[int('\\')] = catEscape;
39 theCatcode[int('{')] = catBegin;
40 theCatcode[int('}')] = catEnd;
41 theCatcode[int('$')] = catMath;
42 theCatcode[int('&')] = catAlign;
43 theCatcode[int('\n')] = catNewline;
44 theCatcode[int('#')] = catParameter;
45 theCatcode[int('^')] = catSuper;
46 theCatcode[int('_')] = catSub;
47 theCatcode[0x7f] = catIgnore;
48 theCatcode[int(' ')] = catSpace;
49 theCatcode[int('\t')] = catSpace;
50 theCatcode[int('\r')] = catNewline;
51 theCatcode[int('~')] = catActive;
52 theCatcode[int('%')] = catComment;
55 theCatcode[int('@')] = catLetter;
59 * Translate a line ending to '\n'.
60 * \p c must have catcode catNewline, and it must be the last character read
63 char_type getNewline(idocstream & is, char_type c)
65 // we have to handle 3 different line endings:
72 if (is.get(wc) && wc != '\n') {
82 CatCode catcode(char_type c)
85 return theCatcode[(unsigned char)c];
96 ostream & operator<<(ostream & os, Token const & t)
98 if (t.cat() == catComment)
99 os << '%' << t.cs() << '\n';
100 else if (t.cat() == catSpace)
102 else if (t.cat() == catEscape)
103 os << '\\' << t.cs() << ' ';
104 else if (t.cat() == catLetter)
106 else if (t.cat() == catNewline)
107 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
109 os << '[' << t.cs() << ',' << t.cat() << ']';
114 string Token::asInput() const
116 if (cat_ == catComment)
117 return '%' + cs_ + '\n';
118 if (cat_ == catEscape)
124 bool Token::isAlnumASCII() const
126 return cat_ == catLetter ||
127 (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
132 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
135 os << "t: " << t << " flags: " << flags;
136 if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
137 if (flags & FLAG_RIGHT ) { os << sep << "RIGHT" ; sep = '|'; }
138 if (flags & FLAG_END ) { os << sep << "END" ; sep = '|'; }
139 if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
140 if (flags & FLAG_TEXTMODE ) { os << sep << "TEXTMODE" ; sep = '|'; }
141 if (flags & FLAG_ITEM ) { os << sep << "ITEM" ; sep = '|'; }
142 if (flags & FLAG_LEAVE ) { os << sep << "LEAVE" ; sep = '|'; }
143 if (flags & FLAG_SIMPLE ) { os << sep << "SIMPLE" ; sep = '|'; }
144 if (flags & FLAG_EQUATION ) { os << sep << "EQUATION" ; sep = '|'; }
145 if (flags & FLAG_SIMPLE2 ) { os << sep << "SIMPLE2" ; sep = '|'; }
146 if (flags & FLAG_OPTION ) { os << sep << "OPTION" ; sep = '|'; }
147 if (flags & FLAG_BRACED ) { os << sep << "BRACED" ; sep = '|'; }
148 if (flags & FLAG_CELL ) { os << sep << "CELL" ; sep = '|'; }
149 if (flags & FLAG_TABBING ) { os << sep << "TABBING" ; sep = '|'; }
160 Parser::Parser(idocstream & is)
161 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_latex_("utf8")
166 Parser::Parser(string const & s)
167 : lineno_(0), pos_(0),
168 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
169 encoding_latex_("utf8")
180 void Parser::setEncoding(std::string const & e)
182 // We may (and need to) use unsafe encodings here: Since the text is
183 // converted to unicode while reading from is_, we never see text in
184 // the original encoding of the parser, but operate on utf8 strings
185 // instead. Therefore, we cannot misparse high bytes as {, } or \\.
186 Encoding const * enc = encodings.fromLaTeXName(e, true);
188 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
191 //cerr << "setting encoding to " << enc->iconvName() << std::endl;
192 is_ << lyx::setEncoding(enc->iconvName());
197 void Parser::push_back(Token const & t)
199 tokens_.push_back(t);
203 // We return a copy here because the tokens_ vector may get reallocated
204 Token const Parser::prev_token() const
206 static const Token dummy;
207 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
211 // We return a copy here because the tokens_ vector may get reallocated
212 Token const Parser::curr_token() const
214 static const Token dummy;
215 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
219 // We return a copy here because the tokens_ vector may get reallocated
220 Token const Parser::next_token()
222 static const Token dummy;
223 return good() ? tokens_[pos_] : dummy;
227 // We return a copy here because the tokens_ vector may get reallocated
228 Token const Parser::next_next_token()
230 static const Token dummy;
231 // If good() has not been called after the last get_token() we need
232 // to tokenize two more tokens.
233 if (pos_ + 1 >= tokens_.size()) {
237 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
241 // We return a copy here because the tokens_ vector may get reallocated
242 Token const Parser::get_token()
244 static const Token dummy;
245 //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
246 return good() ? tokens_[pos_++] : dummy;
250 bool Parser::isParagraph()
252 // A new paragraph in TeX ist started
253 // - either by a newline, following any amount of whitespace
254 // characters (including zero), and another newline
255 // - or the token \par
256 if (curr_token().cat() == catNewline &&
257 (curr_token().cs().size() > 1 ||
258 (next_token().cat() == catSpace &&
259 next_next_token().cat() == catNewline)))
261 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
267 bool Parser::skip_spaces(bool skip_comments)
269 // We just silently return if we have no more tokens.
270 // skip_spaces() should be callable at any time,
271 // the caller must check p::good() anyway.
272 bool skipped = false;
279 if (curr_token().cat() == catSpace ||
280 curr_token().cat() == catNewline) {
284 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
286 if (skip_comments && curr_token().cat() == catComment) {
287 // If positions_ is not empty we are doing some kind
289 if (!positions_.empty())
290 cerr << " Ignoring comment: "
291 << curr_token().asInput();
301 void Parser::unskip_spaces(bool skip_comments)
304 if ( curr_token().cat() == catSpace ||
305 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
307 else if (skip_comments && curr_token().cat() == catComment) {
308 // TODO: Get rid of this
309 // If positions_ is not empty we are doing some kind
311 if (!positions_.empty())
312 cerr << "Unignoring comment: "
313 << curr_token().asInput();
322 void Parser::putback()
328 void Parser::pushPosition()
330 positions_.push_back(pos_);
334 void Parser::popPosition()
336 pos_ = positions_.back();
337 positions_.pop_back();
343 if (pos_ < tokens_.size())
346 return pos_ < tokens_.size();
350 char Parser::getChar()
353 error("The input stream is not well...");
354 return get_token().character();
358 bool Parser::hasOpt()
360 // An optional argument can occur in any of the following forms:
368 // remember current position
369 unsigned int oldpos = pos_;
370 // skip spaces and comments
377 if (curr_token().cat() == catSpace ||
378 curr_token().cat() == catNewline ||
379 curr_token().cat() == catComment)
384 bool const retval = (next_token().asInput() == "[");
390 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
394 // This is needed if a partial file ends with a command without arguments,
397 return make_pair(false, string());
400 Token t = get_token();
402 if (t.cat() == catComment || t.cat() == catEscape ||
403 t.character() != left) {
405 return make_pair(false, string());
407 for (t = get_token(); good(); t = get_token()) {
409 if (t.cat() == catComment) {
411 cerr << "Ignoring comment: " << t.asInput();
414 if (allow_escaping) {
415 if (t.cat() != catEscape && t.character() == right)
418 if (t.character() == right) {
419 if (t.cat() == catEscape)
424 result += t.asInput();
427 return make_pair(true, result);
431 string Parser::getArg(char left, char right, bool allow_escaping)
433 return getFullArg(left, right, allow_escaping).second;
437 string Parser::getFullOpt(bool keepws)
439 Arg arg = getFullArg('[', ']');
441 return '[' + arg.second + ']';
448 string Parser::getOpt(bool keepws)
450 string const res = getArg('[', ']');
456 return '[' + res + ']';
460 string Parser::getFullParentheseArg()
462 Arg arg = getFullArg('(', ')');
464 return '(' + arg.second + ')';
469 string const Parser::verbatimEnvironment(string const & name)
475 for (Token t = get_token(); good(); t = get_token()) {
476 if (t.cat() == catBegin) {
478 os << '{' << verbatim_item() << '}';
479 } else if (t.asInput() == "\\begin") {
480 string const env = getArg('{', '}');
481 os << "\\begin{" << env << '}'
482 << verbatimEnvironment(env)
483 << "\\end{" << env << '}';
484 } else if (t.asInput() == "\\end") {
485 string const end = getArg('{', '}');
487 cerr << "\\end{" << end
488 << "} does not match \\begin{" << name
494 cerr << "unexpected end of input" << endl;
499 string const Parser::plainEnvironment(string const & name)
505 for (Token t = get_token(); good(); t = get_token()) {
506 if (t.asInput() == "\\end") {
507 string const end = getArg('{', '}');
511 os << "\\end{" << end << '}';
515 cerr << "unexpected end of input" << endl;
520 string const Parser::plainCommand(char left, char right, string const & name)
524 // check if first token is really the start character
525 Token tok = get_token();
526 if (tok.character() != left) {
527 cerr << "first character does not match start character of command \\" << name << endl;
531 for (Token t = get_token(); good(); t = get_token()) {
532 if (t.character() == right) {
537 cerr << "unexpected end of input" << endl;
542 void Parser::tokenize_one()
549 switch (catcode(c)) {
552 while (is_.get(c) && catcode(c) == catSpace)
554 if (catcode(c) != catSpace)
556 push_back(Token(s, catSpace));
562 docstring s(1, getNewline(is_, c));
563 while (is_.get(c) && catcode(c) == catNewline) {
565 s += getNewline(is_, c);
567 if (catcode(c) != catNewline)
569 push_back(Token(s, catNewline));
574 // We don't treat "%\n" combinations here specially because
575 // we want to preserve them in the preamble
577 while (is_.get(c) && catcode(c) != catNewline)
579 // handle possible DOS line ending
580 if (catcode(c) == catNewline)
581 c = getNewline(is_, c);
582 // Note: The '%' at the beginning and the '\n' at the end
583 // of the comment are not stored.
585 push_back(Token(s, catComment));
592 error("unexpected end of input");
595 if (catcode(c) == catLetter) {
597 while (is_.get(c) && catcode(c) == catLetter)
599 if (catcode(c) != catLetter)
602 push_back(Token(s, catEscape));
608 cerr << "ignoring a char: " << c << "\n";
613 push_back(Token(docstring(1, c), catcode(c)));
615 //cerr << tokens_.back();
619 void Parser::dump() const
621 cerr << "\nTokens: ";
622 for (unsigned i = 0; i < tokens_.size(); ++i) {
627 cerr << " pos: " << pos_ << "\n";
631 void Parser::error(string const & msg)
633 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;
639 string Parser::verbatimOption()
642 if (next_token().character() == '[') {
643 Token t = get_token();
644 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
645 if (t.cat() == catBegin) {
647 res += '{' + verbatim_item() + '}';
656 string Parser::verbatim_item()
661 if (next_token().cat() == catBegin) {
662 Token t = get_token(); // skip brace
664 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
665 if (t.cat() == catBegin) {
667 res += '{' + verbatim_item() + '}';
674 return get_token().asInput();
684 void Parser::setCatCode(char c, CatCode cat)
686 theCatcode[(unsigned char)c] = cat;
690 CatCode Parser::getCatCode(char c) const
692 return theCatcode[(unsigned char)c];