]> git.lyx.org Git - features.git/blob - src/mathed/math_parser.C
Small fixes to allow building with STLport
[features.git] / src / mathed / math_parser.C
1 /**
2  * \file math_parser.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 /*
12
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
16
17   \newif\ifcomment
18   \commentfalse
19   \ifcomment
20           \def\makeamptab{\catcode`\&=4\relax}
21           \def\makeampletter{\catcode`\&=11\relax}
22     \def\b{\makeampletter\expandafter\makeamptab\bi}
23     \long\def\bi#1\e{}
24   \else
25     \def\b{}\def\e{}
26   \fi
27
28   ...
29
30   \[\begin{array}{ccc}
31 1
32 &
33
34   \end{array}\]
35
36 */
37
38
39 #include <config.h>
40
41 #include "math_parser.h"
42 #include "math_arrayinset.h"
43 #include "math_braceinset.h"
44 #include "math_charinset.h"
45 #include "math_commentinset.h"
46 #include "math_deliminset.h"
47 #include "math_envinset.h"
48 #include "math_factory.h"
49 #include "math_kerninset.h"
50 #include "math_macro.h"
51 #include "math_macroarg.h"
52 #include "math_macrotemplate.h"
53 #include "math_parboxinset.h"
54 #include "math_parinset.h"
55 #include "math_rootinset.h"
56 #include "math_scriptinset.h"
57 #include "math_sqrtinset.h"
58 #include "math_support.h"
59 #include "math_tabularinset.h"
60
61 //#include "insets/insetref.h"
62 #include "ref_inset.h"
63
64 #include "lyxlex.h"
65 #include "support/std_sstream.h"
66 #include "debug.h"
67
68 #ifndef CXX_GLOBAL_CSTD
69 using std::atoi;
70 #endif
71 using std::endl;
72 using std::fill;
73
74 using std::ios;
75 using std::istream;
76 using std::istringstream;
77 using std::ostream;
78 using std::vector;
79
80
81 //#define FILEDEBUG
82
83
84 namespace {
85
86 MathInset::mode_type asMode(MathInset::mode_type oldmode, string const & str)
87 {
88         //lyxerr << "handling mode: '" << str << "'" << endl;
89         if (str == "mathmode")
90                 return MathInset::MATH_MODE;
91         if (str == "textmode" || str == "forcetext")
92                 return MathInset::TEXT_MODE;
93         return oldmode;
94 }
95
96
97 bool stared(string const & s)
98 {
99         string::size_type const n = s.size();
100         return n && s[n - 1] == '*';
101 }
102
103
104 // These are TeX's catcodes
105 enum CatCode {
106         catEscape,     // 0    backslash
107         catBegin,      // 1    {
108         catEnd,        // 2    }
109         catMath,       // 3    $
110         catAlign,      // 4    &
111         catNewline,    // 5    ^^M
112         catParameter,  // 6    #
113         catSuper,      // 7    ^
114         catSub,        // 8    _
115         catIgnore,     // 9
116         catSpace,      // 10   space
117         catLetter,     // 11   a-zA-Z
118         catOther,      // 12   none of the above
119         catActive,     // 13   ~
120         catComment,    // 14   %
121         catInvalid     // 15   <delete>
122 };
123
124 CatCode theCatcode[256];
125
126
127 inline CatCode catcode(unsigned char c)
128 {
129         return theCatcode[c];
130 }
131
132
133 enum {
134         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing
135         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
136         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
137         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
138         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
139         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced token)
140         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
141         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
142         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
143         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
144         FLAG_OPTION     = 1 << 11, //  read [...] style option
145         FLAG_BRACED     = 1 << 12  //  read {...} style argument
146 };
147
148
149 void catInit()
150 {
151         fill(theCatcode, theCatcode + 256, catOther);
152         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
153         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
154
155         theCatcode[int('\\')] = catEscape;
156         theCatcode[int('{')]  = catBegin;
157         theCatcode[int('}')]  = catEnd;
158         theCatcode[int('$')]  = catMath;
159         theCatcode[int('&')]  = catAlign;
160         theCatcode[int('\n')] = catNewline;
161         theCatcode[int('#')]  = catParameter;
162         theCatcode[int('^')]  = catSuper;
163         theCatcode[int('_')]  = catSub;
164         theCatcode[int(0x7f)] = catIgnore;
165         theCatcode[int(' ')]  = catSpace;
166         theCatcode[int('\t')] = catSpace;
167         theCatcode[int('\r')] = catNewline;
168         theCatcode[int('~')]  = catActive;
169         theCatcode[int('%')]  = catComment;
170 }
171
172
173
174 //
175 // Helper class for parsing
176 //
177
178 class Token {
179 public:
180         ///
181         Token() : cs_(), char_(0), cat_(catIgnore) {}
182         ///
183         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
184         ///
185         Token(string const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
186
187         ///
188         string const & cs() const { return cs_; }
189         ///
190         CatCode cat() const { return cat_; }
191         ///
192         char character() const { return char_; }
193         ///
194         string asString() const { return cs_.size() ? cs_ : string(1, char_); }
195
196 private:
197         ///
198         string cs_;
199         ///
200         char char_;
201         ///
202         CatCode cat_;
203 };
204
205 ostream & operator<<(ostream & os, Token const & t)
206 {
207         if (t.cs().size())
208                 os << '\\' << t.cs();
209         else if (t.cat() == catLetter)
210                 os << t.character();
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_ << endl;
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 << endl;
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 << endl;
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) << endl;
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_ << endl;
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         skipSpaces();
535         string res;
536         if (nextToken().character() == '[') {
537                 Token t = getToken();
538                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
539                         if (t.cat() == catBegin) {
540                                 putback();
541                                 res += '{' + parse_verbatim_item() + '}';
542                         } else
543                                 res += t.asString();
544                 }
545         }
546         return res;
547 }
548
549
550 string Parser::parse_verbatim_item()
551 {
552         skipSpaces();
553         string res;
554         if (nextToken().cat() == catBegin) {
555                 Token t = getToken();
556                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
557                         if (t.cat() == catBegin) {
558                                 putback();
559                                 res += '{' + parse_verbatim_item() + '}';
560                         }
561                         else
562                                 res += t.asString();
563                 }
564         }
565         return res;
566 }
567
568
569 MathArray Parser::parse(unsigned flags, mode_type mode)
570 {
571         MathArray ar;
572         parse(ar, flags, mode);
573         return ar;
574 }
575
576
577 void Parser::parse(MathArray & array, unsigned flags, mode_type mode)
578 {
579         MathGridInset grid(1, 1);
580         parse1(grid, flags, mode, false);
581         array = grid.cell(0);
582 }
583
584
585 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
586         const bool numbered)
587 {
588         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
589 }
590
591
592 void Parser::parse1(MathGridInset & grid, unsigned flags,
593         const mode_type mode, const bool numbered)
594 {
595         int limits = 0;
596         MathGridInset::row_type cellrow = 0;
597         MathGridInset::col_type cellcol = 0;
598         MathArray * cell = &grid.cell(grid.index(cellrow, cellcol));
599
600         if (grid.asHullInset())
601                 grid.asHullInset()->numbered(cellrow, numbered);
602
603         //dump();
604         //lyxerr << " flags: " << flags << endl;
605         //lyxerr << " mode: " << mode  << endl;
606         //lyxerr << "grid: " << grid << endl;
607
608         while (good()) {
609                 Token const & t = getToken();
610
611 #ifdef FILEDEBUG
612                 lyxerr << "t: " << t << " flags: " << flags << endl;
613                 lyxerr << "mode: " << mode  << endl;
614                 cell->dump();
615                 lyxerr << endl;
616 #endif
617
618                 if (flags & FLAG_ITEM) {
619
620                 if (t.cat() == catBegin) {
621                                 // skip the brace and collect everything to the next matching
622                                 // closing brace
623                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
624                                 return;
625                         }
626
627                         // handle only this single token, leave the loop if done
628                         flags = FLAG_LEAVE;
629                 }
630
631
632                 if (flags & FLAG_BRACED) {
633                         if (t.cat() == catSpace)
634                                 continue;
635
636                         if (t.cat() != catBegin) {
637                                 error("opening brace expected");
638                                 return;
639                         }
640
641                         // skip the brace and collect everything to the next matching
642                         // closing brace
643                         flags = FLAG_BRACE_LAST;
644                 }
645
646
647                 if (flags & FLAG_OPTION) {
648                         if (t.cat() == catOther && t.character() == '[') {
649                                 MathArray ar;
650                                 parse(ar, FLAG_BRACK_LAST, mode);
651                                 cell->append(ar);
652                         } else {
653                                 // no option found, put back token and we are done
654                                 putback();
655                         }
656                         return;
657                 }
658
659                 //
660                 // cat codes
661                 //
662                 if (t.cat() == catMath) {
663                         if (mode != MathInset::MATH_MODE) {
664                                 // we are inside some text mode thingy, so opening new math is allowed
665                                 Token const & n = getToken();
666                                 if (n.cat() == catMath) {
667                                         // TeX's $$...$$ syntax for displayed math
668                                         cell->push_back(MathAtom(new MathHullInset("equation")));
669                                         parse2(cell->back(), FLAG_SIMPLE, MathInset::MATH_MODE, false);
670                                         getToken(); // skip the second '$' token
671                                 } else {
672                                         // simple $...$  stuff
673                                         putback();
674                                         cell->push_back(MathAtom(new MathHullInset("simple")));
675                                         parse2(cell->back(), FLAG_SIMPLE, MathInset::MATH_MODE, false);
676                                 }
677                         }
678
679                         else if (flags & FLAG_SIMPLE) {
680                                 // this is the end of the formula
681                                 return;
682                         }
683
684                         else {
685                                 error("something strange in the parser");
686                                 break;
687                         }
688                 }
689
690                 else if (t.cat() == catLetter)
691                         cell->push_back(MathAtom(new MathCharInset(t.character())));
692
693                 else if (t.cat() == catSpace && mode != MathInset::MATH_MODE) {
694                         if (cell->empty() || cell->back()->getChar() != ' ')
695                                 cell->push_back(MathAtom(new MathCharInset(t.character())));
696                 }
697
698                 else if (t.cat() == catNewline && mode != MathInset::MATH_MODE) {
699                         if (cell->empty() || cell->back()->getChar() != ' ')
700                                 cell->push_back(MathAtom(new MathCharInset(' ')));
701                 }
702
703                 else if (t.cat() == catParameter) {
704                         Token const & n = getToken();
705                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
706                 }
707
708                 else if (t.cat() == catActive)
709                         cell->push_back(MathAtom(new MathCharInset(t.character())));
710
711                 else if (t.cat() == catBegin) {
712                         MathArray ar;
713                         parse(ar, FLAG_BRACE_LAST, mode);
714                         // do not create a BraceInset if they were written by LyX
715                         // this helps to keep the annoyance of  "a choose b"  to a minimum
716                         if (ar.size() == 1 && ar[0]->extraBraces())
717                                 cell->append(ar);
718                         else
719                                 cell->push_back(MathAtom(new MathBraceInset(ar)));
720                 }
721
722                 else if (t.cat() == catEnd) {
723                         if (flags & FLAG_BRACE_LAST)
724                                 return;
725                         error("found '}' unexpectedly");
726                         //BOOST_ASSERT(false);
727                         //add(cell, '}', LM_TC_TEX);
728                 }
729
730                 else if (t.cat() == catAlign) {
731                         ++cellcol;
732                         //lyxerr << " column now " << cellcol << " max: " << grid.ncols() << endl;
733                         if (cellcol == grid.ncols()) {
734                                 //lyxerr << "adding column " << cellcol << endl;
735                                 grid.addCol(cellcol - 1);
736                         }
737                         cell = &grid.cell(grid.index(cellrow, cellcol));
738                 }
739
740                 else if (t.cat() == catSuper || t.cat() == catSub) {
741                         bool up = (t.cat() == catSuper);
742                         // we need no new script inset if the last thing was a scriptinset,
743                         // which has that script already not the same script already
744                         if (!cell->size())
745                                 cell->push_back(MathAtom(new MathScriptInset(up)));
746                         else if (cell->back()->asScriptInset() &&
747                                         !cell->back()->asScriptInset()->has(up))
748                                 cell->back().nucleus()->asScriptInset()->ensure(up);
749                         else if (cell->back()->asScriptInset())
750                                 cell->push_back(MathAtom(new MathScriptInset(up)));
751                         else
752                                 cell->back() = MathAtom(new MathScriptInset(cell->back(), up));
753                         MathScriptInset * p = cell->back().nucleus()->asScriptInset();
754                         // special handling of {}-bases
755                         // is this always correct?
756                         // It appears that this is wrong (Dekel)
757                         //if (p->nuc().size() == 1 && p->nuc().back()->asNestInset() &&
758                         //    p->nuc().back()->extraBraces())
759                         //      p->nuc() = p->nuc().back()->asNestInset()->cell(0);
760                         parse(p->cell(up), FLAG_ITEM, mode);
761                         if (limits) {
762                                 p->limits(limits);
763                                 limits = 0;
764                         }
765                 }
766
767                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
768                         //lyxerr << "finished reading option" << endl;
769                         return;
770                 }
771
772                 else if (t.cat() == catOther)
773                         cell->push_back(MathAtom(new MathCharInset(t.character())));
774
775                 else if (t.cat() == catComment) {
776                         string s;
777                         while (good()) {
778                                 Token const & t = getToken();
779                                 if (t.cat() == catNewline)
780                                         break;
781                                 s += t.asString();
782                         }
783                         cell->push_back(MathAtom(new MathCommentInset(s)));
784                         skipSpaces();
785                 }
786
787                 //
788                 // control sequences
789                 //
790
791                 else if (t.cs() == "lyxlock") {
792                         if (cell->size())
793                                 cell->back().nucleus()->lock(true);
794                 }
795
796                 else if (t.cs() == "def" ||
797                         t.cs() == "newcommand" ||
798                         t.cs() == "renewcommand")
799                 {
800                         string const type = t.cs();
801                         string name;
802                         int nargs = 0;
803                         if (t.cs() == "def") {
804                                 // get name
805                                 name = getToken().cs();
806
807                                 // read parameter
808                                 string pars;
809                                 while (good() && nextToken().cat() != catBegin) {
810                                         pars += getToken().cs();
811                                         ++nargs;
812                                 }
813                                 nargs /= 2;
814                                 //lyxerr << "read \\def parameter list '" << pars << "'" << endl;
815
816                         } else { // t.cs() == "newcommand" || t.cs() == "renewcommand"
817
818                                 if (getToken().cat() != catBegin) {
819                                         error("'{' in \\newcommand expected (1) ");
820                                         return;
821                                 }
822
823                                 name = getToken().cs();
824
825                                 if (getToken().cat() != catEnd) {
826                                         error("'}' in \\newcommand expected");
827                                         return;
828                                 }
829
830                                 string arg  = getArg('[', ']');
831                                 if (!arg.empty())
832                                         nargs = atoi(arg.c_str());
833
834                         }
835
836                         MathArray ar1;
837                         parse(ar1, FLAG_ITEM, MathInset::UNDECIDED_MODE);
838
839                         // we cannot handle recursive stuff at all
840                         //MathArray test;
841                         //test.push_back(createMathInset(name));
842                         //if (ar1.contains(test)) {
843                         //      error("we cannot handle recursive macros at all.");
844                         //      return;
845                         //}
846
847                         // is a version for display attached?
848                         skipSpaces();
849                         MathArray ar2;
850                         if (nextToken().cat() == catBegin)
851                                 parse(ar2, FLAG_ITEM, MathInset::MATH_MODE);
852
853                         cell->push_back(MathAtom(new MathMacroTemplate(name, nargs, type,
854                                 ar1, ar2)));
855                 }
856
857                 else if (t.cs() == "(") {
858                         cell->push_back(MathAtom(new MathHullInset("simple")));
859                         parse2(cell->back(), FLAG_SIMPLE2, MathInset::MATH_MODE, false);
860                 }
861
862                 else if (t.cs() == "[") {
863                         cell->push_back(MathAtom(new MathHullInset("equation")));
864                         parse2(cell->back(), FLAG_EQUATION, MathInset::MATH_MODE, false);
865                 }
866
867                 else if (t.cs() == "protect")
868                         // ignore \\protect, will hopefully be re-added during output
869                         ;
870
871                 else if (t.cs() == "end") {
872                         if (flags & FLAG_END) {
873                                 // eat environment name
874                                 //string const name =
875                                 getArg('{', '}');
876                                 // FIXME: check that we ended the correct environment
877                                 return;
878                         }
879                         error("found 'end' unexpectedly");
880                 }
881
882                 else if (t.cs() == ")") {
883                         if (flags & FLAG_SIMPLE2)
884                                 return;
885                         error("found '\\)' unexpectedly");
886                 }
887
888                 else if (t.cs() == "]") {
889                         if (flags & FLAG_EQUATION)
890                                 return;
891                         error("found '\\]' unexpectedly");
892                 }
893
894                 else if (t.cs() == "\\") {
895                         grid.vcrskip(LyXLength(getArg('[', ']')), cellrow);
896                         ++cellrow;
897                         cellcol = 0;
898                         if (cellrow == grid.nrows())
899                                 grid.addRow(cellrow - 1);
900                         if (grid.asHullInset())
901                                 grid.asHullInset()->numbered(cellrow, numbered);
902                         cell = &grid.cell(grid.index(cellrow, cellcol));
903                 }
904
905 #if 0
906                 else if (t.cs() == "multicolumn") {
907                         // extract column count and insert dummy cells
908                         MathArray count;
909                         parse(count, FLAG_ITEM, mode);
910                         int cols = 1;
911                         if (!extractNumber(count, cols)) {
912                                 lyxerr << " can't extract number of cells from " << count << endl;
913                         }
914                         // resize the table if necessary
915                         for (int i = 0; i < cols; ++i) {
916                                 ++cellcol;
917                                 if (cellcol == grid.ncols()) {
918                                         //lyxerr << "adding column " << cellcol << endl;
919                                         grid.addCol(cellcol - 1);
920                                 }
921                                 cell = &grid.cell(grid.index(cellrow, cellcol));
922                                 // mark this as dummy
923                                 grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = true;
924                         }
925                         // the last cell is the real thng, not a dummy
926                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
927
928                         // read special alignment
929                         MathArray align;
930                         parse(align, FLAG_ITEM, mode);
931                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
932
933                         // parse the remaining contents into the "real" cell
934                         parse(*cell, FLAG_ITEM, mode);
935                 }
936 #endif
937
938                 else if (t.cs() == "limits")
939                         limits = 1;
940
941                 else if (t.cs() == "nolimits")
942                         limits = -1;
943
944                 else if (t.cs() == "nonumber") {
945                         if (grid.asHullInset())
946                                 grid.asHullInset()->numbered(cellrow, false);
947                 }
948
949                 else if (t.cs() == "number") {
950                         if (grid.asHullInset())
951                                 grid.asHullInset()->numbered(cellrow, true);
952                 }
953
954                 else if (t.cs() == "hline") {
955                         grid.rowinfo(cellrow).lines_ ++;
956                 }
957
958                 else if (t.cs() == "sqrt") {
959                         MathArray ar;
960                         parse(ar, FLAG_OPTION, mode);
961                         if (ar.size()) {
962                                 cell->push_back(MathAtom(new MathRootInset));
963                                 cell->back().nucleus()->cell(0) = ar;
964                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
965                         } else {
966                                 cell->push_back(MathAtom(new MathSqrtInset));
967                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
968                         }
969                 }
970
971                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
972                         cell->push_back(createMathInset(t.cs()));
973                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
974                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
975                 }
976
977                 else if (t.cs() == "ref" || t.cs() == "prettyref" ||
978                                 t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
979                         cell->push_back(MathAtom(new RefInset(t.cs())));
980                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
981                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
982                 }
983
984                 else if (t.cs() == "left") {
985                         skipSpaces();
986                         string l = getToken().asString();
987                         MathArray ar;
988                         parse(ar, FLAG_RIGHT, mode);
989                         skipSpaces();
990                         string r = getToken().asString();
991                         cell->push_back(MathAtom(new MathDelimInset(l, r, ar)));
992                 }
993
994                 else if (t.cs() == "right") {
995                         if (flags & FLAG_RIGHT)
996                                 return;
997                         //lyxerr << "got so far: '" << cell << "'" << endl;
998                         error("Unmatched right delimiter");
999                         return;
1000                 }
1001
1002                 else if (t.cs() == "begin") {
1003                         string const name = getArg('{', '}');
1004
1005                         if (name == "array" || name == "subarray") {
1006                                 string const valign = parse_verbatim_option() + 'c';
1007                                 string const halign = parse_verbatim_item();
1008                                 cell->push_back(MathAtom(new MathArrayInset(name, valign[0], halign)));
1009                                 parse2(cell->back(), FLAG_END, mode, false);
1010                         }
1011
1012                         else if (name == "tabular") {
1013                                 string const valign = parse_verbatim_option() + 'c';
1014                                 string const halign = parse_verbatim_item();
1015                                 cell->push_back(MathAtom(new MathTabularInset(name, valign[0], halign)));
1016                                 parse2(cell->back(), FLAG_END, MathInset::TEXT_MODE, false);
1017                         }
1018
1019                         else if (name == "split" || name == "cases" ||
1020                                          name == "gathered" || name == "aligned") {
1021                                 cell->push_back(createMathInset(name));
1022                                 parse2(cell->back(), FLAG_END, mode, false);
1023                         }
1024
1025                         else if (name == "math") {
1026                                 cell->push_back(MathAtom(new MathHullInset("simple")));
1027                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, true);
1028                         }
1029
1030                         else if (name == "equation" || name == "equation*"
1031                                         || name == "displaymath") {
1032                                 cell->push_back(MathAtom(new MathHullInset("equation")));
1033                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, (name == "equation"));
1034                         }
1035
1036                         else if (name == "eqnarray" || name == "eqnarray*") {
1037                                 cell->push_back(MathAtom(new MathHullInset("eqnarray")));
1038                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1039                         }
1040
1041                         else if (name == "align" || name == "align*") {
1042                                 cell->push_back(MathAtom(new MathHullInset("align")));
1043                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1044                         }
1045
1046                         else if (name == "flalign" || name == "flalign*") {
1047                                 cell->push_back(MathAtom(new MathHullInset("flalign")));
1048                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1049                         }
1050
1051                         else if (name == "alignat" || name == "alignat*") {
1052                                 // ignore this for a while
1053                                 getArg('{', '}');
1054                                 cell->push_back(MathAtom(new MathHullInset("alignat")));
1055                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1056                         }
1057
1058                         else if (name == "xalignat" || name == "xalignat*") {
1059                                 // ignore this for a while
1060                                 getArg('{', '}');
1061                                 cell->push_back(MathAtom(new MathHullInset("xalignat")));
1062                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1063                         }
1064
1065                         else if (name == "xxalignat") {
1066                                 // ignore this for a while
1067                                 getArg('{', '}');
1068                                 cell->push_back(MathAtom(new MathHullInset("xxalignat")));
1069                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1070                         }
1071
1072                         else if (name == "multline" || name == "multline*") {
1073                                 cell->push_back(MathAtom(new MathHullInset("multline")));
1074                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1075                         }
1076
1077                         else if (name == "gather" || name == "gather*") {
1078                                 cell->push_back(MathAtom(new MathHullInset("gather")));
1079                                 parse2(cell->back(), FLAG_END, MathInset::MATH_MODE, !stared(name));
1080                         }
1081
1082                         else if (latexkeys const * l = in_word_set(name)) {
1083                                 if (l->inset == "matrix") {
1084                                         cell->push_back(createMathInset(name));
1085                                         parse2(cell->back(), FLAG_END, mode, false);
1086                                 }
1087                         }
1088
1089                         else {
1090                                 dump();
1091                                 lyxerr << "found unknown math environment '" << name << "'" << endl;
1092                                 // create generic environment inset
1093                                 cell->push_back(MathAtom(new MathEnvInset(name)));
1094                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1095                         }
1096                 }
1097
1098                 else if (t.cs() == "kern") {
1099 #ifdef WITH_WARNINGS
1100 #warning A hack...
1101 #endif
1102                         string s;
1103                         while (true) {
1104                                 Token const & t = getToken();
1105                                 if (!good()) {
1106                                         putback();
1107                                         break;
1108                                 }
1109                                 s += t.character();
1110                                 if (isValidLength(s))
1111                                         break;
1112                         }
1113                         cell->push_back(MathAtom(new MathKernInset(s)));
1114                 }
1115
1116                 else if (t.cs() == "label") {
1117                         string label = parse_verbatim_item();
1118                         MathArray ar;
1119                         asArray(label, ar);
1120                         if (grid.asHullInset()) {
1121                                 grid.asHullInset()->label(cellrow, label);
1122                         } else {
1123                                 cell->push_back(createMathInset(t.cs()));
1124                                 cell->push_back(MathAtom(new MathBraceInset(ar)));
1125                         }
1126                 }
1127
1128                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1129                         MathAtom at = createMathInset(t.cs());
1130                         at.nucleus()->cell(0) = *cell;
1131                         cell->clear();
1132                         parse(at.nucleus()->cell(1), flags, mode);
1133                         cell->push_back(at);
1134                         return;
1135                 }
1136
1137                 else if (t.cs() == "substack") {
1138                         cell->push_back(createMathInset(t.cs()));
1139                         parse2(cell->back(), FLAG_ITEM, mode, false);
1140                 }
1141
1142                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1143                         cell->push_back(createMathInset(t.cs()));
1144                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, MathInset::TEXT_MODE);
1145                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, MathInset::TEXT_MODE);
1146                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, MathInset::TEXT_MODE);
1147                 }
1148
1149 #if 0
1150                 else if (t.cs() == "infer") {
1151                         MathArray ar;
1152                         parse(ar, FLAG_OPTION, mode);
1153                         cell->push_back(createMathInset(t.cs()));
1154                         parse2(cell->back(), FLAG_ITEM, mode, false);
1155                 }
1156
1157                 // Disabled
1158                 else if (1 && t.cs() == "ar") {
1159                         MathXYArrowInset * p = new MathXYArrowInset;
1160                         // try to read target
1161                         parse(p->cell(0), FLAG_OTPTION, mode);
1162                         // try to read label
1163                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1164                                 p->up_ = nextToken().cat() == catSuper;
1165                                 getToken();
1166                                 parse(p->cell(1), FLAG_ITEM, mode);
1167                                 //lyxerr << "read label: " << p->cell(1) << endl;
1168                         }
1169
1170                         cell->push_back(MathAtom(p));
1171                         //lyxerr << "read cell: " << cell << endl;
1172                 }
1173 #endif
1174
1175                 else if (t.cs().size()) {
1176                         latexkeys const * l = in_word_set(t.cs());
1177                         if (l) {
1178                                 if (l->inset == "font") {
1179                                         cell->push_back(createMathInset(t.cs()));
1180                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, asMode(mode, l->extra));
1181                                 }
1182
1183                                 else if (l->inset == "oldfont") {
1184                                         cell->push_back(createMathInset(t.cs()));
1185                                         parse(cell->back().nucleus()->cell(0), flags, asMode(mode, l->extra));
1186                                         return;
1187                                 }
1188
1189                                 else if (l->inset == "style") {
1190                                         cell->push_back(createMathInset(t.cs()));
1191                                         parse(cell->back().nucleus()->cell(0), flags, mode);
1192                                         return;
1193                                 }
1194
1195                                 else if (l->inset == "parbox") {
1196                                         // read optional positioning and width
1197                                         string pos   = parse_verbatim_option();
1198                                         string width = parse_verbatim_item();
1199                                         cell->push_back(createMathInset(t.cs()));
1200                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, MathInset::TEXT_MODE);
1201                                         cell->back().nucleus()->asParboxInset()->setPosition(pos);
1202                                         cell->back().nucleus()->asParboxInset()->setWidth(width);
1203                                 }
1204
1205                                 else {
1206                                         MathAtom at = createMathInset(t.cs());
1207                                         for (MathInset::idx_type i = 0; i < at->nargs(); ++i)
1208                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, asMode(mode, l->extra));
1209                                         cell->push_back(at);
1210                                 }
1211                         }
1212
1213                         else {
1214                                 MathAtom at = createMathInset(t.cs());
1215                                 MathInset::mode_type m = mode;
1216                                 //if (m == MathInset::UNDECIDED_MODE)
1217                                 //lyxerr << "default creation: m1: " << m << endl;
1218                                 if (at->currentMode() != MathInset::UNDECIDED_MODE)
1219                                         m = at->currentMode();
1220                                 //lyxerr << "default creation: m2: " << m << endl;
1221                                 MathInset::idx_type start = 0;
1222                                 // this fails on \bigg[...\bigg]
1223                                 //MathArray opt;
1224                                 //parse(opt, FLAG_OPTION, MathInset::VERBATIM_MODE);
1225                                 //if (opt.size()) {
1226                                 //      start = 1;
1227                                 //      at.nucleus()->cell(0) = opt;
1228                                 //}
1229                                 for (MathInset::idx_type i = start; i < at->nargs(); ++i)
1230                                         parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1231                                 cell->push_back(at);
1232                         }
1233                 }
1234
1235
1236                 if (flags & FLAG_LEAVE) {
1237                         flags &= ~FLAG_LEAVE;
1238                         break;
1239                 }
1240         }
1241 }
1242
1243
1244
1245 } // anonymous namespace
1246
1247
1248 void mathed_parse_cell(MathArray & ar, string const & str)
1249 {
1250         istringstream is(str.c_str());
1251         mathed_parse_cell(ar, is);
1252 }
1253
1254
1255 void mathed_parse_cell(MathArray & ar, istream & is)
1256 {
1257         Parser(is).parse(ar, 0, MathInset::MATH_MODE);
1258 }
1259
1260
1261 bool mathed_parse_normal(MathAtom & t, string const & str)
1262 {
1263         istringstream is(str.c_str());
1264         return Parser(is).parse(t);
1265 }
1266
1267
1268 bool mathed_parse_normal(MathAtom & t, istream & is)
1269 {
1270         return Parser(is).parse(t);
1271 }
1272
1273
1274 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1275 {
1276         return Parser(lex).parse(t);
1277 }
1278
1279
1280 void mathed_parse_normal(MathGridInset & grid, string const & str)
1281 {
1282         istringstream is(str.c_str());
1283         Parser(is).parse1(grid, 0, MathInset::MATH_MODE, false);
1284 }