]> git.lyx.org Git - lyx.git/blob - src/mathed/math_parser.C
add missing 'else'
[lyx.git] / src / mathed / math_parser.C
1 /** The math parser
2     \author André Pönitz (2001)
3  */
4
5 /*
6
7 If someone desperately needs partial "structures" (such as a few
8 cells of an array inset or similar) (s)he could uses the
9 following hack as starting point to write some macros:
10
11   \newif\ifcomment
12   \commentfalse
13   \ifcomment
14           \def\makeamptab{\catcode`\&=4\relax}
15           \def\makeampletter{\catcode`\&=11\relax}
16     \def\b{\makeampletter\expandafter\makeamptab\bi}
17     \long\def\bi#1\e{}
18   \else
19     \def\b{}\def\e{}
20   \fi
21
22   ...
23
24   \[\begin{array}{ccc}
25 1
26 &
27
28   \end{array}\]
29
30 */
31
32
33 #include <config.h>
34
35
36 #include "math_parser.h"
37 #include "math_inset.h"
38 #include "math_arrayinset.h"
39 #include "math_braceinset.h"
40 #include "math_boxinset.h"
41 #include "math_charinset.h"
42 #include "math_commentinset.h"
43 #include "math_deliminset.h"
44 #include "math_envinset.h"
45 #include "math_extern.h"
46 #include "math_factory.h"
47 #include "math_kerninset.h"
48 #include "math_macro.h"
49 #include "math_macrotemplate.h"
50 #include "math_hullinset.h"
51 #include "math_parboxinset.h"
52 #include "math_parinset.h"
53 #include "math_rootinset.h"
54 #include "math_scriptinset.h"
55 #include "math_sizeinset.h"
56 #include "math_sqrtinset.h"
57 #include "math_stringinset.h"
58 #include "math_support.h"
59 #include "math_tabularinset.h"
60 #include "math_xyarrowinset.h"
61
62 //#include "insets/insetref.h"
63 #include "ref_inset.h"
64
65 #include "lyxlex.h"
66 #include "debug.h"
67 #include "support/LAssert.h"
68 #include "support/lstrings.h"
69
70 #include <cctype>
71 #include <algorithm>
72
73 using std::istream;
74 using std::ostream;
75 using std::ios;
76 using std::endl;
77 using std::fill;
78 using std::vector;
79 using std::atoi;
80
81
82 //#define FILEDEBUG
83
84
85 namespace {
86
87 MathInset::mode_type asMode(MathInset::mode_type oldmode, string const & str)
88 {
89         if (str == "mathmode")
90                 return MathInset::MATH_MODE;
91         if (str == "textmode" || str == "forcetext")
92                 return MathInset::TEXT_MODE;
93         return oldmode;
94 }
95
96
97 bool stared(string const & s)
98 {
99         string::size_type const n = s.size();
100         return n && s[n - 1] == '*';
101 }
102
103
104 // These are TeX's catcodes
105 enum CatCode {
106         catEscape,     // 0    backslash
107         catBegin,      // 1    {
108         catEnd,        // 2    }
109         catMath,       // 3    $
110         catAlign,      // 4    &
111         catNewline,    // 5    ^^M
112         catParameter,  // 6    #
113         catSuper,      // 7    ^
114         catSub,        // 8    _
115         catIgnore,     // 9
116         catSpace,      // 10   space
117         catLetter,     // 11   a-zA-Z
118         catOther,      // 12   none of the above
119         catActive,     // 13   ~
120         catComment,    // 14   %
121         catInvalid     // 15   <delete>
122 };
123
124 CatCode theCatcode[256];
125
126
127 inline CatCode catcode(unsigned char c)
128 {
129         return theCatcode[c];
130 }
131
132
133 enum {
134         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing
135         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
136         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
137         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
138         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
139         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced token)
140         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
141         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
142         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
143         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
144         FLAG_OPTION     = 1 << 11, //  read [...] style option
145         FLAG_BRACED     = 1 << 12  //  read {...} style argument
146 };
147
148
149 void catInit()
150 {
151         fill(theCatcode, theCatcode + 256, catOther);
152         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
153         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
154
155         theCatcode['\\'] = catEscape;
156         theCatcode['{']  = catBegin;
157         theCatcode['}']  = catEnd;
158         theCatcode['$']  = catMath;
159         theCatcode['&']  = catAlign;
160         theCatcode['\n'] = catNewline;
161         theCatcode['#']  = catParameter;
162         theCatcode['^']  = catSuper;
163         theCatcode['_']  = catSub;
164         theCatcode['\7f'] = catIgnore;
165         theCatcode[' ']  = catSpace;
166         theCatcode['\t'] = catSpace;
167         theCatcode['\r'] = catNewline;
168         theCatcode['~']  = catActive;
169         theCatcode['%']  = catComment;
170 }
171
172
173
174 //
175 // Helper class for parsing
176 //
177
178 class Token {
179 public:
180         ///
181         Token() : cs_(), char_(0), cat_(catIgnore) {}
182         ///
183         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
184         ///
185         Token(string const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
186
187         ///
188         string const & cs() const { return cs_; }
189         ///
190         CatCode cat() const { return cat_; }
191         ///
192         char character() const { return char_; }
193         ///
194         string asString() const { return cs_.size() ? cs_ : string(1, char_); }
195
196 private:
197         ///
198         string cs_;
199         ///
200         char char_;
201         ///
202         CatCode cat_;
203 };
204
205 ostream & operator<<(ostream & os, Token const & t)
206 {
207         if (t.cs().size())
208                 os << '\\' << t.cs();
209         else
210                 os << '[' << t.character() << ',' << t.cat() << ']';
211         return os;
212 }
213
214
215 class Parser {
216
217 public:
218         ///
219         typedef  MathInset::mode_type mode_type;
220
221         ///
222         Parser(LyXLex & lex);
223         ///
224         Parser(istream & is);
225
226         ///
227         bool parse(MathAtom & at);
228         ///
229         void parse(MathArray & array, unsigned flags, mode_type mode);
230         ///
231         void parse1(MathGridInset & grid, unsigned flags, mode_type mode,
232                 bool numbered);
233         ///
234         MathArray parse(unsigned flags, mode_type mode);
235         ///
236         int lineno() const { return lineno_; }
237         ///
238         void putback();
239
240 private:
241         ///
242         void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
243         /// get arg delimited by 'left' and 'right'
244         string getArg(char left, char right);
245         ///
246         char getChar();
247         ///
248         void error(string const & msg);
249         /// dump contents to screen
250         void dump() const;
251         ///
252         void tokenize(istream & is);
253         ///
254         void tokenize(string const & s);
255         ///
256         void skipSpaceTokens(istream & is, char c);
257         ///
258         void push_back(Token const & t);
259         ///
260         void pop_back();
261         ///
262         Token const & prevToken() const;
263         ///
264         Token const & nextToken() const;
265         ///
266         Token const & getToken();
267         /// skips spaces if any
268         void skipSpaces();
269         ///
270         void lex(string const & s);
271         ///
272         bool good() const;
273         ///
274         string parse_verbatim_item();
275         ///
276         string parse_verbatim_option();
277
278         ///
279         int lineno_;
280         ///
281         vector<Token> tokens_;
282         ///
283         unsigned pos_;
284 };
285
286
287 Parser::Parser(LyXLex & lexer)
288         : lineno_(lexer.getLineNo()), pos_(0)
289 {
290         tokenize(lexer.getStream());
291         lexer.eatLine();
292 }
293
294
295 Parser::Parser(istream & is)
296         : lineno_(0), pos_(0)
297 {
298         tokenize(is);
299 }
300
301
302 void Parser::push_back(Token const & t)
303 {
304         tokens_.push_back(t);
305 }
306
307
308 void Parser::pop_back()
309 {
310         tokens_.pop_back();
311 }
312
313
314 Token const & Parser::prevToken() const
315 {
316         static const Token dummy;
317         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
318 }
319
320
321 Token const & Parser::nextToken() const
322 {
323         static const Token dummy;
324         return good() ? tokens_[pos_] : dummy;
325 }
326
327
328 Token const & Parser::getToken()
329 {
330         static const Token dummy;
331         //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
332         return good() ? tokens_[pos_++] : dummy;
333 }
334
335
336 void Parser::skipSpaces()
337 {
338         while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
339                 getToken();
340 }
341
342
343 void Parser::putback()
344 {
345         --pos_;
346 }
347
348
349 bool Parser::good() const
350 {
351         return pos_ < tokens_.size();
352 }
353
354
355 char Parser::getChar()
356 {
357         if (!good())
358                 error("The input stream is not well...");
359         return tokens_[pos_++].character();
360 }
361
362
363 string Parser::getArg(char left, char right)
364 {
365         skipSpaces();
366
367         string result;
368         char c = getChar();
369
370         if (c != left)
371                 putback();
372         else
373                 while ((c = getChar()) != right && good())
374                         result += c;
375
376         return result;
377 }
378
379
380 void Parser::skipSpaceTokens(istream & is, char c)
381 {
382         // skip trailing spaces
383         while (catcode(c) == catSpace || catcode(c) == catNewline)
384                 if (!is.get(c))
385                         break;
386         //lyxerr << "putting back: " << c << "\n";
387         is.putback(c);
388 }
389
390
391 void Parser::tokenize(istream & is)
392 {
393         // eat everything up to the next \end_inset or end of stream
394         // and store it in s for further tokenization
395         string s;
396         char c;
397         while (is.get(c)) {
398                 s += c;
399                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
400                         s = s.substr(0, s.size() - 10);
401                         break;
402                 }
403         }
404         // Remove the space after \end_inset
405         if (is.get(c) && c != ' ')
406                 is.unget();
407
408         // tokenize buffer
409         tokenize(s);
410 }
411
412
413 void Parser::tokenize(string const & buffer)
414 {
415         static bool init_done = false;
416
417         if (!init_done) {
418                 catInit();
419                 init_done = true;
420         }
421
422         istringstream is(buffer.c_str(), ios::in | ios::binary);
423
424         char c;
425         while (is.get(c)) {
426                 //lyxerr << "reading c: " << c << "\n";
427
428                 switch (catcode(c)) {
429                         case catNewline: {
430                                 ++lineno_;
431                                 is.get(c);
432                                 if (catcode(c) == catNewline)
433                                         ; //push_back(Token("par"));
434                                 else {
435                                         push_back(Token('\n', catNewline));
436                                         is.putback(c);
437                                 }
438                                 break;
439                         }
440
441 /*
442                         case catComment: {
443                                 while (is.get(c) && catcode(c) != catNewline)
444                                         ;
445                                 ++lineno_;
446                                 break;
447                         }
448 */
449
450                         case catEscape: {
451                                 is.get(c);
452                                 if (!is) {
453                                         error("unexpected end of input");
454                                 } else {
455                                         string s(1, c);
456                                         if (catcode(c) == catLetter) {
457                                                 // collect letters
458                                                 while (is.get(c) && catcode(c) == catLetter)
459                                                         s += c;
460                                                 skipSpaceTokens(is, c);
461                                         }
462                                         push_back(Token(s));
463                                 }
464                                 break;
465                         }
466
467                         case catSuper:
468                         case catSub: {
469                                 push_back(Token(c, catcode(c)));
470                                 is.get(c);
471                                 skipSpaceTokens(is, c);
472                                 break;
473                         }
474
475                         case catIgnore: {
476                                 lyxerr << "ignoring a char: " << int(c) << "\n";
477                                 break;
478                         }
479
480                         default:
481                                 push_back(Token(c, catcode(c)));
482                 }
483         }
484
485 #ifdef FILEDEBUG
486         dump();
487 #endif
488 }
489
490
491 void Parser::dump() const
492 {
493         lyxerr << "\nTokens: ";
494         for (unsigned i = 0; i < tokens_.size(); ++i) {
495                 if (i == pos_)
496                         lyxerr << " <#> ";
497                 lyxerr << tokens_[i];
498         }
499         lyxerr << " pos: " << pos_ << "\n";
500 }
501
502
503 void Parser::error(string const & msg)
504 {
505         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
506         dump();
507         //exit(1);
508 }
509
510
511 bool Parser::parse(MathAtom & at)
512 {
513         skipSpaces();
514         MathArray ar;
515         parse(ar, false, MathInset::UNDECIDED_MODE);
516         if (ar.size() != 1 || ar.front()->getType() == "none") {
517                 lyxerr << "unusual contents found: " << ar << endl;
518                 at = MathAtom(new MathParInset(ar));
519                 //if (at->nargs() > 0)
520                 //      at.nucleus()->cell(0) = ar;
521                 //else
522                 //      lyxerr << "unusual contents found: " << ar << endl;
523                 return true;
524         }
525         at = ar[0];
526         return true;
527 }
528
529
530 string Parser::parse_verbatim_option()
531 {
532         skipSpaces();
533         string res;
534         if (nextToken().character() == '[') {
535                 Token t = getToken();
536                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
537                         if (t.cat() == catBegin) {
538                                 putback();
539                                 res += '{' + parse_verbatim_item() + '}';
540                         } else
541                                 res += t.asString();
542                 }
543         }
544         return res;
545 }
546
547
548 string Parser::parse_verbatim_item()
549 {
550         skipSpaces();
551         string res;
552         if (nextToken().cat() == catBegin) {
553                 Token t = getToken();
554                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
555                         if (t.cat() == catBegin) {
556                                 putback();
557                                 res += '{' + parse_verbatim_item() + '}';
558                         }
559                         else
560                                 res += t.asString();
561                 }
562         }
563         return res;
564 }
565
566
567 MathArray Parser::parse(unsigned flags, mode_type mode)
568 {
569         MathArray ar;
570         parse(ar, flags, mode);
571         return ar;
572 }
573
574
575 void Parser::parse(MathArray & array, unsigned flags, mode_type mode)
576 {
577         MathGridInset grid(1, 1);
578         parse1(grid, flags, mode, false);
579         array = grid.cell(0);
580 }
581
582
583 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
584         const bool numbered)
585 {
586         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
587 }
588
589
590 void Parser::parse1(MathGridInset & grid, unsigned flags,
591         const mode_type mode, const bool numbered)
592 {
593         int limits = 0;
594         MathGridInset::row_type cellrow = 0;
595         MathGridInset::col_type cellcol = 0;
596         MathArray * cell = &grid.cell(grid.index(cellrow, cellcol));
597
598         if (grid.asHullInset())
599                 grid.asHullInset()->numbered(cellrow, numbered);
600
601         //dump();
602         //lyxerr << "grid: " << grid << endl;
603
604         while (good()) {
605                 Token const & t = getToken();
606
607 #ifdef FILEDEBUG
608                 lyxerr << "t: " << t << " flags: " << flags << "\n";
609                 cell->dump();
610                 lyxerr << "\n";
611 #endif
612
613                 if (flags & FLAG_ITEM) {
614                         skipSpaces();
615
616                         flags &= ~FLAG_ITEM;
617                         if (t.cat() == catBegin) {
618                                 // skip the brace and collect everything to the next matching
619                                 // closing brace
620                                 flags |= FLAG_BRACE_LAST;
621                                 continue;
622                         }
623
624                         // handle only this single token, leave the loop if done
625                         flags |= FLAG_LEAVE;
626                 }
627
628
629                 if (flags & FLAG_BRACED) {
630                         if (t.cat() == catSpace)
631                                 continue;
632
633                         if (t.cat() != catBegin) {
634                                 error("opening brace expected");
635                                 return;
636                         }
637
638                         // skip the brace and collect everything to the next matching
639                         // closing brace
640                         flags = FLAG_BRACE_LAST;
641                 }
642
643
644                 if (flags & FLAG_OPTION) {
645                         if (t.cat() == catOther && t.character() == '[') {
646                                 MathArray ar;
647                                 parse(ar, FLAG_BRACK_LAST, mode);
648                                 cell->append(ar);
649                         } else {
650                                 // no option found, put back token and we are done
651                                 putback();
652                         }
653                         return;
654                 }
655
656                 //
657                 // cat codes
658                 //
659                 if (t.cat() == catMath) {
660                         if (mode != MathInset::MATH_MODE) {
661                                 // we are inside some text mode thingy, so opening new math is allowed
662                                 Token const & n = getToken();
663                                 if (n.cat() == catMath) {
664                                         // TeX's $$...$$ syntax for displayed math
665                                         cell->push_back(MathAtom(new MathHullInset("equation")));
666                                         parse2(cell->back(), FLAG_SIMPLE, MathInset::MATH_MODE, false);
667                                         getToken(); // skip the second '$' token
668                                 } else {
669                                         // simple $...$  stuff
670                                         putback();
671                                         cell->push_back(MathAtom(new MathHullInset("simple")));
672                                         parse2(cell->back(), FLAG_SIMPLE, MathInset::MATH_MODE, false);
673                                 }
674                         }
675
676                         else if (flags & FLAG_SIMPLE) {
677                                 // this is the end of the formula
678                                 return;
679                         }
680
681                         else {
682                                 error("something strange in the parser\n");
683                                 break;
684                         }
685                 }
686
687                 else if (t.cat() == catLetter)
688                         cell->push_back(MathAtom(new MathCharInset(t.character())));
689
690                 else if (t.cat() == catSpace && mode != MathInset::MATH_MODE) {
691                         if (cell->empty() || cell->back()->getChar() != ' ')
692                                 cell->push_back(MathAtom(new MathCharInset(t.character())));
693                 }
694
695                 else if (t.cat() == catNewline && mode != MathInset::MATH_MODE)
696                         cell->push_back(MathAtom(new MathCharInset(t.character())));
697
698                 else if (t.cat() == catParameter) {
699                         Token const & n = getToken();
700                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
701                 }
702
703                 else if (t.cat() == catActive)
704                         cell->push_back(MathAtom(new MathCharInset(t.character())));
705
706                 else if (t.cat() == catBegin) {
707                         MathArray ar;
708                         parse(ar, FLAG_BRACE_LAST, mode);
709                         // do not create a BraceInset if they were written by LyX
710                         // this helps to keep the annoyance of  "a choose b"  to a minimum
711                         if (ar.size() == 1 && ar[0]->extraBraces())
712                                 cell->append(ar);
713                         else
714                                 cell->push_back(MathAtom(new MathBraceInset(ar)));
715                 }
716
717                 else if (t.cat() == catEnd) {
718                         if (flags & FLAG_BRACE_LAST)
719                                 return;
720                         error("found '}' unexpectedly");
721                         //lyx::Assert(0);
722                         //add(cell, '}', LM_TC_TEX);
723                 }
724
725                 else if (t.cat() == catAlign) {
726                         ++cellcol;
727                         //lyxerr << " column now " << cellcol << " max: " << grid.ncols() << "\n";
728                         if (cellcol == grid.ncols()) {
729                                 //lyxerr << "adding column " << cellcol << "\n";
730                                 grid.addCol(cellcol - 1);
731                         }
732                         cell = &grid.cell(grid.index(cellrow, cellcol));
733                 }
734
735                 else if (t.cat() == catSuper || t.cat() == catSub) {
736                         bool up = (t.cat() == catSuper);
737                         // we need no new script inset if the last thing was a scriptinset,
738                         // which has that script already not the same script already
739                         if (!cell->size())
740                                 cell->push_back(MathAtom(new MathScriptInset(up)));
741                         else if (cell->back()->asScriptInset() &&
742                                         !cell->back()->asScriptInset()->has(up))
743                                 cell->back().nucleus()->asScriptInset()->ensure(up);
744                         else if (cell->back()->asScriptInset())
745                                 cell->push_back(MathAtom(new MathScriptInset(up)));
746                         else
747                                 cell->back() = MathAtom(new MathScriptInset(cell->back(), up));
748                         MathScriptInset * p = cell->back().nucleus()->asScriptInset();
749                         // special handling of {}-bases
750                         // is this always correct?
751                         // It appears that this is wrong (Dekel)
752                         //if (p->nuc().size() == 1 && p->nuc().back()->asNestInset() &&
753                         //    p->nuc().back()->extraBraces())
754                         //      p->nuc() = p->nuc().back()->asNestInset()->cell(0);
755                         parse(p->cell(up), FLAG_ITEM, mode);
756                         if (limits) {
757                                 p->limits(limits);
758                                 limits = 0;
759                         }
760                 }
761
762                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
763                         //lyxerr << "finished reading option\n";
764                         return;
765                 }
766
767                 else if (t.cat() == catOther)
768                         cell->push_back(MathAtom(new MathCharInset(t.character())));
769
770                 else if (t.cat() == catComment) {
771                         string s;
772                         while (good()) {
773                                 Token const & t = getToken();
774                                 if (t.cat() == catNewline)
775                                         break;
776                                 s += t.asString();
777                         }
778                         cell->push_back(MathAtom(new MathCommentInset(s)));
779                         skipSpaces();
780                 }
781
782                 //
783                 // control sequences
784                 //
785
786                 else if (t.cs() == "lyxlock") {
787                         if (cell->size())
788                                 cell->back().nucleus()->lock(true);
789                 }
790
791                 else if (t.cs() == "def" || t.cs() == "newcommand") {
792                         string name;
793                         int nargs = 0;
794                         if (t.cs() == "def") {
795                                 // get name
796                                 name = getToken().cs();
797
798                                 // read parameter
799                                 string pars;
800                                 while (good() && nextToken().cat() != catBegin) {
801                                         pars += getToken().cs();
802                                         ++nargs;
803                                 }
804                                 nargs /= 2;
805                                 //lyxerr << "read \\def parameter list '" << pars << "'\n";
806
807                         } else { // t.cs() == "newcommand"
808
809                                 if (getToken().cat() != catBegin) {
810                                         error("'{' in \\newcommand expected (1) \n");
811                                         return;
812                                 }
813
814                                 name = getToken().cs();
815
816                                 if (getToken().cat() != catEnd) {
817                                         error("'}' in \\newcommand expected\n");
818                                         return;
819                                 }
820
821                                 string arg  = getArg('[', ']');
822                                 if (!arg.empty())
823                                         nargs = atoi(arg.c_str());
824
825                         }
826
827                         MathArray ar1;
828                         parse(ar1, FLAG_ITEM, MathInset::UNDECIDED_MODE);
829
830                         // we cannot handle recursive stuff at all
831                         //MathArray test;
832                         //test.push_back(createMathInset(name));
833                         //if (ar1.contains(test)) {
834                         //      error("we cannot handle recursive macros at all.\n");
835                         //      return;
836                         //}
837
838                         // is a version for display attached?
839                         skipSpaces();
840                         MathArray ar2;
841                         if (nextToken().cat() == catBegin) {
842                                 parse(ar2, FLAG_ITEM, MathInset::MATH_MODE);
843                         }
844
845                         cell->push_back(MathAtom(new MathMacroTemplate(name, nargs, ar1, ar2)));
846                 }
847
848                 else if (t.cs() == "(") {
849                         cell->push_back(MathAtom(new MathHullInset("simple")));
850                         parse2(cell->back(), FLAG_SIMPLE2, MathInset::MATH_MODE, false);
851                 }
852
853                 else if (t.cs() == "[") {
854                         cell->push_back(MathAtom(new MathHullInset("equation")));
855                         parse2(cell->back(), FLAG_EQUATION, MathInset::MATH_MODE, false);
856                 }
857
858                 else if (t.cs() == "protect")
859                         // ignore \\protect, will hopefully be re-added during output
860                         ;
861
862                 else if (t.cs() == "end") {
863                         if (flags & FLAG_END) {
864                                 // eat environment name
865                                 //string const name =
866                                 getArg('{', '}');
867                                 // FIXME: check that we ended the correct environment
868                                 return;
869                         }
870                         error("found 'end' unexpectedly");
871                 }
872
873                 else if (t.cs() == ")") {
874                         if (flags & FLAG_SIMPLE2)
875                                 return;
876                         error("found '\\)' unexpectedly");
877                 }
878
879                 else if (t.cs() == "]") {
880                         if (flags & FLAG_EQUATION)
881                                 return;
882                         error("found '\\]' unexpectedly");
883                 }
884
885                 else if (t.cs() == "\\") {
886                         grid.vcrskip(LyXLength(getArg('[', ']')), cellrow);
887                         ++cellrow;
888                         cellcol = 0;
889                         if (cellrow == grid.nrows())
890                                 grid.addRow(cellrow - 1);
891                         if (grid.asHullInset())
892                                 grid.asHullInset()->numbered(cellrow, numbered);
893                         cell = &grid.cell(grid.index(cellrow, cellcol));
894                 }
895
896 #if 0
897                 else if (t.cs() == "multicolumn") {
898                         // extract column count and insert dummy cells
899                         MathArray count;
900                         parse(count, FLAG_ITEM, mode);
901                         int cols = 1;
902                         if (!extractNumber(count, cols)) {
903                                 lyxerr << " can't extract number of cells from " << count << "\n";
904                         }
905                         // resize the table if necessary
906                         for (int i = 0; i < cols; ++i) {
907                                 ++cellcol;
908                                 if (cellcol == grid.ncols()) {
909                                         //lyxerr << "adding column " << cellcol << "\n";
910                                         grid.addCol(cellcol - 1);
911                                 }
912                                 cell = &grid.cell(grid.index(cellrow, cellcol));
913                                 // mark this as dummy
914                                 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = true;
915                         }
916                         // the last cell is the real thng, not a dummy
917                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
918
919                         // read special alignment
920                         MathArray align;
921                         parse(align, FLAG_ITEM, mode);
922                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
923
924                         // parse the remaining contents into the "real" cell
925                         parse(*cell, FLAG_ITEM, mode);
926                 }
927 #endif
928
929                 else if (t.cs() == "limits")
930                         limits = 1;
931
932                 else if (t.cs() == "nolimits")
933                         limits = -1;
934
935                 else if (t.cs() == "nonumber") {
936                         if (grid.asHullInset())
937                                 grid.asHullInset()->numbered(cellrow, false);
938                 }
939
940                 else if (t.cs() == "number") {
941                         if (grid.asHullInset())
942                                 grid.asHullInset()->numbered(cellrow, true);
943                 }
944
945                 else if (t.cs() == "hline") {
946                         grid.rowinfo(cellrow).lines_ ++;
947                 }
948
949                 else if (t.cs() == "sqrt") {
950                         MathArray ar;
951                         parse(ar, FLAG_OPTION, mode);
952                         if (ar.size()) {
953                                 cell->push_back(MathAtom(new MathRootInset));
954                                 cell->back().nucleus()->cell(0) = ar;
955                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
956                         } else {
957                                 cell->push_back(MathAtom(new MathSqrtInset));
958                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
959                         }
960                 }
961
962                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
963                         cell->push_back(createMathInset(t.cs()));
964                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
965                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
966                 }
967
968                 else if (t.cs() == "ref" || t.cs() == "prettyref" || 
969                                 t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
970                         cell->push_back(MathAtom(new RefInset(t.cs())));
971                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
972                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
973                 }
974
975                 else if (t.cs() == "left") {
976                         skipSpaces();
977                         string l = getToken().asString();
978                         MathArray ar;
979                         parse(ar, FLAG_RIGHT, mode);
980                         skipSpaces();
981                         string r = getToken().asString();
982                         cell->push_back(MathAtom(new MathDelimInset(l, r, ar)));
983                 }
984
985                 else if (t.cs() == "right") {
986                         if (flags & FLAG_RIGHT)
987                                 return;
988                         //lyxerr << "got so far: '" << cell << "'\n";
989                         error("Unmatched right delimiter");
990                         return;
991                 }
992
993                 else if (t.cs() == "begin") {
994                         string const name = getArg('{', '}');
995
996                         if (name == "array" || name == "subarray") {
997                                 string const valign = parse_verbatim_option() + 'c';
998                                 string const halign = parse_verbatim_item();
999                                 cell->push_back(MathAtom(new MathArrayInset(name, valign[0], halign)));
1000                                 parse2(cell->back(), FLAG_END, mode, false);
1001                         }
1002
1003                         else if (name == "tabular") {
1004                                 string const valign = parse_verbatim_option() + 'c';
1005                                 string const halign = parse_verbatim_item();
1006                                 cell->push_back(MathAtom(new MathTabularInset(name, valign[0], halign)));
1007                                 parse2(cell->back(), FLAG_END, MathInset::TEXT_MODE, false);
1008                         }
1009
1010                         else if (name == "split" || name == "cases" ||
1011                                          name == "gathered" || name == "aligned") {
1012                                 cell->push_back(createMathInset(name));
1013                                 parse2(cell->back(), FLAG_END, mode, false);
1014                         }
1015
1016                         else if (name == "math") {
1017                                 cell->push_back(MathAtom(new MathHullInset("simple")));
1018                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, true);
1019                         }
1020
1021                         else if (name == "equation" || name == "equation*"
1022                                         || name == "displaymath") {
1023                                 cell->push_back(MathAtom(new MathHullInset("equation")));
1024                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, (name == "equation"));
1025                         }
1026
1027                         else if (name == "eqnarray" || name == "eqnarray*") {
1028                                 cell->push_back(MathAtom(new MathHullInset("eqnarray")));
1029                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1030                         }
1031
1032                         else if (name == "align" || name == "align*") {
1033                                 cell->push_back(MathAtom(new MathHullInset("align")));
1034                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1035                         }
1036
1037                         else if (name == "flalign" || name == "flalign*") {
1038                                 cell->push_back(MathAtom(new MathHullInset("flalign")));
1039                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1040                         }
1041
1042                         else if (name == "alignat" || name == "alignat*") {
1043                                 // ignore this for a while
1044                                 getArg('{', '}');
1045                                 cell->push_back(MathAtom(new MathHullInset("alignat")));
1046                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1047                         }
1048
1049                         else if (name == "xalignat" || name == "xalignat*") {
1050                                 // ignore this for a while
1051                                 getArg('{', '}');
1052                                 cell->push_back(MathAtom(new MathHullInset("xalignat")));
1053                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1054                         }
1055
1056                         else if (name == "xxalignat") {
1057                                 // ignore this for a while
1058                                 getArg('{', '}');
1059                                 cell->push_back(MathAtom(new MathHullInset("xxalignat")));
1060                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1061                         }
1062
1063                         else if (name == "multline" || name == "multline*") {
1064                                 cell->push_back(MathAtom(new MathHullInset("multline")));
1065                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1066                         }
1067
1068                         else if (name == "gather" || name == "gather*") {
1069                                 cell->push_back(MathAtom(new MathHullInset("gather")));
1070                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1071                         }
1072
1073                         else if (latexkeys const * l = in_word_set(name)) {
1074                                 if (l->inset == "matrix") {
1075                                         cell->push_back(createMathInset(name));
1076                                         parse2(cell->back(), FLAG_END, mode, false);
1077                                 }
1078                         }
1079
1080                         else {
1081                                 //lyxerr << "unknow math inset begin '" << name << "'\n";
1082                                 // create generic environment inset
1083                                 cell->push_back(MathAtom(new MathEnvInset(name)));
1084                                 parse2(cell->back(), FLAG_END, mode, false);
1085                         }
1086                 }
1087
1088                 else if (t.cs() == "kern") {
1089 #ifdef WITH_WARNINGS
1090 #warning A hack...
1091 #endif
1092                         string s;
1093                         while (true) {
1094                                 Token const & t = getToken();
1095                                 if (!good()) {
1096                                         putback();
1097                                         break;
1098                                 }
1099                                 s += t.character();
1100                                 if (isValidLength(s))
1101                                         break;
1102                         }
1103                         cell->push_back(MathAtom(new MathKernInset(s)));
1104                 }
1105
1106                 else if (t.cs() == "label") {
1107                         string label = parse_verbatim_item();
1108                         if (grid.asHullInset()) {
1109                                 grid.asHullInset()->label(cellrow, label);
1110                         } else {
1111                                 cell->push_back(createMathInset(t.cs()));
1112                                 cell->push_back(MathAtom(new MathBraceInset(asArray(label))));
1113                         }
1114                 }
1115
1116                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1117                         MathAtom at = createMathInset(t.cs());
1118                         at.nucleus()->cell(0) = *cell;
1119                         cell->clear();
1120                         parse(at.nucleus()->cell(1), flags, mode);
1121                         cell->push_back(at);
1122                         return;
1123                 }
1124
1125                 else if (t.cs() == "substack") {
1126                         cell->push_back(createMathInset(t.cs()));
1127                         parse2(cell->back(), FLAG_ITEM, mode, false);
1128                 }
1129
1130                 else if (t.cs() == "xymatrix") {
1131                         cell->push_back(createMathInset(t.cs()));
1132                         parse2(cell->back(), FLAG_ITEM, mode, false);
1133                 }
1134
1135                 else if (t.cs() == "framebox") {
1136                         cell->push_back(createMathInset(t.cs()));
1137                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, MathInset::TEXT_MODE);
1138                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, MathInset::TEXT_MODE);
1139                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, MathInset::TEXT_MODE);
1140                 }
1141
1142 #if 0
1143                 else if (t.cs() == "infer") {
1144                         MathArray ar;
1145                         parse(ar, FLAG_OPTION, mode);
1146                         cell->push_back(createMathInset(t.cs()));
1147                         parse2(cell->back(), FLAG_ITEM, mode, false);
1148                 }
1149
1150                 // Disabled
1151                 else if (1 && t.cs() == "ar") {
1152                         MathXYArrowInset * p = new MathXYArrowInset;
1153                         // try to read target
1154                         parse(p->cell(0), FLAG_OTPTION, mode);
1155                         // try to read label
1156                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1157                                 p->up_ = nextToken().cat() == catSuper;
1158                                 getToken();
1159                                 parse(p->cell(1), FLAG_ITEM, mode);
1160                                 //lyxerr << "read label: " << p->cell(1) << "\n";
1161                         }
1162
1163                         cell->push_back(MathAtom(p));
1164                         //lyxerr << "read cell: " << cell << "\n";
1165                 }
1166 #endif
1167
1168                 else if (t.cs().size()) {
1169                         latexkeys const * l = in_word_set(t.cs());
1170                         if (l) {
1171                                 if (l->inset == "font") {
1172                                         cell->push_back(createMathInset(t.cs()));
1173                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, asMode(mode, l->extra));
1174                                 }
1175
1176                                 else if (l->inset == "oldfont") {
1177                                         cell->push_back(createMathInset(t.cs()));
1178                                         parse(cell->back().nucleus()->cell(0), flags, asMode(mode, l->extra));
1179                                         return;
1180                                 }
1181
1182                                 else if (l->inset == "style") {
1183                                         cell->push_back(createMathInset(t.cs()));
1184                                         parse(cell->back().nucleus()->cell(0), flags, mode);
1185                                         return;
1186                                 }
1187
1188                                 else if (l->inset == "parbox") {
1189                                         // read optional positioning and width
1190                                         string pos   = parse_verbatim_option();
1191                                         string width = parse_verbatim_item();
1192                                         cell->push_back(createMathInset(t.cs()));
1193                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, MathInset::TEXT_MODE);
1194                                         cell->back().nucleus()->asParboxInset()->setPosition(pos);
1195                                         cell->back().nucleus()->asParboxInset()->setWidth(width);
1196                                 }
1197
1198                                 else {
1199                                         MathAtom at = createMathInset(t.cs());
1200                                         for (MathInset::idx_type i = 0; i < at->nargs(); ++i)
1201                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, asMode(mode, l->extra));
1202                                         cell->push_back(at);
1203                                 }
1204                         }
1205
1206                         else {
1207                                 MathAtom at = createMathInset(t.cs());
1208                                 MathInset::mode_type m = mode;
1209                                 if (m == MathInset::UNDECIDED_MODE)
1210                                         m = at->currentMode();
1211                                 MathInset::idx_type start = 0;
1212                                 // this fails on \bigg[...\bigg]
1213                                 //MathArray opt;
1214                                 //parse(opt, FLAG_OPTION, MathInset::VERBATIM_MODE);
1215                                 //if (opt.size()) {
1216                                 //      start = 1;
1217                                 //      at.nucleus()->cell(0) = opt;
1218                                 //}
1219                                 for (MathInset::idx_type i = start; i < at->nargs(); ++i)
1220                                         parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1221                                 cell->push_back(at);
1222                         }
1223                 }
1224
1225
1226                 if (flags & FLAG_LEAVE) {
1227                         flags &= ~FLAG_LEAVE;
1228                         break;
1229                 }
1230         }
1231 }
1232
1233
1234
1235 } // anonymous namespace
1236
1237
1238 void mathed_parse_cell(MathArray & ar, string const & str)
1239 {
1240         istringstream is(str.c_str());
1241         mathed_parse_cell(ar, is);
1242 }
1243
1244
1245 void mathed_parse_cell(MathArray & ar, istream & is)
1246 {
1247         Parser(is).parse(ar, 0, MathInset::MATH_MODE);
1248 }
1249
1250
1251 bool mathed_parse_normal(MathAtom & t, string const & str)
1252 {
1253         istringstream is(str.c_str());
1254         return Parser(is).parse(t);
1255 }
1256
1257
1258 bool mathed_parse_normal(MathAtom & t, istream & is)
1259 {
1260         return Parser(is).parse(t);
1261 }
1262
1263
1264 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1265 {
1266         return Parser(lex).parse(t);
1267 }
1268
1269
1270 void mathed_parse_normal(MathGridInset & grid, string const & str)
1271 {
1272         istringstream is(str.c_str());
1273         Parser(is).parse1(grid, 0, MathInset::MATH_MODE, false);
1274 }