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