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