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