]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.cpp
* doxy
[lyx.git] / src / tex2lyx / Parser.cpp
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.
5  *
6  * \author André Pönitz 
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Encoding.h"
14 #include "Parser.h"
15
16 #include <iostream>
17
18 using namespace std;
19
20 namespace lyx {
21
22 namespace {
23
24 CatCode theCatcode[256];
25
26 void catInit()
27 {
28         static bool init_done = false;
29         if (init_done) 
30                 return;
31         init_done = true;
32
33         fill(theCatcode, theCatcode + 256, catOther);
34         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
35         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
36
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;
52
53         // This is wrong!
54         theCatcode[int('@')]  = catLetter;
55 }
56
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.
61  */
62 char_type getNewline(idocstream & is, char_type c)
63 {
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);
74                 }
75                 return '\n';
76         }
77         // UNIX
78         return c;
79 }
80
81 CatCode catcode(char_type c)
82 {
83         if (c < 256)
84                 return theCatcode[(unsigned char)c];
85         return catOther;
86 }
87
88 }
89
90
91 //
92 // Token
93 //
94
95 ostream & operator<<(ostream & os, Token const & t)
96 {
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;
110 }
111
112
113 string Token::asInput() const
114 {
115         if (cat_ == catComment)
116                 return '%' + cs_ + '\n';
117         if (cat_ == catEscape)
118                 return '\\' + cs_;
119         return cs_;
120 }
121
122
123 //
124 // Parser
125 //
126
127
128 Parser::Parser(idocstream & is)
129         : lineno_(0), pos_(0), iss_(0), is_(is), encoding_latex_("utf8")
130 {
131 }
132
133
134 Parser::Parser(string const & s)
135         : lineno_(0), pos_(0), 
136           iss_(new idocstringstream(from_utf8(s))), is_(*iss_), 
137           encoding_latex_("utf8")
138 {
139 }
140
141
142 Parser::~Parser()
143 {
144         delete iss_;
145 }
146
147
148 void Parser::setEncoding(std::string const & e)
149 {
150         Encoding const * enc = encodings.fromLaTeXName(e);
151         if (!enc) {
152                 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
153                 return;
154         }
155         //cerr << "setting encoding to " << enc->iconvName() << std::endl;
156         is_ << lyx::setEncoding(enc->iconvName());
157         encoding_latex_ = e;
158 }
159
160
161 void Parser::push_back(Token const & t)
162 {
163         tokens_.push_back(t);
164 }
165
166
167 // We return a copy here because the tokens_ vector may get reallocated
168 Token const Parser::prev_token() const
169 {
170         static const Token dummy;
171         return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
172 }
173
174
175 // We return a copy here because the tokens_ vector may get reallocated
176 Token const Parser::curr_token() const
177 {
178         static const Token dummy;
179         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
180 }
181
182
183 // We return a copy here because the tokens_ vector may get reallocated
184 Token const Parser::next_token()
185 {
186         static const Token dummy;
187         return good() ? tokens_[pos_] : dummy;
188 }
189
190
191 // We return a copy here because the tokens_ vector may get reallocated
192 Token const Parser::get_token()
193 {
194         static const Token dummy;
195         //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
196         return good() ? tokens_[pos_++] : dummy;
197 }
198
199
200 bool Parser::isParagraph()
201 {
202         // A new paragraph in TeX ist started
203         // - either by a newline, following any amount of whitespace
204         //   characters (including zero), and another newline
205         // - or the token \par
206         if (curr_token().cat() == catNewline &&
207             (curr_token().cs().size() > 1 ||
208              (next_token().cat() == catSpace &&
209               pos_ < tokens_.size() - 1 &&
210               tokens_[pos_ + 1].cat() == catNewline)))
211                 return true;
212         if (curr_token().cat() == catEscape && curr_token().cs() == "par")
213                 return true;
214         return false;
215 }
216
217
218 void Parser::skip_spaces(bool skip_comments)
219 {
220         // We just silently return if we have no more tokens.
221         // skip_spaces() should be callable at any time,
222         // the caller must check p::good() anyway.
223         while (good()) {
224                 get_token();
225                 if (isParagraph()) {
226                         putback();
227                         break;
228                 }
229                 if ( curr_token().cat() == catSpace ||
230                      curr_token().cat() == catNewline ||
231                     (curr_token().cat() == catComment && curr_token().cs().empty()))
232                         continue;
233                 if (skip_comments && curr_token().cat() == catComment)
234                         cerr << "  Ignoring comment: " << curr_token().asInput();
235                 else {
236                         putback();
237                         break;
238                 }
239         }
240 }
241
242
243 void Parser::unskip_spaces(bool skip_comments)
244 {
245         while (pos_ > 0) {
246                 if ( curr_token().cat() == catSpace ||
247                     (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
248                         putback();
249                 else if (skip_comments && curr_token().cat() == catComment) {
250                         // TODO: Get rid of this
251                         cerr << "Unignoring comment: " << curr_token().asInput();
252                         putback();
253                 }
254                 else
255                         break;
256         }
257 }
258
259
260 void Parser::putback()
261 {
262         --pos_;
263 }
264
265
266 bool Parser::good()
267 {
268         if (pos_ < tokens_.size())
269                 return true;
270         tokenize_one();
271         return pos_ < tokens_.size();
272 }
273
274
275 char Parser::getChar()
276 {
277         if (!good())
278                 error("The input stream is not well...");
279         return get_token().character();
280 }
281
282
283 Parser::Arg Parser::getFullArg(char left, char right)
284 {
285         skip_spaces(true);
286
287         // This is needed if a partial file ends with a command without arguments,
288         // e. g. \medskip
289         if (! good())
290                 return make_pair(false, string());
291
292         string result;
293         char c = getChar();
294
295         if (c != left) {
296                 putback();
297                 return make_pair(false, string());
298         } else
299                 while ((c = getChar()) != right && good()) {
300                         // Ignore comments
301                         if (curr_token().cat() == catComment) {
302                                 if (!curr_token().cs().empty())
303                                         cerr << "Ignoring comment: " << curr_token().asInput();
304                         }
305                         else
306                                 result += curr_token().asInput();
307                 }
308
309         return make_pair(true, result);
310 }
311
312
313 string Parser::getArg(char left, char right)
314 {
315         return getFullArg(left, right).second;
316 }
317
318
319 string Parser::getFullOpt()
320 {
321         Arg arg = getFullArg('[', ']');
322         if (arg.first)
323                 return '[' + arg.second + ']';
324         return string();
325 }
326
327
328 string Parser::getOpt()
329 {
330         string const res = getArg('[', ']');
331         return res.empty() ? string() : '[' + res + ']';
332 }
333
334
335 string Parser::getOptContent()
336 // the same as getOpt but without the brackets
337 {
338         string const res = getArg('[', ']');
339         return res.empty() ? string() : res;
340 }
341
342
343 string Parser::getFullParentheseArg()
344 {
345         Arg arg = getFullArg('(', ')');
346         if (arg.first)
347                 return '(' + arg.second + ')';
348         return string();
349 }
350
351
352 string const Parser::verbatimEnvironment(string const & name)
353 {
354         if (!good())
355                 return string();
356
357         ostringstream os;
358         for (Token t = get_token(); good(); t = get_token()) {
359                 if (t.cat() == catBegin) {
360                         putback();
361                         os << '{' << verbatim_item() << '}';
362                 } else if (t.asInput() == "\\begin") {
363                         string const env = getArg('{', '}');
364                         os << "\\begin{" << env << '}'
365                            << verbatimEnvironment(env)
366                            << "\\end{" << env << '}';
367                 } else if (t.asInput() == "\\end") {
368                         string const end = getArg('{', '}');
369                         if (end != name)
370                                 cerr << "\\end{" << end
371                                      << "} does not match \\begin{" << name
372                                      << "}." << endl;
373                         return os.str();
374                 } else
375                         os << t.asInput();
376         }
377         cerr << "unexpected end of input" << endl;
378         return os.str();
379 }
380
381
382 void Parser::tokenize_one()
383 {
384         catInit();
385         char_type c;
386         if (!is_.get(c)) 
387                 return;
388
389         switch (catcode(c)) {
390         case catSpace: {
391                 docstring s(1, c);
392                 while (is_.get(c) && catcode(c) == catSpace)
393                         s += c;
394                 if (catcode(c) != catSpace)
395                         is_.putback(c);
396                 push_back(Token(s, catSpace));
397                 break;
398         }
399                 
400         case catNewline: {
401                 ++lineno_;
402                 docstring s(1, getNewline(is_, c));
403                 while (is_.get(c) && catcode(c) == catNewline) {
404                         ++lineno_;
405                         s += getNewline(is_, c);
406                 }
407                 if (catcode(c) != catNewline)
408                         is_.putback(c);
409                 push_back(Token(s, catNewline));
410                 break;
411         }
412                 
413         case catComment: {
414                 // We don't treat "%\n" combinations here specially because
415                 // we want to preserve them in the preamble
416                 docstring s;
417                 while (is_.get(c) && catcode(c) != catNewline)
418                         s += c;
419                 // handle possible DOS line ending
420                 if (catcode(c) == catNewline)
421                         c = getNewline(is_, c);
422                 // Note: The '%' at the beginning and the '\n' at the end
423                 // of the comment are not stored.
424                 ++lineno_;
425                 push_back(Token(s, catComment));
426                 break;
427         }
428                 
429         case catEscape: {
430                 is_.get(c);
431                 if (!is_) {
432                         error("unexpected end of input");
433                 } else {
434                         docstring s(1, c);
435                         if (catcode(c) == catLetter) {
436                                 // collect letters
437                                 while (is_.get(c) && catcode(c) == catLetter)
438                                         s += c;
439                                 if (catcode(c) != catLetter)
440                                         is_.putback(c);
441                         }
442                         push_back(Token(s, catEscape));
443                 }
444                 break;
445         }
446                 
447         case catIgnore: {
448                 cerr << "ignoring a char: " << c << "\n";
449                 break;
450         }
451                 
452         default:
453                 push_back(Token(docstring(1, c), catcode(c)));
454         }
455         //cerr << tokens_.back();
456 }
457
458
459 void Parser::dump() const
460 {
461         cerr << "\nTokens: ";
462         for (unsigned i = 0; i < tokens_.size(); ++i) {
463                 if (i == pos_)
464                         cerr << " <#> ";
465                 cerr << tokens_[i];
466         }
467         cerr << " pos: " << pos_ << "\n";
468 }
469
470
471 void Parser::error(string const & msg)
472 {
473         cerr << "Line ~" << lineno_ << ":  parse error: " << msg << endl;
474         dump();
475         //exit(1);
476 }
477
478
479 string Parser::verbatimOption()
480 {
481         string res;
482         if (next_token().character() == '[') {
483                 Token t = get_token();
484                 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
485                         if (t.cat() == catBegin) {
486                                 putback();
487                                 res += '{' + verbatim_item() + '}';
488                         } else
489                                 res += t.cs();
490                 }
491         }
492         return res;
493 }
494
495
496 string Parser::verbatim_item()
497 {
498         if (!good())
499                 error("stream bad");
500         skip_spaces();
501         if (next_token().cat() == catBegin) {
502                 Token t = get_token(); // skip brace
503                 string res;
504                 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
505                         if (t.cat() == catBegin) {
506                                 putback();
507                                 res += '{' + verbatim_item() + '}';
508                         }
509                         else
510                                 res += t.asInput();
511                 }
512                 return res;
513         }
514         return get_token().asInput();
515 }
516
517
518 void Parser::reset()
519 {
520         pos_ = 0;
521 }
522
523
524 void Parser::setCatCode(char c, CatCode cat)
525 {
526         theCatcode[(unsigned char)c] = cat;
527 }
528
529
530 CatCode Parser::getCatCode(char c) const
531 {
532         return theCatcode[(unsigned char)c];
533 }
534
535
536 } // namespace lyx