]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.cpp
Fix "stray '}' in text" warnings: When parsing with FLAG_ITEM the braces need
[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 #include "support/textutils.h"
16
17 #include <iostream>
18
19 using namespace std;
20
21 namespace lyx {
22
23 namespace {
24
25 CatCode theCatcode[256];
26
27 void catInit()
28 {
29         static bool init_done = false;
30         if (init_done) 
31                 return;
32         init_done = true;
33
34         fill(theCatcode, theCatcode + 256, catOther);
35         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
36         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
37
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;
53
54         // This is wrong!
55         theCatcode[int('@')]  = catLetter;
56 }
57
58 /*!
59  * Translate a line ending to '\n'.
60  * \p c must have catcode catNewline, and it must be the last character read
61  * from \p is.
62  */
63 char_type getNewline(idocstream & is, char_type c)
64 {
65         // we have to handle 3 different line endings:
66         // - UNIX (\n)
67         // - MAC  (\r)
68         // - DOS  (\r\n)
69         if (c == '\r') {
70                 // MAC or DOS
71                 char_type wc;
72                 if (is.get(wc) && wc != '\n') {
73                         // MAC
74                         is.putback(wc);
75                 }
76                 return '\n';
77         }
78         // UNIX
79         return c;
80 }
81
82 CatCode catcode(char_type c)
83 {
84         if (c < 256)
85                 return theCatcode[(unsigned char)c];
86         return catOther;
87 }
88
89 }
90
91
92 //
93 // Token
94 //
95
96 ostream & operator<<(ostream & os, Token const & t)
97 {
98         if (t.cat() == catComment)
99                 os << '%' << t.cs() << '\n';
100         else if (t.cat() == catSpace)
101                 os << t.cs();
102         else if (t.cat() == catEscape)
103                 os << '\\' << t.cs() << ' ';
104         else if (t.cat() == catLetter)
105                 os << t.cs();
106         else if (t.cat() == catNewline)
107                 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
108         else
109                 os << '[' << t.cs() << ',' << t.cat() << ']';
110         return os;
111 }
112
113
114 string Token::asInput() const
115 {
116         if (cat_ == catComment)
117                 return '%' + cs_ + '\n';
118         if (cat_ == catEscape)
119                 return '\\' + cs_;
120         return cs_;
121 }
122
123
124 bool Token::isAlnumASCII() const
125 {
126         return cat_ == catLetter ||
127                (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
128 }
129
130
131 #ifdef FILEDEBUG
132 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
133 {
134         char sep = ' ';
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 = '|'; }
150         os << "\n";
151 }
152 #endif
153
154
155 //
156 // Parser
157 //
158
159
160 Parser::Parser(idocstream & is)
161         : lineno_(0), pos_(0), iss_(0), is_(is), encoding_latex_("utf8")
162 {
163 }
164
165
166 Parser::Parser(string const & s)
167         : lineno_(0), pos_(0), 
168           iss_(new idocstringstream(from_utf8(s))), is_(*iss_), 
169           encoding_latex_("utf8")
170 {
171 }
172
173
174 Parser::~Parser()
175 {
176         delete iss_;
177 }
178
179
180 void Parser::setEncoding(std::string const & e)
181 {
182         Encoding const * enc = encodings.fromLaTeXName(e);
183         if (!enc) {
184                 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
185                 return;
186         }
187         //cerr << "setting encoding to " << enc->iconvName() << std::endl;
188         is_ << lyx::setEncoding(enc->iconvName());
189         encoding_latex_ = e;
190 }
191
192
193 void Parser::push_back(Token const & t)
194 {
195         tokens_.push_back(t);
196 }
197
198
199 // We return a copy here because the tokens_ vector may get reallocated
200 Token const Parser::prev_token() const
201 {
202         static const Token dummy;
203         return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
204 }
205
206
207 // We return a copy here because the tokens_ vector may get reallocated
208 Token const Parser::curr_token() const
209 {
210         static const Token dummy;
211         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
212 }
213
214
215 // We return a copy here because the tokens_ vector may get reallocated
216 Token const Parser::next_token()
217 {
218         static const Token dummy;
219         return good() ? tokens_[pos_] : dummy;
220 }
221
222
223 // We return a copy here because the tokens_ vector may get reallocated
224 Token const Parser::get_token()
225 {
226         static const Token dummy;
227         //cerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
228         return good() ? tokens_[pos_++] : dummy;
229 }
230
231
232 bool Parser::isParagraph()
233 {
234         // A new paragraph in TeX ist started
235         // - either by a newline, following any amount of whitespace
236         //   characters (including zero), and another newline
237         // - or the token \par
238         if (curr_token().cat() == catNewline &&
239             (curr_token().cs().size() > 1 ||
240              (next_token().cat() == catSpace &&
241               pos_ < tokens_.size() - 1 &&
242               tokens_[pos_ + 1].cat() == catNewline)))
243                 return true;
244         if (curr_token().cat() == catEscape && curr_token().cs() == "par")
245                 return true;
246         return false;
247 }
248
249
250 bool Parser::skip_spaces(bool skip_comments)
251 {
252         // We just silently return if we have no more tokens.
253         // skip_spaces() should be callable at any time,
254         // the caller must check p::good() anyway.
255         bool skipped = false;
256         while (good()) {
257                 get_token();
258                 if (isParagraph()) {
259                         putback();
260                         break;
261                 }
262                 if (curr_token().cat() == catSpace ||
263                     curr_token().cat() == catNewline) {
264                         skipped = true;
265                         continue;
266                 }
267                 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
268                         continue;
269                 if (skip_comments && curr_token().cat() == catComment) {
270                         // If positions_ is not empty we are doing some kind
271                         // of look ahead
272                         if (!positions_.empty())
273                                 cerr << "  Ignoring comment: "
274                                      << curr_token().asInput();
275                 } else {
276                         putback();
277                         break;
278                 }
279         }
280         return skipped;
281 }
282
283
284 void Parser::unskip_spaces(bool skip_comments)
285 {
286         while (pos_ > 0) {
287                 if ( curr_token().cat() == catSpace ||
288                     (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
289                         putback();
290                 else if (skip_comments && curr_token().cat() == catComment) {
291                         // TODO: Get rid of this
292                         // If positions_ is not empty we are doing some kind
293                         // of look ahead
294                         if (!positions_.empty())
295                                 cerr << "Unignoring comment: "
296                                      << curr_token().asInput();
297                         putback();
298                 }
299                 else
300                         break;
301         }
302 }
303
304
305 void Parser::putback()
306 {
307         --pos_;
308 }
309
310
311 void Parser::pushPosition()
312 {
313         positions_.push_back(pos_);
314 }
315
316
317 void Parser::popPosition()
318 {
319         pos_ = positions_.back();
320         positions_.pop_back();
321 }
322
323
324 bool Parser::good()
325 {
326         if (pos_ < tokens_.size())
327                 return true;
328         tokenize_one();
329         return pos_ < tokens_.size();
330 }
331
332
333 char Parser::getChar()
334 {
335         if (!good())
336                 error("The input stream is not well...");
337         return get_token().character();
338 }
339
340
341 bool Parser::hasOpt()
342 {
343         // An optional argument can occur in any of the following forms:
344         // - \foo[bar]
345         // - \foo [bar]
346         // - \foo
347         //   [bar]
348         // - \foo %comment
349         //   [bar]
350
351         // remember current position
352         unsigned int oldpos = pos_;
353         // skip spaces and comments
354         while (good()) {
355                 get_token();
356                 if (isParagraph()) {
357                         putback();
358                         break;
359                 }
360                 if (curr_token().cat() == catSpace ||
361                     curr_token().cat() == catNewline ||
362                     curr_token().cat() == catComment)
363                         continue;
364                 putback();
365                 break;
366         }
367         bool const retval = (next_token().asInput() == "[");
368         pos_ = oldpos;
369         return retval;
370 }
371
372
373 Parser::Arg Parser::getFullArg(char left, char right)
374 {
375         skip_spaces(true);
376
377         // This is needed if a partial file ends with a command without arguments,
378         // e. g. \medskip
379         if (! good())
380                 return make_pair(false, string());
381
382         string result;
383         char c = getChar();
384
385         if (c != left) {
386                 putback();
387                 return make_pair(false, string());
388         } else
389                 while ((c = getChar()) != right && good()) {
390                         // Ignore comments
391                         if (curr_token().cat() == catComment) {
392                                 if (!curr_token().cs().empty())
393                                         cerr << "Ignoring comment: " << curr_token().asInput();
394                         }
395                         else
396                                 result += curr_token().asInput();
397                 }
398
399         return make_pair(true, result);
400 }
401
402
403 string Parser::getArg(char left, char right)
404 {
405         return getFullArg(left, right).second;
406 }
407
408
409 string Parser::getFullOpt(bool keepws)
410 {
411         Arg arg = getFullArg('[', ']');
412         if (arg.first)
413                 return '[' + arg.second + ']';
414         if (keepws)
415                 unskip_spaces(true);
416         return string();
417 }
418
419
420 string Parser::getOpt(bool keepws)
421 {
422         string const res = getArg('[', ']');
423         if (res.empty()) {
424                 if (keepws)
425                         unskip_spaces(true);
426                 return string();
427         }
428         return '[' + res + ']';
429 }
430
431
432 string Parser::getFullParentheseArg()
433 {
434         Arg arg = getFullArg('(', ')');
435         if (arg.first)
436                 return '(' + arg.second + ')';
437         return string();
438 }
439
440
441 string const Parser::verbatimEnvironment(string const & name)
442 {
443         if (!good())
444                 return string();
445
446         ostringstream os;
447         for (Token t = get_token(); good(); t = get_token()) {
448                 if (t.cat() == catBegin) {
449                         putback();
450                         os << '{' << verbatim_item() << '}';
451                 } else if (t.asInput() == "\\begin") {
452                         string const env = getArg('{', '}');
453                         os << "\\begin{" << env << '}'
454                            << verbatimEnvironment(env)
455                            << "\\end{" << env << '}';
456                 } else if (t.asInput() == "\\end") {
457                         string const end = getArg('{', '}');
458                         if (end != name)
459                                 cerr << "\\end{" << end
460                                      << "} does not match \\begin{" << name
461                                      << "}." << endl;
462                         return os.str();
463                 } else
464                         os << t.asInput();
465         }
466         cerr << "unexpected end of input" << endl;
467         return os.str();
468 }
469
470
471 void Parser::tokenize_one()
472 {
473         catInit();
474         char_type c;
475         if (!is_.get(c)) 
476                 return;
477
478         switch (catcode(c)) {
479         case catSpace: {
480                 docstring s(1, c);
481                 while (is_.get(c) && catcode(c) == catSpace)
482                         s += c;
483                 if (catcode(c) != catSpace)
484                         is_.putback(c);
485                 push_back(Token(s, catSpace));
486                 break;
487         }
488                 
489         case catNewline: {
490                 ++lineno_;
491                 docstring s(1, getNewline(is_, c));
492                 while (is_.get(c) && catcode(c) == catNewline) {
493                         ++lineno_;
494                         s += getNewline(is_, c);
495                 }
496                 if (catcode(c) != catNewline)
497                         is_.putback(c);
498                 push_back(Token(s, catNewline));
499                 break;
500         }
501                 
502         case catComment: {
503                 // We don't treat "%\n" combinations here specially because
504                 // we want to preserve them in the preamble
505                 docstring s;
506                 while (is_.get(c) && catcode(c) != catNewline)
507                         s += c;
508                 // handle possible DOS line ending
509                 if (catcode(c) == catNewline)
510                         c = getNewline(is_, c);
511                 // Note: The '%' at the beginning and the '\n' at the end
512                 // of the comment are not stored.
513                 ++lineno_;
514                 push_back(Token(s, catComment));
515                 break;
516         }
517                 
518         case catEscape: {
519                 is_.get(c);
520                 if (!is_) {
521                         error("unexpected end of input");
522                 } else {
523                         docstring s(1, c);
524                         if (catcode(c) == catLetter) {
525                                 // collect letters
526                                 while (is_.get(c) && catcode(c) == catLetter)
527                                         s += c;
528                                 if (catcode(c) != catLetter)
529                                         is_.putback(c);
530                         }
531                         push_back(Token(s, catEscape));
532                 }
533                 break;
534         }
535                 
536         case catIgnore: {
537                 cerr << "ignoring a char: " << c << "\n";
538                 break;
539         }
540                 
541         default:
542                 push_back(Token(docstring(1, c), catcode(c)));
543         }
544         //cerr << tokens_.back();
545 }
546
547
548 void Parser::dump() const
549 {
550         cerr << "\nTokens: ";
551         for (unsigned i = 0; i < tokens_.size(); ++i) {
552                 if (i == pos_)
553                         cerr << " <#> ";
554                 cerr << tokens_[i];
555         }
556         cerr << " pos: " << pos_ << "\n";
557 }
558
559
560 void Parser::error(string const & msg)
561 {
562         cerr << "Line ~" << lineno_ << ":  parse error: " << msg << endl;
563         dump();
564         //exit(1);
565 }
566
567
568 string Parser::verbatimOption()
569 {
570         string res;
571         if (next_token().character() == '[') {
572                 Token t = get_token();
573                 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
574                         if (t.cat() == catBegin) {
575                                 putback();
576                                 res += '{' + verbatim_item() + '}';
577                         } else
578                                 res += t.cs();
579                 }
580         }
581         return res;
582 }
583
584
585 string Parser::verbatim_item()
586 {
587         if (!good())
588                 error("stream bad");
589         skip_spaces();
590         if (next_token().cat() == catBegin) {
591                 Token t = get_token(); // skip brace
592                 string res;
593                 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
594                         if (t.cat() == catBegin) {
595                                 putback();
596                                 res += '{' + verbatim_item() + '}';
597                         }
598                         else
599                                 res += t.asInput();
600                 }
601                 return res;
602         }
603         return get_token().asInput();
604 }
605
606
607 void Parser::reset()
608 {
609         pos_ = 0;
610 }
611
612
613 void Parser::setCatCode(char c, CatCode cat)
614 {
615         theCatcode[(unsigned char)c] = cat;
616 }
617
618
619 CatCode Parser::getCatCode(char c) const
620 {
621         return theCatcode[(unsigned char)c];
622 }
623
624
625 } // namespace lyx