]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.cpp
Kornel's gcc compile fix.
[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::asString() const
114 {
115         return cs_;
116 }
117
118
119 string Token::asInput() const
120 {
121         if (cat_ == catComment)
122                 return '%' + cs_ + '\n';
123         if (cat_ == catEscape)
124                 return '\\' + cs_;
125         return cs_;
126 }
127
128
129 //
130 // Parser
131 //
132
133
134 Parser::Parser(idocstream & is)
135         : lineno_(0), pos_(0), iss_(0), is_(is), encoding_latex_("utf8")
136 {
137 }
138
139
140 Parser::Parser(string const & s)
141         : lineno_(0), pos_(0), 
142           iss_(new idocstringstream(from_utf8(s))), is_(*iss_), 
143           encoding_latex_("utf8")
144 {
145 }
146
147
148 Parser::~Parser()
149 {
150         delete iss_;
151 }
152
153
154 void Parser::setEncoding(std::string const & e)
155 {
156         Encoding const * enc = encodings.fromLaTeXName(e);
157         if (!enc) {
158                 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
159                 return;
160         }
161         //cerr << "setting encoding to " << enc->iconvName() << std::endl;
162         is_ << lyx::setEncoding(enc->iconvName());
163         encoding_latex_ = e;
164 }
165
166
167 void Parser::push_back(Token const & t)
168 {
169         tokens_.push_back(t);
170 }
171
172
173 // We return a copy here because the tokens_ vector may get reallocated
174 Token const Parser::prev_token() const
175 {
176         static const Token dummy;
177         return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
178 }
179
180
181 // We return a copy here because the tokens_ vector may get reallocated
182 Token const Parser::curr_token() const
183 {
184         static const Token dummy;
185         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
186 }
187
188
189 // We return a copy here because the tokens_ vector may get reallocated
190 Token const Parser::next_token()
191 {
192         static const Token dummy;
193         return good() ? tokens_[pos_] : dummy;
194 }
195
196
197 // We return a copy here because the tokens_ vector may get reallocated
198 Token const Parser::get_token()
199 {
200         static const Token dummy;
201         //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
202         return good() ? tokens_[pos_++] : dummy;
203 }
204
205
206 bool Parser::isParagraph()
207 {
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;
221 }
222
223
224 void Parser::skip_spaces(bool skip_comments)
225 {
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;
234                 }
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;
244                 }
245         }
246 }
247
248
249 void Parser::unskip_spaces(bool skip_comments)
250 {
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();
259                 }
260                 else
261                         break;
262         }
263 }
264
265
266 void Parser::putback()
267 {
268         --pos_;
269 }
270
271
272 bool Parser::good()
273 {
274         if (pos_ < tokens_.size())
275                 return true;
276         tokenize_one();
277         return pos_ < tokens_.size();
278 }
279
280
281 char Parser::getChar()
282 {
283         if (!good())
284                 error("The input stream is not well...");
285         return get_token().character();
286 }
287
288
289 Parser::Arg Parser::getFullArg(char left, char right)
290 {
291         skip_spaces(true);
292
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());
297
298         string result;
299         char c = getChar();
300
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();
310                         }
311                         else
312                                 result += curr_token().asInput();
313                 }
314
315         return make_pair(true, result);
316 }
317
318
319 string Parser::getArg(char left, char right)
320 {
321         return getFullArg(left, right).second;
322 }
323
324
325 string Parser::getFullOpt()
326 {
327         Arg arg = getFullArg('[', ']');
328         if (arg.first)
329                 return '[' + arg.second + ']';
330         return string();
331 }
332
333
334 string Parser::getOpt()
335 {
336         string const res = getArg('[', ']');
337         return res.empty() ? string() : '[' + res + ']';
338 }
339
340
341 string Parser::getOptContent()
342 // the same as getOpt but without the brackets
343 {
344         string const res = getArg('[', ']');
345         return res.empty() ? string() : res;
346 }
347
348
349 string Parser::getFullParentheseArg()
350 {
351         Arg arg = getFullArg('(', ')');
352         if (arg.first)
353                 return '(' + arg.second + ')';
354         return string();
355 }
356
357
358 string const Parser::verbatimEnvironment(string const & name)
359 {
360         if (!good())
361                 return string();
362
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();
382         }
383         cerr << "unexpected end of input" << endl;
384         return os.str();
385 }
386
387
388 void Parser::tokenize_one()
389 {
390         catInit();
391         char_type c;
392         if (!is_.get(c)) 
393                 return;
394
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;
404         }
405                 
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);
412                 }
413                 if (catcode(c) != catNewline)
414                         is_.putback(c);
415                 push_back(Token(s, catNewline));
416                 break;
417         }
418                 
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;
433         }
434                 
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);
447                         }
448                         push_back(Token(s, catEscape));
449                 }
450                 break;
451         }
452                 
453         case catIgnore: {
454                 cerr << "ignoring a char: " << c << "\n";
455                 break;
456         }
457                 
458         default:
459                 push_back(Token(docstring(1, c), catcode(c)));
460         }
461         //cerr << tokens_.back();
462 }
463
464
465 void Parser::dump() const
466 {
467         cerr << "\nTokens: ";
468         for (unsigned i = 0; i < tokens_.size(); ++i) {
469                 if (i == pos_)
470                         cerr << " <#> ";
471                 cerr << tokens_[i];
472         }
473         cerr << " pos: " << pos_ << "\n";
474 }
475
476
477 void Parser::error(string const & msg)
478 {
479         cerr << "Line ~" << lineno_ << ":  parse error: " << msg << endl;
480         dump();
481         //exit(1);
482 }
483
484
485 string Parser::verbatimOption()
486 {
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();
496                 }
497         }
498         return res;
499 }
500
501
502 string Parser::verbatim_item()
503 {
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() + '}';
514                         }
515                         else
516                                 res += t.asInput();
517                 }
518                 return res;
519         }
520         return get_token().asInput();
521 }
522
523
524 void Parser::reset()
525 {
526         pos_ = 0;
527 }
528
529
530 void Parser::setCatCode(char c, CatCode cat)
531 {
532         theCatcode[(unsigned char)c] = cat;
533 }
534
535
536 CatCode Parser::getCatCode(char c) const
537 {
538         return theCatcode[(unsigned char)c];
539 }
540
541
542 } // namespace lyx