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