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