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 Encoding const * enc = encodings.fromLaTeXName(e);
184 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
187 //cerr << "setting encoding to " << enc->iconvName() << std::endl;
188 is_ << lyx::setEncoding(enc->iconvName());
193 void Parser::push_back(Token const & t)
195 tokens_.push_back(t);
199 // We return a copy here because the tokens_ vector may get reallocated
200 Token const Parser::prev_token() const
202 static const Token dummy;
203 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
207 // We return a copy here because the tokens_ vector may get reallocated
208 Token const Parser::curr_token() const
210 static const Token dummy;
211 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
215 // We return a copy here because the tokens_ vector may get reallocated
216 Token const Parser::next_token()
218 static const Token dummy;
219 return good() ? tokens_[pos_] : dummy;
223 // We return a copy here because the tokens_ vector may get reallocated
224 Token const Parser::next_next_token()
226 static const Token dummy;
227 // If good() has not been called after the last get_token() we need
228 // to tokenize two more tokens.
229 if (pos_ + 1 >= tokens_.size()) {
233 return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
237 // We return a copy here because the tokens_ vector may get reallocated
238 Token const Parser::get_token()
240 static const Token dummy;
241 //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
242 return good() ? tokens_[pos_++] : dummy;
246 bool Parser::isParagraph()
248 // A new paragraph in TeX ist started
249 // - either by a newline, following any amount of whitespace
250 // characters (including zero), and another newline
251 // - or the token \par
252 if (curr_token().cat() == catNewline &&
253 (curr_token().cs().size() > 1 ||
254 (next_token().cat() == catSpace &&
255 next_next_token().cat() == catNewline)))
257 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
263 bool Parser::skip_spaces(bool skip_comments)
265 // We just silently return if we have no more tokens.
266 // skip_spaces() should be callable at any time,
267 // the caller must check p::good() anyway.
268 bool skipped = false;
275 if (curr_token().cat() == catSpace ||
276 curr_token().cat() == catNewline) {
280 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
282 if (skip_comments && curr_token().cat() == catComment) {
283 // If positions_ is not empty we are doing some kind
285 if (!positions_.empty())
286 cerr << " Ignoring comment: "
287 << curr_token().asInput();
297 void Parser::unskip_spaces(bool skip_comments)
300 if ( curr_token().cat() == catSpace ||
301 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
303 else if (skip_comments && curr_token().cat() == catComment) {
304 // TODO: Get rid of this
305 // If positions_ is not empty we are doing some kind
307 if (!positions_.empty())
308 cerr << "Unignoring comment: "
309 << curr_token().asInput();
318 void Parser::putback()
324 void Parser::pushPosition()
326 positions_.push_back(pos_);
330 void Parser::popPosition()
332 pos_ = positions_.back();
333 positions_.pop_back();
339 if (pos_ < tokens_.size())
342 return pos_ < tokens_.size();
346 char Parser::getChar()
349 error("The input stream is not well...");
350 return get_token().character();
354 bool Parser::hasOpt()
356 // An optional argument can occur in any of the following forms:
364 // remember current position
365 unsigned int oldpos = pos_;
366 // skip spaces and comments
373 if (curr_token().cat() == catSpace ||
374 curr_token().cat() == catNewline ||
375 curr_token().cat() == catComment)
380 bool const retval = (next_token().asInput() == "[");
386 Parser::Arg Parser::getFullArg(char left, char right)
390 // This is needed if a partial file ends with a command without arguments,
393 return make_pair(false, string());
400 return make_pair(false, string());
402 // in case of the '+' as delimiter single a '\' is allowed
403 // as content, for example "\verb+\+" (reported as bug #4468)
404 // we need special handling because single \ are normally ignored
405 // or taken as start of a command
407 if (next_token().cat() == catEscape)
409 while ((c = getChar()) != right && good()) {
411 if (curr_token().cat() == catComment) {
412 if (!curr_token().cs().empty())
413 cerr << "Ignoring comment: " << curr_token().asInput();
416 result += curr_token().asInput();
419 return make_pair(true, result);
423 string Parser::getArg(char left, char right)
425 return getFullArg(left, right).second;
429 string Parser::getFullOpt(bool keepws)
431 Arg arg = getFullArg('[', ']');
433 return '[' + arg.second + ']';
440 string Parser::getOpt(bool keepws)
442 string const res = getArg('[', ']');
448 return '[' + res + ']';
452 string Parser::getFullParentheseArg()
454 Arg arg = getFullArg('(', ')');
456 return '(' + arg.second + ')';
461 string const Parser::verbatimEnvironment(string const & name)
467 for (Token t = get_token(); good(); t = get_token()) {
468 if (t.cat() == catBegin) {
470 os << '{' << verbatim_item() << '}';
471 } else if (t.asInput() == "\\begin") {
472 string const env = getArg('{', '}');
473 os << "\\begin{" << env << '}'
474 << verbatimEnvironment(env)
475 << "\\end{" << env << '}';
476 } else if (t.asInput() == "\\end") {
477 string const end = getArg('{', '}');
479 cerr << "\\end{" << end
480 << "} does not match \\begin{" << name
486 cerr << "unexpected end of input" << endl;
491 string const Parser::plainEnvironment(string const & name)
497 for (Token t = get_token(); good(); t = get_token()) {
498 if (t.asInput() == "\\end") {
499 string const end = getArg('{', '}');
503 os << "\\end{" << end << '}';
507 cerr << "unexpected end of input" << endl;
512 string const Parser::plainCommand(char left, char right, string const & name)
516 // check if first token is really the start character
517 Token tok = get_token();
518 if (tok.character() != left) {
519 cerr << "first character does not match start character of command \\" << name << endl;
523 for (Token t = get_token(); good(); t = get_token()) {
524 if (t.character() == right) {
529 cerr << "unexpected end of input" << endl;
534 void Parser::tokenize_one()
541 switch (catcode(c)) {
544 while (is_.get(c) && catcode(c) == catSpace)
546 if (catcode(c) != catSpace)
548 push_back(Token(s, catSpace));
554 docstring s(1, getNewline(is_, c));
555 while (is_.get(c) && catcode(c) == catNewline) {
557 s += getNewline(is_, c);
559 if (catcode(c) != catNewline)
561 push_back(Token(s, catNewline));
566 // We don't treat "%\n" combinations here specially because
567 // we want to preserve them in the preamble
569 while (is_.get(c) && catcode(c) != catNewline)
571 // handle possible DOS line ending
572 if (catcode(c) == catNewline)
573 c = getNewline(is_, c);
574 // Note: The '%' at the beginning and the '\n' at the end
575 // of the comment are not stored.
577 push_back(Token(s, catComment));
584 error("unexpected end of input");
587 if (catcode(c) == catLetter) {
589 while (is_.get(c) && catcode(c) == catLetter)
591 if (catcode(c) != catLetter)
594 push_back(Token(s, catEscape));
600 cerr << "ignoring a char: " << c << "\n";
605 push_back(Token(docstring(1, c), catcode(c)));
607 //cerr << tokens_.back();
611 void Parser::dump() const
613 cerr << "\nTokens: ";
614 for (unsigned i = 0; i < tokens_.size(); ++i) {
619 cerr << " pos: " << pos_ << "\n";
623 void Parser::error(string const & msg)
625 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;
631 string Parser::verbatimOption()
634 if (next_token().character() == '[') {
635 Token t = get_token();
636 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
637 if (t.cat() == catBegin) {
639 res += '{' + verbatim_item() + '}';
648 string Parser::verbatim_item()
653 if (next_token().cat() == catBegin) {
654 Token t = get_token(); // skip brace
656 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
657 if (t.cat() == catBegin) {
659 res += '{' + verbatim_item() + '}';
666 return get_token().asInput();
676 void Parser::setCatCode(char c, CatCode cat)
678 theCatcode[(unsigned char)c] = cat;
682 CatCode Parser::getCatCode(char c) const
684 return theCatcode[(unsigned char)c];