]> git.lyx.org Git - lyx.git/blob - src/tex2lyx/Parser.cpp
ec63b77da83e7c063724746427fa64be8c0c127e
[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/lstrings.h"
16 #include "support/textutils.h"
17
18 #include <iostream>
19
20 using namespace std;
21 using namespace lyx::support;
22
23 namespace lyx {
24
25 namespace {
26
27 /*!
28  * Translate a line ending to '\n'.
29  * \p c must have catcode catNewline, and it must be the last character read
30  * from \p is.
31  */
32 char_type getNewline(iparserdocstream & is, char_type c)
33 {
34         // we have to handle 3 different line endings:
35         // - UNIX (\n)
36         // - MAC  (\r)
37         // - DOS  (\r\n)
38         if (c == '\r') {
39                 // MAC or DOS
40                 char_type wc;
41                 if (is.get(wc) && wc != '\n') {
42                         // MAC
43                         is.putback(wc);
44                 }
45                 return '\n';
46         }
47         // UNIX
48         return c;
49 }
50
51 } // namespace
52
53 //
54 // Token
55 //
56
57 ostream & operator<<(ostream & os, Token const & t)
58 {
59         if (t.cat() == catComment)
60                 os << '%' << t.cs() << '\n';
61         else if (t.cat() == catSpace)
62                 os << t.cs();
63         else if (t.cat() == catEscape)
64                 os << '\\' << t.cs() << ' ';
65         else if (t.cat() == catLetter)
66                 os << t.cs();
67         else if (t.cat() == catNewline)
68                 os << "[" << t.cs().size() << "\\n," << t.cat() << "]\n";
69         else
70                 os << '[' << t.cs() << ',' << t.cat() << ']';
71         return os;
72 }
73
74
75 string Token::asInput() const
76 {
77         if (cat_ == catComment)
78                 return '%' + cs_ + '\n';
79         if (cat_ == catEscape)
80                 return '\\' + cs_;
81         return cs_;
82 }
83
84
85 bool Token::isAlnumASCII() const
86 {
87         return cat_ == catLetter ||
88                (cat_ == catOther && cs_.length() == 1 && isDigitASCII(cs_[0]));
89 }
90
91
92 #ifdef FILEDEBUG
93 void debugToken(std::ostream & os, Token const & t, unsigned int flags)
94 {
95         char sep = ' ';
96         os << "t: " << t << " flags: " << flags;
97         if (flags & FLAG_BRACE_LAST) { os << sep << "BRACE_LAST"; sep = '|'; }
98         if (flags & FLAG_RIGHT     ) { os << sep << "RIGHT"     ; sep = '|'; }
99         if (flags & FLAG_END       ) { os << sep << "END"       ; sep = '|'; }
100         if (flags & FLAG_BRACK_LAST) { os << sep << "BRACK_LAST"; sep = '|'; }
101         if (flags & FLAG_TEXTMODE  ) { os << sep << "TEXTMODE"  ; sep = '|'; }
102         if (flags & FLAG_ITEM      ) { os << sep << "ITEM"      ; sep = '|'; }
103         if (flags & FLAG_LEAVE     ) { os << sep << "LEAVE"     ; sep = '|'; }
104         if (flags & FLAG_SIMPLE    ) { os << sep << "SIMPLE"    ; sep = '|'; }
105         if (flags & FLAG_EQUATION  ) { os << sep << "EQUATION"  ; sep = '|'; }
106         if (flags & FLAG_SIMPLE2   ) { os << sep << "SIMPLE2"   ; sep = '|'; }
107         if (flags & FLAG_OPTION    ) { os << sep << "OPTION"    ; sep = '|'; }
108         if (flags & FLAG_BRACED    ) { os << sep << "BRACED"    ; sep = '|'; }
109         if (flags & FLAG_CELL      ) { os << sep << "CELL"      ; sep = '|'; }
110         if (flags & FLAG_TABBING   ) { os << sep << "TABBING"   ; sep = '|'; }
111         os << "\n";
112 }
113 #endif
114
115
116 //
117 // Wrapper
118 //
119
120 void iparserdocstream::setEncoding(std::string const & e)
121 {
122         is_ << lyx::setEncoding(e);
123 }
124
125
126 void iparserdocstream::putback(char_type c)
127 {
128         s_ = c + s_;
129 }
130
131
132 void iparserdocstream::putback(docstring s)
133 {
134         s_ = s + s_;
135 }
136
137
138 iparserdocstream & iparserdocstream::get(char_type &c)
139 {
140         if (s_.empty())
141                 is_.get(c);
142         else {
143                 //cerr << "unparsed: " << to_utf8(s_) <<endl;
144                 c = s_[0];
145                 s_.erase(0,1);
146         }
147         return *this;
148 }
149
150
151 //
152 // Parser
153 //
154
155
156 Parser::Parser(idocstream & is, std::string const & fixedenc)
157         : lineno_(0), pos_(0), iss_(0), is_(is),
158           encoding_iconv_(fixedenc.empty() ? "UTF-8" : fixedenc),
159           theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
160           fixed_enc_(!fixedenc.empty())
161 {
162         if (fixed_enc_)
163                 is_.setEncoding(fixedenc);
164         catInit();
165 }
166
167
168 Parser::Parser(string const & s)
169         : lineno_(0), pos_(0),
170           iss_(new idocstringstream(from_utf8(s))), is_(*iss_),
171           encoding_iconv_("UTF-8"),
172           theCatcodesType_(NORMAL_CATCODES), curr_cat_(UNDECIDED_CATCODES),
173           // An idocstringstream can not change the encoding
174           fixed_enc_(true)
175 {
176         catInit();
177 }
178
179
180 Parser::~Parser()
181 {
182         delete iss_;
183 }
184
185
186 void Parser::deparse()
187 {
188         string s;
189         for(size_type i = pos_ ; i < tokens_.size() ; ++i) {
190                 s += tokens_[i].asInput();
191         }
192         is_.putback(from_utf8(s));
193         tokens_.erase(tokens_.begin() + pos_, tokens_.end());
194         // make sure that next token is read
195         tokenize_one();
196 }
197
198
199 bool Parser::setEncoding(std::string const & e, int const & p)
200 {
201         // We may (and need to) use unsafe encodings here: Since the text is
202         // converted to unicode while reading from is_, we never see text in
203         // the original encoding of the parser, but operate on utf8 strings
204         // instead. Therefore, we cannot misparse high bytes as {, } or \\.
205         Encoding const * const enc = encodings.fromLaTeXName(e, p, true);
206         if (!enc) {
207                 cerr << "Unknown encoding " << e << ". Ignoring." << std::endl;
208                 return false;
209         }
210         return setEncoding(enc->iconvName());
211 }
212
213
214 void Parser::catInit()
215 {
216         if (curr_cat_ == theCatcodesType_)
217                 return;
218         curr_cat_ = theCatcodesType_;
219
220         fill(theCatcode_, theCatcode_ + 256, catOther);
221         fill(theCatcode_ + 'a', theCatcode_ + 'z' + 1, catLetter);
222         fill(theCatcode_ + 'A', theCatcode_ + 'Z' + 1, catLetter);
223         // This is wrong!
224         theCatcode_[int('@')]  = catLetter;
225
226         if (theCatcodesType_ == NORMAL_CATCODES) {
227                 theCatcode_[int('\\')] = catEscape;
228                 theCatcode_[int('{')]  = catBegin;
229                 theCatcode_[int('}')]  = catEnd;
230                 theCatcode_[int('$')]  = catMath;
231                 theCatcode_[int('&')]  = catAlign;
232                 theCatcode_[int('\n')] = catNewline;
233                 theCatcode_[int('#')]  = catParameter;
234                 theCatcode_[int('^')]  = catSuper;
235                 theCatcode_[int('_')]  = catSub;
236                 theCatcode_[0x7f]      = catIgnore;
237                 theCatcode_[int(' ')]  = catSpace;
238                 theCatcode_[int('\t')] = catSpace;
239                 theCatcode_[int('\r')] = catNewline;
240                 theCatcode_[int('~')]  = catActive;
241                 theCatcode_[int('%')]  = catComment;
242         }
243 }
244
245 CatCode Parser::catcode(char_type c) const
246 {
247         if (c < 256)
248                 return theCatcode_[(unsigned char)c];
249         return catOther;
250 }
251
252
253 void Parser::setCatcode(char c, CatCode cat)
254 {
255         theCatcode_[(unsigned char)c] = cat;
256         deparse();
257 }
258
259
260 void Parser::setCatcodes(cat_type t)
261 {
262         theCatcodesType_ = t;
263         deparse();
264 }
265
266
267 bool Parser::setEncoding(std::string const & e)
268 {
269         //cerr << "setting encoding to " << e << std::endl;
270         encoding_iconv_ = e;
271         // If the encoding is fixed, we must not change the stream encoding
272         // (because the whole input uses that encoding, e.g. if it comes from
273         // the clipboard). We still need to track the original encoding in
274         // encoding_iconv_, so that the generated output is correct.
275         if (!fixed_enc_)
276                 is_.setEncoding(e);
277         return true;
278 }
279
280
281 void Parser::push_back(Token const & t)
282 {
283         tokens_.push_back(t);
284 }
285
286
287 // We return a copy here because the tokens_ vector may get reallocated
288 Token const Parser::prev_token() const
289 {
290         static const Token dummy;
291         return pos_ > 1 ? tokens_[pos_ - 2] : dummy;
292 }
293
294
295 // We return a copy here because the tokens_ vector may get reallocated
296 Token const Parser::curr_token() const
297 {
298         static const Token dummy;
299         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
300 }
301
302
303 // We return a copy here because the tokens_ vector may get reallocated
304 Token const Parser::next_token()
305 {
306         static const Token dummy;
307         if (!good())
308                 return dummy;
309         if (pos_ >= tokens_.size())
310                 tokenize_one();
311         return pos_ < tokens_.size() ? tokens_[pos_] : dummy;
312 }
313
314
315 // We return a copy here because the tokens_ vector may get reallocated
316 Token const Parser::next_next_token()
317 {
318         static const Token dummy;
319         if (!good())
320                 return dummy;
321         // If tokenize_one() has not been called after the last get_token() we
322         // need to tokenize two more tokens.
323         if (pos_ >= tokens_.size())
324                 tokenize_one();
325         if (pos_ + 1 >= tokens_.size())
326                 tokenize_one();
327         return pos_ + 1 < tokens_.size() ? tokens_[pos_ + 1] : dummy;
328 }
329
330
331 // We return a copy here because the tokens_ vector may get reallocated
332 Token const Parser::get_token()
333 {
334         static const Token dummy;
335         if (!good())
336                 return dummy;
337         if (pos_ >= tokens_.size()) {
338                 tokenize_one();
339                 if (pos_ >= tokens_.size())
340                         return dummy;
341         }
342         // cerr << "looking at token " << tokens_[pos_]
343         //      << " pos: " << pos_ << '\n';
344         return tokens_[pos_++];
345 }
346
347
348 bool Parser::isParagraph()
349 {
350         // A new paragraph in TeX ist started
351         // - either by a newline, following any amount of whitespace
352         //   characters (including zero), and another newline
353         // - or the token \par
354         if (curr_token().cat() == catNewline &&
355             (curr_token().cs().size() > 1 ||
356              (next_token().cat() == catSpace &&
357               next_next_token().cat() == catNewline)))
358                 return true;
359         if (curr_token().cat() == catEscape && curr_token().cs() == "par")
360                 return true;
361         return false;
362 }
363
364
365 bool Parser::skip_spaces(bool skip_comments)
366 {
367         // We just silently return if we have no more tokens.
368         // skip_spaces() should be callable at any time,
369         // the caller must check p::good() anyway.
370         bool skipped = false;
371         while (good()) {
372                 get_token();
373                 if (isParagraph()) {
374                         putback();
375                         break;
376                 }
377                 if (curr_token().cat() == catSpace ||
378                     curr_token().cat() == catNewline) {
379                         skipped = true;
380                         continue;
381                 }
382                 if ((curr_token().cat() == catComment && curr_token().cs().empty()))
383                         continue;
384                 if (skip_comments && curr_token().cat() == catComment) {
385                         // If positions_ is not empty we are doing some kind
386                         // of look ahead
387                         if (!positions_.empty())
388                                 cerr << "  Ignoring comment: "
389                                      << curr_token().asInput();
390                 } else {
391                         putback();
392                         break;
393                 }
394         }
395         return skipped;
396 }
397
398
399 void Parser::unskip_spaces(bool skip_comments)
400 {
401         while (pos_ > 0) {
402                 if ( curr_token().cat() == catSpace ||
403                     (curr_token().cat() == catNewline && curr_token().cs().size() == 1))
404                         putback();
405                 else if (skip_comments && curr_token().cat() == catComment) {
406                         // TODO: Get rid of this
407                         // If positions_ is not empty we are doing some kind
408                         // of look ahead
409                         if (!positions_.empty())
410                                 cerr << "Unignoring comment: "
411                                      << curr_token().asInput();
412                         putback();
413                 }
414                 else
415                         break;
416         }
417 }
418
419
420 void Parser::putback()
421 {
422         --pos_;
423 }
424
425
426 void Parser::pushPosition()
427 {
428         positions_.push_back(pos_);
429 }
430
431
432 void Parser::popPosition()
433 {
434         pos_ = positions_.back();
435         positions_.pop_back();
436         deparse();
437 }
438
439
440 void Parser::dropPosition()
441 {
442         positions_.pop_back();
443 }
444
445
446 bool Parser::good()
447 {
448         if (pos_ < tokens_.size())
449                 return true;
450         if (!is_.good())
451                 return false;
452         return is_.peek() != idocstream::traits_type::eof();
453 }
454
455
456 bool Parser::hasOpt()
457 {
458         // An optional argument can occur in any of the following forms:
459         // - \foo[bar]
460         // - \foo [bar]
461         // - \foo
462         //   [bar]
463         // - \foo %comment
464         //   [bar]
465
466         // remember current position
467         unsigned int oldpos = pos_;
468         // skip spaces and comments
469         while (good()) {
470                 get_token();
471                 if (isParagraph()) {
472                         putback();
473                         break;
474                 }
475                 if (curr_token().cat() == catSpace ||
476                     curr_token().cat() == catNewline ||
477                     curr_token().cat() == catComment)
478                         continue;
479                 putback();
480                 break;
481         }
482         bool const retval = (next_token().asInput() == "[");
483         pos_ = oldpos;
484         return retval;
485 }
486
487
488 Parser::Arg Parser::getFullArg(char left, char right, bool allow_escaping)
489 {
490         skip_spaces(true);
491
492         // This is needed if a partial file ends with a command without arguments,
493         // e. g. \medskip
494         if (! good())
495                 return make_pair(false, string());
496
497         string result;
498         Token t = get_token();
499
500         if (t.cat() == catComment || t.cat() == catEscape ||
501             t.character() != left) {
502                 putback();
503                 return make_pair(false, string());
504         } else {
505                 while (good()) {
506                         t = get_token();
507                         // Ignore comments
508                         if (t.cat() == catComment) {
509                                 if (!t.cs().empty())
510                                         cerr << "Ignoring comment: " << t.asInput();
511                                 continue;
512                         }
513                         if (allow_escaping) {
514                                 if (t.cat() != catEscape && t.character() == right)
515                                         break;
516                         } else {
517                                 if (t.character() == right) {
518                                         if (t.cat() == catEscape)
519                                                 result += '\\';
520                                         break;
521                                 }
522                         }
523                         result += t.asInput();
524                 }
525         }
526         return make_pair(true, result);
527 }
528
529
530 string Parser::getArg(char left, char right, bool allow_escaping)
531 {
532         return getFullArg(left, right, allow_escaping).second;
533 }
534
535
536 string Parser::getFullOpt(bool keepws)
537 {
538         Arg arg = getFullArg('[', ']');
539         if (arg.first)
540                 return '[' + arg.second + ']';
541         if (keepws)
542                 unskip_spaces(true);
543         return string();
544 }
545
546
547 string Parser::getOpt(bool keepws)
548 {
549         string const res = getArg('[', ']');
550         if (res.empty()) {
551                 if (keepws)
552                         unskip_spaces(true);
553                 return string();
554         }
555         return '[' + res + ']';
556 }
557
558
559 string Parser::getFullParentheseArg()
560 {
561         Arg arg = getFullArg('(', ')');
562         if (arg.first)
563                 return '(' + arg.second + ')';
564         return string();
565 }
566
567
568 string const Parser::ertEnvironment(string const & name)
569 {
570         if (!good())
571                 return string();
572
573         ostringstream os;
574         for (Token t = get_token(); good(); t = get_token()) {
575                 if (t.cat() == catBegin) {
576                         putback();
577                         os << '{' << verbatim_item() << '}';
578                 } else if (t.asInput() == "\\begin") {
579                         string const env = getArg('{', '}');
580                         os << "\\begin{" << env << '}'
581                            << ertEnvironment(env)
582                            << "\\end{" << env << '}';
583                 } else if (t.asInput() == "\\end") {
584                         string const end = getArg('{', '}');
585                         if (end != name)
586                                 cerr << "\\end{" << end
587                                      << "} does not match \\begin{" << name
588                                      << "}." << endl;
589                         return os.str();
590                 } else
591                         os << t.asInput();
592         }
593         cerr << "unexpected end of input" << endl;
594         return os.str();
595 }
596
597
598 string const Parser::plainEnvironment(string const & name)
599 {
600         if (!good())
601                 return string();
602
603         ostringstream os;
604         for (Token t = get_token(); good(); t = get_token()) {
605                 if (t.asInput() == "\\end") {
606                         string const end = getArg('{', '}');
607                         if (end == name)
608                                 return os.str();
609                         else
610                                 os << "\\end{" << end << '}';
611                 } else
612                         os << t.asInput();
613         }
614         cerr << "unexpected end of input" << endl;
615         return os.str();
616 }
617
618
619 string const Parser::plainCommand(char left, char right, string const & name)
620 {
621         if (!good())
622                 return string();
623         // check if first token is really the start character
624         Token tok = get_token();
625         if (tok.character() != left) {
626                 cerr << "first character does not match start character of command \\" << name << endl;
627                 return string();
628         }
629         ostringstream os;
630         for (Token t = get_token(); good(); t = get_token()) {
631                 if (t.character() == right) {
632                         return os.str();
633                 } else
634                         os << t.asInput();
635         }
636         cerr << "unexpected end of input" << endl;
637         return os.str();
638 }
639
640
641 Parser::Arg Parser::verbatimStuff(string const & end_string, bool const allow_linebreak)
642 {
643         if (!good())
644                 return Arg(false, string());
645
646         pushPosition();
647         ostringstream oss;
648         size_t match_index = 0;
649         setCatcodes(VERBATIM_CATCODES);
650         for (Token t = get_token(); good(); t = get_token()) {
651                 // FIXME t.asInput() might be longer than we need ?
652                 if (t.asInput() == end_string.substr(match_index,
653                                                      t.asInput().length())) {
654                         match_index += t.asInput().length();
655                         if (match_index >= end_string.length())
656                                 break;
657                 } else {
658                         if (!allow_linebreak && t.asInput() == "\n") {
659                                 cerr << "unexpected end of input" << endl;
660                                 popPosition();
661                                 setCatcodes(NORMAL_CATCODES);
662                                 return Arg(false, string());
663                         }
664                         if (match_index) {
665                                 oss << end_string.substr(0, match_index)
666                                     << t.asInput();
667                                 match_index = 0;
668                         } else
669                                 oss << t.asInput();
670                 }
671         }
672
673         if (!good()) {
674                 cerr << "unexpected end of input" << endl;
675                 popPosition();
676                 setCatcodes(NORMAL_CATCODES);
677                 return Arg(false, string());
678         }
679         setCatcodes(NORMAL_CATCODES);
680         dropPosition();
681         return Arg(true, oss.str());
682 }
683
684
685 string const Parser::verbatimEnvironment(string const & name)
686 {
687         //FIXME: do something if endstring is not found
688         string s = verbatimStuff("\\end{" + name + "}").second;
689         // ignore one newline at beginning or end of string
690         if (prefixIs(s, "\n"))
691                 s.erase(0,1);
692         if (suffixIs(s, "\n"))
693                 s.erase(s.length() - 1,1);
694         return s;
695 }
696
697
698 string Parser::verbatimOption()
699 {
700         string res;
701         if (next_token().character() == '[') {
702                 Token t = get_token();
703                 for (t = get_token(); t.character() != ']' && good(); t = get_token()) {
704                         if (t.cat() == catBegin) {
705                                 putback();
706                                 res += '{' + verbatim_item() + '}';
707                         } else
708                                 res += t.asInput();
709                 }
710         }
711         return res;
712 }
713
714
715 string Parser::verbatim_item()
716 {
717         if (!good())
718                 error("stream bad");
719         skip_spaces();
720         if (next_token().cat() == catBegin) {
721                 Token t = get_token(); // skip brace
722                 string res;
723                 for (Token t = get_token(); t.cat() != catEnd && good(); t = get_token()) {
724                         if (t.cat() == catBegin) {
725                                 putback();
726                                 res += '{' + verbatim_item() + '}';
727                         }
728                         else
729                                 res += t.asInput();
730                 }
731                 return res;
732         }
733         return get_token().asInput();
734 }
735
736
737 void Parser::tokenize_one()
738 {
739         catInit();
740         char_type c;
741         if (!is_.get(c))
742                 return;
743
744         switch (catcode(c)) {
745         case catSpace: {
746                 docstring s(1, c);
747                 while (is_.get(c) && catcode(c) == catSpace)
748                         s += c;
749                 if (catcode(c) != catSpace)
750                         is_.putback(c);
751                 push_back(Token(s, catSpace));
752                 break;
753         }
754
755         case catNewline: {
756                 ++lineno_;
757                 docstring s(1, getNewline(is_, c));
758                 while (is_.get(c) && catcode(c) == catNewline) {
759                         ++lineno_;
760                         s += getNewline(is_, c);
761                 }
762                 if (catcode(c) != catNewline)
763                         is_.putback(c);
764                 push_back(Token(s, catNewline));
765                 break;
766         }
767
768         case catComment: {
769                 // We don't treat "%\n" combinations here specially because
770                 // we want to preserve them in the preamble
771                 docstring s;
772                 while (is_.get(c) && catcode(c) != catNewline)
773                         s += c;
774                 // handle possible DOS line ending
775                 if (catcode(c) == catNewline)
776                         c = getNewline(is_, c);
777                 // Note: The '%' at the beginning and the '\n' at the end
778                 // of the comment are not stored.
779                 ++lineno_;
780                 push_back(Token(s, catComment));
781                 break;
782         }
783
784         case catEscape: {
785                 is_.get(c);
786                 if (!is_) {
787                         error("unexpected end of input");
788                 } else {
789                         docstring s(1, c);
790                         if (catcode(c) == catLetter) {
791                                 // collect letters
792                                 while (is_.get(c) && catcode(c) == catLetter)
793                                         s += c;
794                                 if (catcode(c) != catLetter)
795                                         is_.putback(c);
796                         }
797                         push_back(Token(s, catEscape));
798                 }
799                 break;
800         }
801
802         case catIgnore: {
803                 cerr << "ignoring a char: " << c << "\n";
804                 break;
805         }
806
807         default:
808                 push_back(Token(docstring(1, c), catcode(c)));
809         }
810         //cerr << tokens_.back();
811 }
812
813
814 void Parser::dump() const
815 {
816         cerr << "\nTokens: ";
817         for (unsigned i = 0; i < tokens_.size(); ++i) {
818                 if (i == pos_)
819                         cerr << " <#> ";
820                 cerr << tokens_[i];
821         }
822         cerr << " pos: " << pos_ << "\n";
823 }
824
825
826 void Parser::error(string const & msg)
827 {
828         cerr << "Line ~" << lineno_ << ":  parse error: " << msg << endl;
829         dump();
830         //exit(1);
831 }
832
833
834 void Parser::reset()
835 {
836         pos_ = 0;
837 }
838
839
840 } // namespace lyx