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