Another minor change, but this should almost get us to the point that we
[lyx.git] / src / tex2lyx / Parser.cpp
blob70ffb5eed57b3020794dae6be2148823e350df7b
1 /**
2 * \file Parser.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author André Pönitz
8 * Full author contact details are available in file CREDITS.
9 */
11 #include <config.h>
13 #include "Encoding.h"
14 #include "Parser.h"
16 #include <iostream>
18 using namespace std;
20 namespace lyx {
22 namespace {
24 CatCode theCatcode[256];
26 void catInit()
28 static bool init_done = false;
29 if (init_done)
30 return;
31 init_done = true;
33 fill(theCatcode, theCatcode + 256, catOther);
34 fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
35 fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
37 theCatcode[int('\\')] = catEscape;
38 theCatcode[int('{')] = catBegin;
39 theCatcode[int('}')] = catEnd;
40 theCatcode[int('$')] = catMath;
41 theCatcode[int('&')] = catAlign;
42 theCatcode[int('\n')] = catNewline;
43 theCatcode[int('#')] = catParameter;
44 theCatcode[int('^')] = catSuper;
45 theCatcode[int('_')] = catSub;
46 theCatcode[0x7f] = catIgnore;
47 theCatcode[int(' ')] = catSpace;
48 theCatcode[int('\t')] = catSpace;
49 theCatcode[int('\r')] = catNewline;
50 theCatcode[int('~')] = catActive;
51 theCatcode[int('%')] = catComment;
53 // This is wrong!
54 theCatcode[int('@')] = catLetter;
57 /*!
58 * Translate a line ending to '\n'.
59 * \p c must have catcode catNewline, and it must be the last character read
60 * from \p is.
62 char_type getNewline(idocstream & is, char_type c)
64 // we have to handle 3 different line endings:
65 // - UNIX (\n)
66 // - MAC (\r)
67 // - DOS (\r\n)
68 if (c == '\r') {
69 // MAC or DOS
70 char_type wc;
71 if (is.get(wc) && wc != '\n') {
72 // MAC
73 is.putback(wc);
75 return '\n';
77 // UNIX
78 return c;
81 CatCode catcode(char_type c)
83 if (c < 256)
84 return theCatcode[(unsigned char)c];
85 return catOther;
92 // Token
95 ostream & operator<<(ostream & os, Token const & t)
97 if (t.cat() == catComment)
98 os << '%' << t.cs() << '\n';
99 else if (t.cat() == catSpace)
100 os << t.cs();
101 else if (t.cat() == catEscape)
102 os << '\\' << t.cs() << ' ';
103 else if (t.cat() == catLetter)
104 os << t.cs();
105 else if (t.cat() == catNewline)
106 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
107 else
108 os << '[' << t.cs() << ',' << t.cat() << ']';
109 return os;
113 string Token::asString() const
115 return cs_;
119 string Token::asInput() const
121 if (cat_ == catComment)
122 return '%' + cs_ + '\n';
123 if (cat_ == catEscape)
124 return '\\' + cs_;
125 return cs_;
130 // Parser
134 Parser::Parser(idocstream & is)
135 : lineno_(0), pos_(0), iss_(0), is_(is), encoding_latex_("utf8")
140 Parser::Parser(string const & s)
141 : lineno_(0), pos_(0),
142 iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
143 encoding_latex_("utf8")
148 Parser::~Parser()
150 delete iss_;
154 void Parser::setEncoding(std::string const & e)
156 Encoding const * enc = encodings.fromLaTeXName(e);
157 if (!enc) {
158 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
159 return;
161 //cerr << "setting encoding to " << enc->iconvName() << std::endl;
162 is_ << lyx::setEncoding(enc->iconvName());
163 encoding_latex_ = e;
167 void Parser::push_back(Token const & t)
169 tokens_.push_back(t);
173 // We return a copy here because the tokens_ vector may get reallocated
174 Token const Parser::prev_token() const
176 static const Token dummy;
177 return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
181 // We return a copy here because the tokens_ vector may get reallocated
182 Token const Parser::curr_token() const
184 static const Token dummy;
185 return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
189 // We return a copy here because the tokens_ vector may get reallocated
190 Token const Parser::next_token()
192 static const Token dummy;
193 return good() ? tokens_[pos_] : dummy;
197 // We return a copy here because the tokens_ vector may get reallocated
198 Token const Parser::get_token()
200 static const Token dummy;
201 //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
202 return good() ? tokens_[pos_++] : dummy;
206 bool Parser::isParagraph()
208 // A new paragraph in TeX ist started
209 // - either by a newline, following any amount of whitespace
210 // characters (including zero), and another newline
211 // - or the token \par
212 if (curr_token().cat() == catNewline &&
213 (curr_token().cs().size() > 1 ||
214 (next_token().cat() == catSpace &&
215 pos_ < tokens_.size() - 1 &&
216 tokens_[pos_ + 1].cat() == catNewline)))
217 return true;
218 if (curr_token().cat() == catEscape && curr_token().cs() == "par")
219 return true;
220 return false;
224 void Parser::skip_spaces(bool skip_comments)
226 // We just silently return if we have no more tokens.
227 // skip_spaces() should be callable at any time,
228 // the caller must check p::good() anyway.
229 while (good()) {
230 get_token();
231 if (isParagraph()) {
232 putback();
233 break;
235 if ( curr_token().cat() == catSpace ||
236 curr_token().cat() == catNewline ||
237 (curr_token().cat() == catComment && curr_token().cs().empty()))
238 continue;
239 if (skip_comments && curr_token().cat() == catComment)
240 cerr << " Ignoring comment: " << curr_token().asInput();
241 else {
242 putback();
243 break;
249 void Parser::unskip_spaces(bool skip_comments)
251 while (pos_ > 0) {
252 if ( curr_token().cat() == catSpace ||
253 (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
254 putback();
255 else if (skip_comments && curr_token().cat() == catComment) {
256 // TODO: Get rid of this
257 cerr << "Unignoring comment: " << curr_token().asInput();
258 putback();
260 else
261 break;
266 void Parser::putback()
268 --pos_;
272 bool Parser::good()
274 if (pos_ < tokens_.size())
275 return true;
276 tokenize_one();
277 return pos_ < tokens_.size();
281 char Parser::getChar()
283 if (!good())
284 error("The input stream is not well...");
285 return get_token().character();
289 Parser::Arg Parser::getFullArg(char left, char right)
291 skip_spaces(true);
293 // This is needed if a partial file ends with a command without arguments,
294 // e. g. \medskip
295 if (! good())
296 return make_pair(false, string());
298 string result;
299 char c = getChar();
301 if (c != left) {
302 putback();
303 return make_pair(false, string());
304 } else
305 while ((c = getChar()) != right && good()) {
306 // Ignore comments
307 if (curr_token().cat() == catComment) {
308 if (!curr_token().cs().empty())
309 cerr << "Ignoring comment: " << curr_token().asInput();
311 else
312 result += curr_token().asInput();
315 return make_pair(true, result);
319 string Parser::getArg(char left, char right)
321 return getFullArg(left, right).second;
325 string Parser::getFullOpt()
327 Arg arg = getFullArg('[', ']');
328 if (arg.first)
329 return '[' + arg.second + ']';
330 return string();
334 string Parser::getOpt()
336 string const res = getArg('[', ']');
337 return res.empty() ? string() : '[' + res + ']';
341 string Parser::getOptContent()
342 // the same as getOpt but without the brackets
344 string const res = getArg('[', ']');
345 return res.empty() ? string() : res;
349 string Parser::getFullParentheseArg()
351 Arg arg = getFullArg('(', ')');
352 if (arg.first)
353 return '(' + arg.second + ')';
354 return string();
358 string const Parser::verbatimEnvironment(string const & name)
360 if (!good())
361 return string();
363 ostringstream os;
364 for (Token t = get_token(); good(); t = get_token()) {
365 if (t.cat() == catBegin) {
366 putback();
367 os << '{' << verbatim_item() << '}';
368 } else if (t.asInput() == "\\begin") {
369 string const env = getArg('{', '}');
370 os << "\\begin{" << env << '}'
371 << verbatimEnvironment(env)
372 << "\\end{" << env << '}';
373 } else if (t.asInput() == "\\end") {
374 string const end = getArg('{', '}');
375 if (end != name)
376 cerr << "\\end{" << end
377 << "} does not match \\begin{" << name
378 << "}." << endl;
379 return os.str();
380 } else
381 os << t.asInput();
383 cerr << "unexpected end of input" << endl;
384 return os.str();
388 void Parser::tokenize_one()
390 catInit();
391 char_type c;
392 if (!is_.get(c))
393 return;
395 switch (catcode(c)) {
396 case catSpace: {
397 docstring s(1, c);
398 while (is_.get(c) && catcode(c) == catSpace)
399 s += c;
400 if (catcode(c) != catSpace)
401 is_.putback(c);
402 push_back(Token(s, catSpace));
403 break;
406 case catNewline: {
407 ++lineno_;
408 docstring s(1, getNewline(is_, c));
409 while (is_.get(c) && catcode(c) == catNewline) {
410 ++lineno_;
411 s += getNewline(is_, c);
413 if (catcode(c) != catNewline)
414 is_.putback(c);
415 push_back(Token(s, catNewline));
416 break;
419 case catComment: {
420 // We don't treat "%\n" combinations here specially because
421 // we want to preserve them in the preamble
422 docstring s;
423 while (is_.get(c) && catcode(c) != catNewline)
424 s += c;
425 // handle possible DOS line ending
426 if (catcode(c) == catNewline)
427 c = getNewline(is_, c);
428 // Note: The '%' at the beginning and the '\n' at the end
429 // of the comment are not stored.
430 ++lineno_;
431 push_back(Token(s, catComment));
432 break;
435 case catEscape: {
436 is_.get(c);
437 if (!is_) {
438 error("unexpected end of input");
439 } else {
440 docstring s(1, c);
441 if (catcode(c) == catLetter) {
442 // collect letters
443 while (is_.get(c) && catcode(c) == catLetter)
444 s += c;
445 if (catcode(c) != catLetter)
446 is_.putback(c);
448 push_back(Token(s, catEscape));
450 break;
453 case catIgnore: {
454 cerr << "ignoring a char: " << c << "\n";
455 break;
458 default:
459 push_back(Token(docstring(1, c), catcode(c)));
461 //cerr << tokens_.back();
465 void Parser::dump() const
467 cerr << "\nTokens: ";
468 for (unsigned i = 0; i < tokens_.size(); ++i) {
469 if (i == pos_)
470 cerr << " <#> ";
471 cerr << tokens_[i];
473 cerr << " pos: " << pos_ << "\n";
477 void Parser::error(string const & msg)
479 cerr << "Line ~" << lineno_ << ": parse error: " << msg << endl;
480 dump();
481 //exit(1);
485 string Parser::verbatimOption()
487 string res;
488 if (next_token().character() == '[') {
489 Token t = get_token();
490 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
491 if (t.cat() == catBegin) {
492 putback();
493 res += '{' + verbatim_item() + '}';
494 } else
495 res += t.asString();
498 return res;
502 string Parser::verbatim_item()
504 if (!good())
505 error("stream bad");
506 skip_spaces();
507 if (next_token().cat() == catBegin) {
508 Token t = get_token(); // skip brace
509 string res;
510 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
511 if (t.cat() == catBegin) {
512 putback();
513 res += '{' + verbatim_item() + '}';
515 else
516 res += t.asInput();
518 return res;
520 return get_token().asInput();
524 void Parser::reset()
526 pos_ = 0;
530 void Parser::setCatCode(char c, CatCode cat)
532 theCatcode[(unsigned char)c] = cat;
536 CatCode Parser::getCatCode(char c) const
538 return theCatcode[(unsigned char)c];
542 } // namespace lyx