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