]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.cpp
6b596289ca089d4b09dda110c15cb06d67ba94e0
[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 getNewline(idocstream & is, char 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         //cerr << "setting encoding to " << enc->iconvName()<<std::endl;
158         is_ << lyx::setEncoding(enc->iconvName());
159         encoding_latex_ = e;
160 }
161
162
163 void Parser::push_back(Token const & t)
164 {
165         tokens_.push_back(t);
166 }
167
168
169 Token const & Parser::prev_token() const
170 {
171         static const Token dummy;
172         return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
173 }
174
175
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 Token const & Parser::next_token()
184 {
185         static const Token dummy;
186         return good() ? tokens_[pos_] : dummy;
187 }
188
189
190 Token const & Parser::get_token()
191 {
192         static const Token dummy;
193         //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
194         return good() ? tokens_[pos_++] : dummy;
195 }
196
197
198 bool Parser::isParagraph()
199 {
200         // A new paragraph in TeX ist started
201         // - either by a newline, following any amount of whitespace
202         //   characters (including zero), and another newline
203         // - or the token \par
204         if (curr_token().cat() == catNewline &&
205             (curr_token().cs().size() > 1 ||
206              (next_token().cat() == catSpace &&
207               pos_ < tokens_.size() - 1 &&
208               tokens_[pos_ + 1].cat() == catNewline)))
209                 return true;
210         if (curr_token().cat() == catEscape && curr_token().cs() == "par")
211                 return true;
212         return false;
213 }
214
215
216 void Parser::skip_spaces(bool skip_comments)
217 {
218         // We just silently return if we have no more tokens.
219         // skip_spaces() should be callable at any time,
220         // the caller must check p::good() anyway.
221         while (good()) {
222                 get_token();
223                 if (isParagraph()) {
224                         putback();
225                         break;
226                 }
227                 if ( curr_token().cat() == catSpace ||
228                      curr_token().cat() == catNewline ||
229                     (curr_token().cat() == catComment && curr_token().cs().empty()))
230                         continue;
231                 if (skip_comments && curr_token().cat() == catComment)
232                         cerr << "  Ignoring comment: " << curr_token().asInput();
233                 else {
234                         putback();
235                         break;
236                 }
237         }
238 }
239
240
241 void Parser::unskip_spaces(bool skip_comments)
242 {
243         while (pos_ > 0) {
244                 if ( curr_token().cat() == catSpace ||
245                     (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
246                         putback();
247                 else if (skip_comments && curr_token().cat() == catComment) {
248                         // TODO: Get rid of this
249                         cerr << "Unignoring comment: " << curr_token().asInput();
250                         putback();
251                 }
252                 else
253                         break;
254         }
255 }
256
257
258 void Parser::putback()
259 {
260         --pos_;
261 }
262
263
264 bool Parser::good()
265 {
266         if (pos_ < tokens_.size())
267                 return true;
268         tokenize_one();
269         return pos_ < tokens_.size();
270 }
271
272
273 char Parser::getChar()
274 {
275         if (!good())
276                 error("The input stream is not well...");
277         return get_token().character();
278 }
279
280
281 Parser::Arg Parser::getFullArg(char left, char right)
282 {
283         skip_spaces(true);
284
285         // This is needed if a partial file ends with a command without arguments,
286         // e. g. \medskip
287         if (! good())
288                 return make_pair(false, string());
289
290         string result;
291         char c = getChar();
292
293         if (c != left) {
294                 putback();
295                 return make_pair(false, string());
296         } else
297                 while ((c = getChar()) != right && good()) {
298                         // Ignore comments
299                         if (curr_token().cat() == catComment) {
300                                 if (!curr_token().cs().empty())
301                                         cerr << "Ignoring comment: " << curr_token().asInput();
302                         }
303                         else
304                                 result += curr_token().asInput();
305                 }
306
307         return make_pair(true, result);
308 }
309
310
311 string Parser::getArg(char left, char right)
312 {
313         return getFullArg(left, right).second;
314 }
315
316
317 string Parser::getFullOpt()
318 {
319         Arg arg = getFullArg('[', ']');
320         if (arg.first)
321                 return '[' + arg.second + ']';
322         return string();
323 }
324
325
326 string Parser::getOpt()
327 {
328         string const res = getArg('[', ']');
329         return res.empty() ? string() : '[' + res + ']';
330 }
331
332
333 string Parser::getFullParentheseArg()
334 {
335         Arg arg = getFullArg('(', ')');
336         if (arg.first)
337                 return '(' + arg.second + ')';
338         return string();
339 }
340
341
342 string const Parser::verbatimEnvironment(string const & name)
343 {
344         if (!good())
345                 return string();
346
347         ostringstream os;
348         for (Token t = get_token(); good(); t = get_token()) {
349                 if (t.cat() == catBegin) {
350                         putback();
351                         os << '{' << verbatim_item() << '}';
352                 } else if (t.asInput() == "\\begin") {
353                         string const env = getArg('{', '}');
354                         os << "\\begin{" << env << '}'
355                            << verbatimEnvironment(env)
356                            << "\\end{" << env << '}';
357                 } else if (t.asInput() == "\\end") {
358                         string const end = getArg('{', '}');
359                         if (end != name)
360                                 cerr << "\\end{" << end
361                                      << "} does not match \\begin{" << name
362                                      << "}." << endl;
363                         return os.str();
364                 } else
365                         os << t.asInput();
366         }
367         cerr << "unexpected end of input" << endl;
368         return os.str();
369 }
370
371
372 void Parser::tokenize_one()
373 {
374         catInit();
375         char_type c;
376         if (!is_.get(c)) 
377                 return;
378
379         switch (catcode(c)) {
380         case catSpace: {
381                 docstring s(1, c);
382                 while (is_.get(c) && catcode(c) == catSpace)
383                         s += c;
384                 if (catcode(c) != catSpace)
385                         is_.putback(c);
386                 push_back(Token(s, catSpace));
387                 break;
388         }
389                 
390         case catNewline: {
391                 ++lineno_;
392                 docstring s(1, getNewline(is_, c));
393                 while (is_.get(c) && catcode(c) == catNewline) {
394                         ++lineno_;
395                         s += getNewline(is_, c);
396                 }
397                 if (catcode(c) != catNewline)
398                         is_.putback(c);
399                 push_back(Token(s, catNewline));
400                 break;
401         }
402                 
403         case catComment: {
404                 // We don't treat "%\n" combinations here specially because
405                 // we want to preserve them in the preamble
406                 docstring s;
407                 while (is_.get(c) && catcode(c) != catNewline)
408                         s += c;
409                 // handle possible DOS line ending
410                 if (catcode(c) == catNewline)
411                         c = getNewline(is_, c);
412                 // Note: The '%' at the beginning and the '\n' at the end
413                 // of the comment are not stored.
414                 ++lineno_;
415                 push_back(Token(s, catComment));
416                 break;
417         }
418                 
419         case catEscape: {
420                 is_.get(c);
421                 if (!is_) {
422                         error("unexpected end of input");
423                 } else {
424                         docstring s(1, c);
425                         if (catcode(c) == catLetter) {
426                                 // collect letters
427                                 while (is_.get(c) && catcode(c) == catLetter)
428                                         s += c;
429                                 if (catcode(c) != catLetter)
430                                         is_.putback(c);
431                         }
432                         push_back(Token(s, catEscape));
433                 }
434                 break;
435         }
436                 
437         case catIgnore: {
438                 cerr << "ignoring a char: " << c << "\n";
439                 break;
440         }
441                 
442         default:
443                 push_back(Token(docstring(1, c), catcode(c)));
444         }
445         //cerr << tokens_.back();
446 }
447
448
449 void Parser::dump() const
450 {
451         cerr << "\nTokens: ";
452         for (unsigned i = 0; i < tokens_.size(); ++i) {
453                 if (i == pos_)
454                         cerr << " <#> ";
455                 cerr << tokens_[i];
456         }
457         cerr << " pos: " << pos_ << "\n";
458 }
459
460
461 void Parser::error(string const & msg)
462 {
463         cerr << "Line ~" << lineno_ << ":  parse error: " << msg << endl;
464         dump();
465         //exit(1);
466 }
467
468
469 string Parser::verbatimOption()
470 {
471         string res;
472         if (next_token().character() == '[') {
473                 Token t = get_token();
474                 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
475                         if (t.cat() == catBegin) {
476                                 putback();
477                                 res += '{' + verbatim_item() + '}';
478                         } else
479                                 res += t.asString();
480                 }
481         }
482         return res;
483 }
484
485
486 string Parser::verbatim_item()
487 {
488         if (!good())
489                 error("stream bad");
490         skip_spaces();
491         if (next_token().cat() == catBegin) {
492                 Token t = get_token(); // skip brace
493                 string res;
494                 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
495                         if (t.cat() == catBegin) {
496                                 putback();
497                                 res += '{' + verbatim_item() + '}';
498                         }
499                         else
500                                 res += t.asInput();
501                 }
502                 return res;
503         }
504         return get_token().asInput();
505 }
506
507
508 void Parser::reset()
509 {
510         pos_ = 0;
511 }
512
513
514 void Parser::setCatCode(char c, CatCode cat)
515 {
516         theCatcode[(unsigned char)c] = cat;
517 }
518
519
520 CatCode Parser::getCatCode(char c) const
521 {
522         return theCatcode[(unsigned char)c];
523 }
524
525
526 } // namespace lyx