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