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_iconv_("UTF-8")
166 Parser::Parser(string const & s)
167 : lineno_(0), pos_(0),
168 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
169 encoding_iconv_("UTF-8")
180 void Parser::setEncoding(std::string const & e, int const & p)
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 * const enc = encodings.fromLaTeXName(e, p, true);
188 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
191 setEncoding(enc->iconvName());
195 void Parser::setEncoding(std::string const & e)
197 //cerr << "setting encoding to " << e << std::endl;
198 is_ << lyx::setEncoding(e);
203 void Parser::push_back(Token const & t)
205 tokens_.push_back(t);
209 // We return a copy here because the tokens_ vector may get reallocated
210 Token const Parser::prev_token() const
212 static const Token dummy;
213 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
217 // We return a copy here because the tokens_ vector may get reallocated
218 Token const Parser::curr_token() const
220 static const Token dummy;
221 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
225 // We return a copy here because the tokens_ vector may get reallocated
226 Token const Parser::next_token()
228 static const Token dummy;
229 return good() ? tokens_[pos_] : dummy;
233 // We return a copy here because the tokens_ vector may get reallocated
234 Token const Parser::next_next_token()
236 static const Token dummy;
237 // If good() has not been called after the last get_token() we need
238 // to tokenize two more tokens.
239 if (pos_ + 1 >= tokens_.size()) {
243 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
247 // We return a copy here because the tokens_ vector may get reallocated
248 Token const Parser::get_token()
250 static const Token dummy;
251 //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
252 return good() ? tokens_[pos_++] : dummy;
256 bool Parser::isParagraph()
258 // A new paragraph in TeX ist started
259 // - either by a newline, following any amount of whitespace
260 // characters (including zero), and another newline
261 // - or the token \par
262 if (curr_token().cat() == catNewline &&
263 (curr_token().cs().size() > 1 ||
264 (next_token().cat() == catSpace &&
265 next_next_token().cat() == catNewline)))
267 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
273 bool Parser::skip_spaces(bool skip_comments)
275 // We just silently return if we have no more tokens.
276 // skip_spaces() should be callable at any time,
277 // the caller must check p::good() anyway.
278 bool skipped = false;
285 if (curr_token().cat() == catSpace ||
286 curr_token().cat() == catNewline) {
290 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
292 if (skip_comments && curr_token().cat() == catComment) {
293 // If positions_ is not empty we are doing some kind
295 if (!positions_.empty())
296 cerr << " Ignoring comment: "
297 << curr_token().asInput();
307 void Parser::unskip_spaces(bool skip_comments)
310 if ( curr_token().cat() == catSpace ||
311 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
313 else if (skip_comments && curr_token().cat() == catComment) {
314 // TODO: Get rid of this
315 // If positions_ is not empty we are doing some kind
317 if (!positions_.empty())
318 cerr << "Unignoring comment: "
319 << curr_token().asInput();
328 void Parser::putback()
334 void Parser::pushPosition()
336 positions_.push_back(pos_);
340 void Parser::popPosition()
342 pos_ = positions_.back();
343 positions_.pop_back();
349 if (pos_ < tokens_.size())
352 return pos_ < tokens_.size();
356 char Parser::getChar()
359 error("The input stream is not well...");
360 return get_token().character();
364 bool Parser::hasOpt()
366 // An optional argument can occur in any of the following forms:
374 // remember current position
375 unsigned int oldpos = pos_;
376 // skip spaces and comments
383 if (curr_token().cat() == catSpace ||
384 curr_token().cat() == catNewline ||
385 curr_token().cat() == catComment)
390 bool const retval = (next_token().asInput() == "[");
396 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
400 // This is needed if a partial file ends with a command without arguments,
403 return make_pair(false, string());
406 Token t = get_token();
408 if (t.cat() == catComment || t.cat() == catEscape ||
409 t.character() != left) {
411 return make_pair(false, string());
413 for (t = get_token(); good(); t = get_token()) {
415 if (t.cat() == catComment) {
417 cerr << "Ignoring comment: " << t.asInput();
420 if (allow_escaping) {
421 if (t.cat() != catEscape && t.character() == right)
424 if (t.character() == right) {
425 if (t.cat() == catEscape)
430 result += t.asInput();
433 return make_pair(true, result);
437 string Parser::getArg(char left, char right, bool allow_escaping)
439 return getFullArg(left, right, allow_escaping).second;
443 string Parser::getFullOpt(bool keepws)
445 Arg arg = getFullArg('[', ']');
447 return '[' + arg.second + ']';
454 string Parser::getOpt(bool keepws)
456 string const res = getArg('[', ']');
462 return '[' + res + ']';
466 string Parser::getFullParentheseArg()
468 Arg arg = getFullArg('(', ')');
470 return '(' + arg.second + ')';
475 string const Parser::verbatimEnvironment(string const & name)
481 for (Token t = get_token(); good(); t = get_token()) {
482 if (t.cat() == catBegin) {
484 os << '{' << verbatim_item() << '}';
485 } else if (t.asInput() == "\\begin") {
486 string const env = getArg('{', '}');
487 os << "\\begin{" << env << '}'
488 << verbatimEnvironment(env)
489 << "\\end{" << env << '}';
490 } else if (t.asInput() == "\\end") {
491 string const end = getArg('{', '}');
493 cerr << "\\end{" << end
494 << "} does not match \\begin{" << name
500 cerr << "unexpected end of input" << endl;
505 string const Parser::plainEnvironment(string const & name)
511 for (Token t = get_token(); good(); t = get_token()) {
512 if (t.asInput() == "\\end") {
513 string const end = getArg('{', '}');
517 os << "\\end{" << end << '}';
521 cerr << "unexpected end of input" << endl;
526 string const Parser::plainCommand(char left, char right, string const & name)
530 // check if first token is really the start character
531 Token tok = get_token();
532 if (tok.character() != left) {
533 cerr << "first character does not match start character of command \\" << name << endl;
537 for (Token t = get_token(); good(); t = get_token()) {
538 if (t.character() == right) {
543 cerr << "unexpected end of input" << endl;
548 void Parser::tokenize_one()
555 switch (catcode(c)) {
558 while (is_.get(c) && catcode(c) == catSpace)
560 if (catcode(c) != catSpace)
562 push_back(Token(s, catSpace));
568 docstring s(1, getNewline(is_, c));
569 while (is_.get(c) && catcode(c) == catNewline) {
571 s += getNewline(is_, c);
573 if (catcode(c) != catNewline)
575 push_back(Token(s, catNewline));
580 // We don't treat "%\n" combinations here specially because
581 // we want to preserve them in the preamble
583 while (is_.get(c) && catcode(c) != catNewline)
585 // handle possible DOS line ending
586 if (catcode(c) == catNewline)
587 c = getNewline(is_, c);
588 // Note: The '%' at the beginning and the '\n' at the end
589 // of the comment are not stored.
591 push_back(Token(s, catComment));
598 error("unexpected end of input");
601 if (catcode(c) == catLetter) {
603 while (is_.get(c) && catcode(c) == catLetter)
605 if (catcode(c) != catLetter)
608 push_back(Token(s, catEscape));
614 cerr << "ignoring a char: " << c << "\n";
619 push_back(Token(docstring(1, c), catcode(c)));
621 //cerr << tokens_.back();
625 void Parser::dump() const
627 cerr << "\nTokens: ";
628 for (unsigned i = 0; i < tokens_.size(); ++i) {
633 cerr << " pos: " << pos_ << "\n";
637 void Parser::error(string const & msg)
639 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;
645 string Parser::verbatimOption()
648 if (next_token().character() == '[') {
649 Token t = get_token();
650 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
651 if (t.cat() == catBegin) {
653 res += '{' + verbatim_item() + '}';
662 string Parser::verbatim_item()
667 if (next_token().cat() == catBegin) {
668 Token t = get_token(); // skip brace
670 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
671 if (t.cat() == catBegin) {
673 res += '{' + verbatim_item() + '}';
680 return get_token().asInput();
690 void Parser::setCatCode(char c, CatCode cat)
692 theCatcode[(unsigned char)c] = cat;
696 CatCode Parser::getCatCode(char c) const
698 return theCatcode[(unsigned char)c];