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