]> git.lyx.org Git - lyx.git/blob - src/mathed/MathParser.cpp
make frontend::Application a bit slimmer
[lyx.git] / src / mathed / MathParser.cpp
1 /**
2  * \file MathParser.cpp
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   \[\begin{array}{ccc}
30 1
31 &
32
33   \end{array}\]
34
35 */
36
37
38 #include <config.h>
39
40 #include "MathParser.h"
41
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathChar.h"
46 #include "InsetMathColor.h"
47 #include "InsetMathComment.h"
48 #include "InsetMathDelim.h"
49 #include "InsetMathEnv.h"
50 #include "InsetMathFrac.h"
51 #include "InsetMathKern.h"
52 #include "MathMacro.h"
53 #include "InsetMathPar.h"
54 #include "InsetMathRef.h"
55 #include "InsetMathRoot.h"
56 #include "InsetMathScript.h"
57 #include "InsetMathSplit.h"
58 #include "InsetMathSqrt.h"
59 #include "InsetMathTabular.h"
60 #include "MathMacroTemplate.h"
61 #include "MathFactory.h"
62 #include "MathMacroArgument.h"
63 #include "MathSupport.h"
64
65 #include "Lexer.h"
66 #include "debug.h"
67
68 #include "support/convert.h"
69 #include "support/docstream.h"
70
71 #include <sstream>
72
73
74 namespace lyx {
75
76 using std::endl;
77 using std::fill;
78
79 using std::string;
80 using std::ios;
81 using std::istream;
82 using std::ostream;
83 using std::vector;
84
85
86 //#define FILEDEBUG
87
88
89 namespace {
90
91 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
92 {
93         //lyxerr << "handling mode: '" << str << "'" << endl;
94         if (str == "mathmode")
95                 return InsetMath::MATH_MODE;
96         if (str == "textmode" || str == "forcetext")
97                 return InsetMath::TEXT_MODE;
98         return oldmode;
99 }
100
101
102 bool stared(docstring const & s)
103 {
104         size_t const n = s.size();
105         return n && s[n - 1] == '*';
106 }
107
108
109 /*!
110  * Add the row \p cellrow to \p grid.
111  * \returns wether the row could be added. Adding a row can fail for
112  * environments like "equation" that have a fixed number of rows.
113  */
114 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
115             docstring const & vskip, bool allow_pagebreak = true)
116 {
117         ++cellrow;
118         if (cellrow == grid.nrows()) {
119                 //lyxerr << "adding row " << cellrow << endl;
120                 grid.addRow(cellrow - 1);
121                 if (cellrow == grid.nrows()) {
122                         // We can't add a row to this grid, so let's
123                         // append the content of this cell to the previous
124                         // one.
125                         // This does not happen in well formed .lyx files,
126                         // but LyX versions 1.3.x and older could create
127                         // such files and tex2lyx can still do that.
128                         --cellrow;
129                         lyxerr << "ignoring extra row";
130                         if (!vskip.empty())
131                                 lyxerr << " with extra space " << to_utf8(vskip);
132                         if (!allow_pagebreak)
133                                 lyxerr << " with no page break allowed";
134                         lyxerr << '.' << endl;
135                         return false;
136                 }
137         }
138         grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
139         grid.rowinfo(cellrow - 1).allow_pagebreak_ = allow_pagebreak;
140         return true;
141 }
142
143
144 /*!
145  * Add the column \p cellcol to \p grid.
146  * \returns wether the column could be added. Adding a column can fail for
147  * environments like "eqnarray" that have a fixed number of columns.
148  */
149 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
150 {
151         ++cellcol;
152         if (cellcol == grid.ncols()) {
153                 //lyxerr << "adding column " << cellcol << endl;
154                 grid.addCol(cellcol);
155                 if (cellcol == grid.ncols()) {
156                         // We can't add a column to this grid, so let's
157                         // append the content of this cell to the previous
158                         // one.
159                         // This does not happen in well formed .lyx files,
160                         // but LyX versions 1.3.x and older could create
161                         // such files and tex2lyx can still do that.
162                         --cellcol;
163                         lyxerr << "ignoring extra column." << endl;
164                         return false;
165                 }
166         }
167         return true;
168 }
169
170
171 /*!
172  * Check wether the last row is empty and remove it if yes.
173  * Otherwise the following code
174  * \verbatim
175 \begin{array}{|c|c|}
176 \hline
177 1 & 2 \\ \hline
178 3 & 4 \\ \hline
179 \end{array}
180  * \endverbatim
181  * will result in a grid with 3 rows (+ the dummy row that is always present),
182  * because the last '\\' opens a new row.
183  */
184 void delEmptyLastRow(InsetMathGrid & grid)
185 {
186         InsetMathGrid::row_type const row = grid.nrows() - 1;
187         for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
188                 if (!grid.cell(grid.index(row, col)).empty())
189                         return;
190         }
191         // Copy the row information of the empty row (which would contain the
192         // last hline in the example above) to the dummy row and delete the
193         // empty row.
194         grid.rowinfo(row + 1) = grid.rowinfo(row);
195         grid.delRow(row);
196 }
197
198
199 // These are TeX's catcodes
200 enum CatCode {
201         catEscape,     // 0    backslash
202         catBegin,      // 1    {
203         catEnd,        // 2    }
204         catMath,       // 3    $
205         catAlign,      // 4    &
206         catNewline,    // 5    ^^M
207         catParameter,  // 6    #
208         catSuper,      // 7    ^
209         catSub,        // 8    _
210         catIgnore,     // 9
211         catSpace,      // 10   space
212         catLetter,     // 11   a-zA-Z
213         catOther,      // 12   none of the above
214         catActive,     // 13   ~
215         catComment,    // 14   %
216         catInvalid     // 15   <delete>
217 };
218
219 CatCode theCatcode[128];
220
221
222 inline CatCode catcode(char_type c)
223 {
224         /* The only characters that are not catOther lie in the pure ASCII
225          * range. Therefore theCatcode has only 128 entries.
226          * TeX itself deals with 8bit characters, so if needed this table
227          * could be enlarged to 256 entries.
228          * Any larger value does not make sense, since the fact that we use
229          * unicode internally does not change Knuth's TeX engine.
230          * Apart from that a table for the full 21bit UCS4 range would waste
231          * too much memory. */
232         if (c >= 128)
233                 return catOther;
234
235         return theCatcode[c];
236 }
237
238
239 enum {
240         FLAG_ALIGN      = 1 << 0,  //  next & or \\ ends the parsing process
241         FLAG_BRACE_LAST = 1 << 1,  //  next closing brace ends the parsing
242         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
243         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
244         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
245         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
246         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced) token
247         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
248         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
249         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
250         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
251         FLAG_OPTION     = 1 << 11, //  read [...] style option
252         FLAG_BRACED     = 1 << 12  //  read {...} style argument
253 };
254
255
256 //
257 // Helper class for parsing
258 //
259
260 class Token {
261 public:
262         ///
263         Token() : cs_(), char_(0), cat_(catIgnore) {}
264         ///
265         Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
266         ///
267         explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
268
269         ///
270         docstring const & cs() const { return cs_; }
271         ///
272         CatCode cat() const { return cat_; }
273         ///
274         char_type character() const { return char_; }
275         ///
276         docstring asString() const { return cs_.size() ? cs_ : docstring(1, char_); }
277         ///
278         docstring asInput() const { return cs_.size() ? '\\' + cs_ : docstring(1, char_); }
279
280 private:
281         ///
282         docstring cs_;
283         ///
284         char_type char_;
285         ///
286         CatCode cat_;
287 };
288
289
290 ostream & operator<<(ostream & os, Token const & t)
291 {
292         if (t.cs().size()) {
293                 docstring const & cs = t.cs();
294                 // FIXME: For some strange reason, the stream operator instanciate
295                 // a new Token before outputting the contents of t.cs().
296                 // Because of this the line
297                 //     os << '\\' << cs;
298                 // below becomes recursive.
299                 // In order to avoid that we return early:
300                 if (cs == "\\")
301                         return os;
302                 os << '\\' << to_utf8(cs);
303         }
304         else if (t.cat() == catLetter)
305                 os << t.character();
306         else
307                 os << '[' << t.character() << ',' << t.cat() << ']';
308         return os;
309 }
310
311
312 class Parser {
313 public:
314         ///
315         typedef  InsetMath::mode_type mode_type;
316
317         ///
318         Parser(Lexer & lex);
319         /// Only use this for reading from .lyx file format, for the reason
320         /// see Parser::tokenize(std::istream &).
321         Parser(istream & is);
322         ///
323         Parser(docstring const & str);
324
325         ///
326         bool parse(MathAtom & at);
327         ///
328         void parse(MathData & array, unsigned flags, mode_type mode);
329         ///
330         void parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
331                 bool numbered);
332         ///
333         MathData parse(unsigned flags, mode_type mode);
334         ///
335         int lineno() const { return lineno_; }
336         ///
337         void putback();
338
339 private:
340         ///
341         void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
342         /// get arg delimited by 'left' and 'right'
343         docstring getArg(char_type left, char_type right);
344         ///
345         char_type getChar();
346         ///
347         void error(string const & msg);
348         void error(docstring const & msg) { error(to_utf8(msg)); }
349         /// dump contents to screen
350         void dump() const;
351         /// Only use this for reading from .lyx file format (see
352         /// implementation for reason)
353         void tokenize(istream & is);
354         ///
355         void tokenize(docstring const & s);
356         ///
357         void skipSpaceTokens(idocstream & is, char_type c);
358         ///
359         void push_back(Token const & t);
360         ///
361         void pop_back();
362         ///
363         Token const & prevToken() const;
364         ///
365         Token const & nextToken() const;
366         ///
367         Token const & getToken();
368         /// skips spaces if any
369         void skipSpaces();
370         ///
371         void lex(docstring const & s);
372         ///
373         bool good() const;
374         ///
375         docstring parse_verbatim_item();
376         ///
377         docstring parse_verbatim_option();
378
379         ///
380         int lineno_;
381         ///
382         vector<Token> tokens_;
383         ///
384         unsigned pos_;
385         /// Stack of active environments
386         vector<docstring> environments_;
387 };
388
389
390 Parser::Parser(Lexer & lexer)
391         : lineno_(lexer.getLineNo()), pos_(0)
392 {
393         tokenize(lexer.getStream());
394         lexer.eatLine();
395 }
396
397
398 Parser::Parser(istream & is)
399         : lineno_(0), pos_(0)
400 {
401         tokenize(is);
402 }
403
404
405 Parser::Parser(docstring const & str)
406         : lineno_(0), pos_(0)
407 {
408         tokenize(str);
409 }
410
411
412 void Parser::push_back(Token const & t)
413 {
414         tokens_.push_back(t);
415 }
416
417
418 void Parser::pop_back()
419 {
420         tokens_.pop_back();
421 }
422
423
424 Token const & Parser::prevToken() const
425 {
426         static const Token dummy;
427         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
428 }
429
430
431 Token const & Parser::nextToken() const
432 {
433         static const Token dummy;
434         return good() ? tokens_[pos_] : dummy;
435 }
436
437
438 Token const & Parser::getToken()
439 {
440         static const Token dummy;
441         //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
442         return good() ? tokens_[pos_++] : dummy;
443 }
444
445
446 void Parser::skipSpaces()
447 {
448         while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
449                 getToken();
450 }
451
452
453 void Parser::putback()
454 {
455         --pos_;
456 }
457
458
459 bool Parser::good() const
460 {
461         return pos_ < tokens_.size();
462 }
463
464
465 char_type Parser::getChar()
466 {
467         if (!good()) {
468                 error("The input stream is not well...");
469                 putback();
470                 return 0;
471         }
472         return tokens_[pos_++].character();
473 }
474
475
476 docstring Parser::getArg(char_type left, char_type right)
477 {
478         skipSpaces();
479
480         docstring result;
481         char_type c = getChar();
482
483         if (c != left)
484                 putback();
485         else
486                 while ((c = getChar()) != right && good())
487                         result += c;
488
489         return result;
490 }
491
492
493 void Parser::skipSpaceTokens(idocstream & is, char_type c)
494 {
495         // skip trailing spaces
496         while (catcode(c) == catSpace || catcode(c) == catNewline)
497                 if (!is.get(c))
498                         break;
499         //lyxerr << "putting back: " << c << endl;
500         is.putback(c);
501 }
502
503
504 void Parser::tokenize(istream & is)
505 {
506         // eat everything up to the next \end_inset or end of stream
507         // and store it in s for further tokenization
508         string s;
509         char c;
510         while (is.get(c)) {
511                 s += c;
512                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
513                         s = s.substr(0, s.size() - 10);
514                         break;
515                 }
516         }
517         // Remove the space after \end_inset
518         if (is.get(c) && c != ' ')
519                 is.unget();
520
521         // tokenize buffer
522         tokenize(from_utf8(s));
523 }
524
525
526 void Parser::tokenize(docstring const & buffer)
527 {
528         idocstringstream is(buffer, ios::in | ios::binary);
529
530         char_type c;
531         while (is.get(c)) {
532                 //lyxerr << "reading c: " << c << endl;
533
534                 switch (catcode(c)) {
535                         case catNewline: {
536                                 ++lineno_;
537                                 is.get(c);
538                                 if (catcode(c) == catNewline)
539                                         ; //push_back(Token("par"));
540                                 else {
541                                         push_back(Token('\n', catNewline));
542                                         is.putback(c);
543                                 }
544                                 break;
545                         }
546
547 /*
548                         case catComment: {
549                                 while (is.get(c) && catcode(c) != catNewline)
550                                         ;
551                                 ++lineno_;
552                                 break;
553                         }
554 */
555
556                         case catEscape: {
557                                 is.get(c);
558                                 if (!is) {
559                                         error("unexpected end of input");
560                                 } else {
561                                         docstring s(1, c);
562                                         if (catcode(c) == catLetter) {
563                                                 // collect letters
564                                                 while (is.get(c) && catcode(c) == catLetter)
565                                                         s += c;
566                                                 skipSpaceTokens(is, c);
567                                         }
568                                         push_back(Token(s));
569                                 }
570                                 break;
571                         }
572
573                         case catSuper:
574                         case catSub: {
575                                 push_back(Token(c, catcode(c)));
576                                 is.get(c);
577                                 skipSpaceTokens(is, c);
578                                 break;
579                         }
580
581                         case catIgnore: {
582                                 lyxerr << "ignoring a char: " << int(c) << endl;
583                                 break;
584                         }
585
586                         default:
587                                 push_back(Token(c, catcode(c)));
588                 }
589         }
590
591 #ifdef FILEDEBUG
592         dump();
593 #endif
594 }
595
596
597 void Parser::dump() const
598 {
599         lyxerr << "\nTokens: ";
600         for (unsigned i = 0; i < tokens_.size(); ++i) {
601                 if (i == pos_)
602                         lyxerr << " <#> ";
603                 lyxerr << tokens_[i];
604         }
605         lyxerr << " pos: " << pos_ << endl;
606 }
607
608
609 void Parser::error(string const & msg)
610 {
611         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
612         dump();
613         //exit(1);
614 }
615
616
617 bool Parser::parse(MathAtom & at)
618 {
619         skipSpaces();
620         MathData ar;
621         parse(ar, false, InsetMath::UNDECIDED_MODE);
622         if (ar.size() != 1 || ar.front()->getType() == hullNone) {
623                 lyxerr << "unusual contents found: " << ar << endl;
624                 at = MathAtom(new InsetMathPar(ar));
625                 //if (at->nargs() > 0)
626                 //      at.nucleus()->cell(0) = ar;
627                 //else
628                 //      lyxerr << "unusual contents found: " << ar << endl;
629                 return true;
630         }
631         at = ar[0];
632         return true;
633 }
634
635
636 docstring Parser::parse_verbatim_option()
637 {
638         skipSpaces();
639         docstring res;
640         if (nextToken().character() == '[') {
641                 Token t = getToken();
642                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
643                         if (t.cat() == catBegin) {
644                                 putback();
645                                 res += '{' + parse_verbatim_item() + '}';
646                         } else
647                                 res += t.asString();
648                 }
649         }
650         return res;
651 }
652
653
654 docstring Parser::parse_verbatim_item()
655 {
656         skipSpaces();
657         docstring res;
658         if (nextToken().cat() == catBegin) {
659                 Token t = getToken();
660                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
661                         if (t.cat() == catBegin) {
662                                 putback();
663                                 res += '{' + parse_verbatim_item() + '}';
664                         }
665                         else
666                                 res += t.asString();
667                 }
668         }
669         return res;
670 }
671
672
673 MathData Parser::parse(unsigned flags, mode_type mode)
674 {
675         MathData ar;
676         parse(ar, flags, mode);
677         return ar;
678 }
679
680
681 void Parser::parse(MathData & array, unsigned flags, mode_type mode)
682 {
683         InsetMathGrid grid(1, 1);
684         parse1(grid, flags, mode, false);
685         array = grid.cell(0);
686 }
687
688
689 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
690         const bool numbered)
691 {
692         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
693 }
694
695
696 void Parser::parse1(InsetMathGrid & grid, unsigned flags,
697         const mode_type mode, const bool numbered)
698 {
699         int limits = 0;
700         InsetMathGrid::row_type cellrow = 0;
701         InsetMathGrid::col_type cellcol = 0;
702         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
703
704         if (grid.asHullInset())
705                 grid.asHullInset()->numbered(cellrow, numbered);
706
707         //dump();
708         //lyxerr << " flags: " << flags << endl;
709         //lyxerr << " mode: " << mode  << endl;
710         //lyxerr << "grid: " << grid << endl;
711
712         while (good()) {
713                 Token const & t = getToken();
714
715 #ifdef FILEDEBUG
716                 lyxerr << "t: " << t << " flags: " << flags << endl;
717                 lyxerr << "mode: " << mode  << endl;
718                 cell->dump();
719                 lyxerr << endl;
720 #endif
721
722                 if (flags & FLAG_ITEM) {
723
724                         if (t.cat() == catBegin) {
725                                 // skip the brace and collect everything to the next matching
726                                 // closing brace
727                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
728                                 return;
729                         }
730
731                         // handle only this single token, leave the loop if done
732                         flags = FLAG_LEAVE;
733                 }
734
735
736                 if (flags & FLAG_BRACED) {
737                         if (t.cat() == catSpace)
738                                 continue;
739
740                         if (t.cat() != catBegin) {
741                                 error("opening brace expected");
742                                 return;
743                         }
744
745                         // skip the brace and collect everything to the next matching
746                         // closing brace
747                         flags = FLAG_BRACE_LAST;
748                 }
749
750
751                 if (flags & FLAG_OPTION) {
752                         if (t.cat() == catOther && t.character() == '[') {
753                                 MathData ar;
754                                 parse(ar, FLAG_BRACK_LAST, mode);
755                                 cell->append(ar);
756                         } else {
757                                 // no option found, put back token and we are done
758                                 putback();
759                         }
760                         return;
761                 }
762
763                 //
764                 // cat codes
765                 //
766                 if (t.cat() == catMath) {
767                         if (mode != InsetMath::MATH_MODE) {
768                                 // we are inside some text mode thingy, so opening new math is allowed
769                                 Token const & n = getToken();
770                                 if (n.cat() == catMath) {
771                                         // TeX's $$...$$ syntax for displayed math
772                                         cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
773                                         parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
774                                         getToken(); // skip the second '$' token
775                                 } else {
776                                         // simple $...$  stuff
777                                         putback();
778                                         cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
779                                         parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
780                                 }
781                         }
782
783                         else if (flags & FLAG_SIMPLE) {
784                                 // this is the end of the formula
785                                 return;
786                         }
787
788                         else {
789                                 error("something strange in the parser");
790                                 break;
791                         }
792                 }
793
794                 else if (t.cat() == catLetter)
795                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
796
797                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
798                         if (cell->empty() || cell->back()->getChar() != ' ')
799                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
800                 }
801
802                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
803                         if (cell->empty() || cell->back()->getChar() != ' ')
804                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
805                 }
806
807                 else if (t.cat() == catParameter) {
808                         Token const & n = getToken();
809                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
810                 }
811
812                 else if (t.cat() == catActive)
813                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
814
815                 else if (t.cat() == catBegin) {
816                         MathData ar;
817                         parse(ar, FLAG_BRACE_LAST, mode);
818                         // do not create a BraceInset if they were written by LyX
819                         // this helps to keep the annoyance of  "a choose b"  to a minimum
820                         if (ar.size() == 1 && ar[0]->extraBraces())
821                                 cell->append(ar);
822                         else
823                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
824                 }
825
826                 else if (t.cat() == catEnd) {
827                         if (flags & FLAG_BRACE_LAST)
828                                 return;
829                         error("found '}' unexpectedly");
830                         //BOOST_ASSERT(false);
831                         //add(cell, '}', LM_TC_TEX);
832                 }
833
834                 else if (t.cat() == catAlign) {
835                         //lyxerr << " column now " << (cellcol + 1)
836                         //       << " max: " << grid.ncols() << endl;
837                         if (flags & FLAG_ALIGN)
838                                 return;
839                         if (addCol(grid, cellcol))
840                                 cell = &grid.cell(grid.index(cellrow, cellcol));
841                 }
842
843                 else if (t.cat() == catSuper || t.cat() == catSub) {
844                         bool up = (t.cat() == catSuper);
845                         // we need no new script inset if the last thing was a scriptinset,
846                         // which has that script already not the same script already
847                         if (!cell->size())
848                                 cell->push_back(MathAtom(new InsetMathScript(up)));
849                         else if (cell->back()->asScriptInset() &&
850                                         !cell->back()->asScriptInset()->has(up))
851                                 cell->back().nucleus()->asScriptInset()->ensure(up);
852                         else if (cell->back()->asScriptInset())
853                                 cell->push_back(MathAtom(new InsetMathScript(up)));
854                         else
855                                 cell->back() = MathAtom(new InsetMathScript(cell->back(), up));
856                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
857                         // special handling of {}-bases
858                         // Here we could remove the brace inset for things
859                         // like {a'}^2 and add the braces back in
860                         // InsetMathScript::write().
861                         // We do not do it, since it is not possible to detect
862                         // reliably whether the braces are needed because the
863                         // nucleus contains more than one symbol, or whether
864                         // they are needed for unknown commands like \xx{a}_0
865                         // or \yy{a}{b}_0. This was done in revision 14819
866                         // in an unreliable way. See this thread
867                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
868                         // for more details.
869                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
870                         if (limits) {
871                                 p->limits(limits);
872                                 limits = 0;
873                         }
874                 }
875
876                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
877                         //lyxerr << "finished reading option" << endl;
878                         return;
879                 }
880
881                 else if (t.cat() == catOther)
882                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
883
884                 else if (t.cat() == catComment) {
885                         docstring s;
886                         while (good()) {
887                                 Token const & t = getToken();
888                                 if (t.cat() == catNewline)
889                                         break;
890                                 s += t.asString();
891                         }
892                         cell->push_back(MathAtom(new InsetMathComment(s)));
893                         skipSpaces();
894                 }
895
896                 //
897                 // control sequences
898                 //
899
900                 else if (t.cs() == "lyxlock") {
901                         if (cell->size())
902                                 cell->back().nucleus()->lock(true);
903                 }
904
905                 else if (t.cs() == "def" ||
906                         t.cs() == "newcommand" ||
907                         t.cs() == "renewcommand")
908                 {
909                         docstring const type = t.cs();
910                         docstring name;
911                         int nargs = 0;
912                         int optionals = 0;
913                         std::vector<MathData> optionalValues;
914                         if (t.cs() == "def") {
915                                 // get name
916                                 name = getToken().cs();
917
918                                 // read parameter
919                                 docstring pars;
920                                 while (good() && nextToken().cat() != catBegin) {
921                                         pars += getToken().cs();
922                                         ++nargs;
923                                 }
924                                 nargs /= 2;
925                                 //lyxerr << "read \\def parameter list '" << pars << "'" << endl;
926
927                         } else { // t.cs() == "newcommand" || t.cs() == "renewcommand"
928                                 if (getToken().cat() != catBegin) {
929                                         error("'{' in \\newcommand expected (1) ");
930                                         return;
931                                 }
932
933                                 name = getToken().cs();
934
935                                 if (getToken().cat() != catEnd) {
936                                         error("'}' in \\newcommand expected");
937                                         return;
938                                 }
939
940                                 docstring const arg = getArg('[', ']');
941                                 if (!arg.empty())
942                                         nargs = convert<int>(arg);
943
944                                 // optional argument given?
945                                 skipSpaces();
946                                 while (nextToken().character() == '[') {
947                                         getToken();
948                                         optionalValues.push_back(MathData());
949                                         parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
950                                         ++optionals;
951                                 }
952                         }
953
954                         MathData def;
955                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
956
957                         // is a version for display attached?
958                         skipSpaces();
959                         MathData display;
960                         if (nextToken().cat() == catBegin)
961                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
962
963                         cell->push_back(MathAtom(new MathMacroTemplate(name, nargs, optionals, type, 
964                                                                                                                                                                                                                  optionalValues, def, display)));
965                 }
966
967                 else if (t.cs() == "(") {
968                         cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
969                         parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
970                 }
971
972                 else if (t.cs() == "[") {
973                         cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
974                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
975                 }
976
977                 else if (t.cs() == "protect")
978                         // ignore \\protect, will hopefully be re-added during output
979                         ;
980
981                 else if (t.cs() == "end") {
982                         if (flags & FLAG_END) {
983                                 // eat environment name
984                                 docstring const name = getArg('{', '}');
985                                 if (environments_.empty())
986                                         error("'found \\end{" + name +
987                                               "}' without matching '\\begin{" +
988                                               name + "}'");
989                                 else if (name != environments_.back())
990                                         error("'\\end{" + name +
991                                               "}' does not match '\\begin{" +
992                                               environments_.back() + "}'");
993                                 else {
994                                         environments_.pop_back();
995                                         // Delete empty last row in matrix
996                                         // like insets.
997                                         // If you abuse InsetMathGrid for
998                                         // non-matrix like structures you
999                                         // probably need to refine this test.
1000                                         // Right now we only have to test for
1001                                         // single line hull insets.
1002                                         if (grid.nrows() > 1)
1003                                                 delEmptyLastRow(grid);
1004                                         return;
1005                                 }
1006                         } else
1007                                 error("found 'end' unexpectedly");
1008                 }
1009
1010                 else if (t.cs() == ")") {
1011                         if (flags & FLAG_SIMPLE2)
1012                                 return;
1013                         error("found '\\)' unexpectedly");
1014                 }
1015
1016                 else if (t.cs() == "]") {
1017                         if (flags & FLAG_EQUATION)
1018                                 return;
1019                         error("found '\\]' unexpectedly");
1020                 }
1021
1022                 else if (t.cs() == "\\") {
1023                         if (flags & FLAG_ALIGN)
1024                                 return;
1025                         bool added = false;
1026                         if (nextToken().asInput() == "*") {
1027                                 getToken();
1028                                 added = addRow(grid, cellrow, docstring(), false);
1029                         } else if (good())
1030                                 added = addRow(grid, cellrow, getArg('[', ']'));
1031                         else
1032                                 error("missing token after \\\\");
1033                         if (added) {
1034                                 cellcol = 0;
1035                                 if (grid.asHullInset())
1036                                         grid.asHullInset()->numbered(
1037                                                         cellrow, numbered);
1038                                 cell = &grid.cell(grid.index(cellrow,
1039                                                              cellcol));
1040                         }
1041                 }
1042
1043 #if 0
1044                 else if (t.cs() == "multicolumn") {
1045                         // extract column count and insert dummy cells
1046                         MathData count;
1047                         parse(count, FLAG_ITEM, mode);
1048                         int cols = 1;
1049                         if (!extractNumber(count, cols)) {
1050                                 lyxerr << " can't extract number of cells from " << count << endl;
1051                         }
1052                         // resize the table if necessary
1053                         for (int i = 0; i < cols; ++i) {
1054                                 if (addCol(grid, cellcol)) {
1055                                         cell = &grid.cell(grid.index(
1056                                                         cellrow, cellcol));
1057                                         // mark this as dummy
1058                                         grid.cellinfo(grid.index(
1059                                                 cellrow, cellcol)).dummy_ = true;
1060                                 }
1061                         }
1062                         // the last cell is the real thing, not a dummy
1063                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1064
1065                         // read special alignment
1066                         MathData align;
1067                         parse(align, FLAG_ITEM, mode);
1068                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1069
1070                         // parse the remaining contents into the "real" cell
1071                         parse(*cell, FLAG_ITEM, mode);
1072                 }
1073 #endif
1074
1075                 else if (t.cs() == "limits")
1076                         limits = 1;
1077
1078                 else if (t.cs() == "nolimits")
1079                         limits = -1;
1080
1081                 else if (t.cs() == "nonumber") {
1082                         if (grid.asHullInset())
1083                                 grid.asHullInset()->numbered(cellrow, false);
1084                 }
1085
1086                 else if (t.cs() == "number") {
1087                         if (grid.asHullInset())
1088                                 grid.asHullInset()->numbered(cellrow, true);
1089                 }
1090
1091                 else if (t.cs() == "hline") {
1092                         grid.rowinfo(cellrow).lines_ ++;
1093                 }
1094
1095                 else if (t.cs() == "sqrt") {
1096                         MathData ar;
1097                         parse(ar, FLAG_OPTION, mode);
1098                         if (ar.size()) {
1099                                 cell->push_back(MathAtom(new InsetMathRoot));
1100                                 cell->back().nucleus()->cell(0) = ar;
1101                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1102                         } else {
1103                                 cell->push_back(MathAtom(new InsetMathSqrt));
1104                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1105                         }
1106                 }
1107
1108                 else if (t.cs() == "unit") {
1109                         // Allowed formats \unit[val]{unit}
1110                         MathData ar;
1111                         parse(ar, FLAG_OPTION, mode);
1112                         if (ar.size()) {
1113                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT)));
1114                                 cell->back().nucleus()->cell(0) = ar;
1115                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1116                         } else {
1117                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT, 1)));
1118                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1119                         }
1120                 }
1121                 else if (t.cs() == "unitfrac") {
1122                         // Here allowed formats are \unitfrac[val]{num}{denom}
1123                         MathData ar;
1124                         parse(ar, FLAG_OPTION, mode);
1125                         if (ar.size()) {
1126                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC, 3)));
1127                                 cell->back().nucleus()->cell(2) = ar;
1128                         } else {
1129                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC)));
1130                         }
1131                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1132                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1133                 }
1134
1135                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1136                         cell->push_back(createInsetMath(t.cs()));
1137                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1138                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1139                 }
1140
1141                 else if (t.cs() == "ref" || t.cs() == "prettyref" ||
1142                                 t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1143                         cell->push_back(MathAtom(new InsetMathRef(t.cs())));
1144                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1145                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1146                 }
1147
1148                 else if (t.cs() == "left") {
1149                         skipSpaces();
1150                         Token const & tl = getToken();
1151                         // \| and \Vert are equivalent, and InsetMathDelim
1152                         // can't handle \|
1153                         // FIXME: fix this in InsetMathDelim itself!
1154                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1155                         MathData ar;
1156                         parse(ar, FLAG_RIGHT, mode);
1157                         if (!good())
1158                                 break;
1159                         skipSpaces();
1160                         Token const & tr = getToken();
1161                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1162                         cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1163                 }
1164
1165                 else if (t.cs() == "right") {
1166                         if (flags & FLAG_RIGHT)
1167                                 return;
1168                         //lyxerr << "got so far: '" << cell << "'" << endl;
1169                         error("Unmatched right delimiter");
1170                         return;
1171                 }
1172
1173                 else if (t.cs() == "begin") {
1174                         docstring const name = getArg('{', '}');
1175                         environments_.push_back(name);
1176
1177                         if (name == "array" || name == "subarray") {
1178                                 docstring const valign = parse_verbatim_option() + 'c';
1179                                 docstring const halign = parse_verbatim_item();
1180                                 cell->push_back(MathAtom(new InsetMathArray(name, (char)valign[0], halign)));
1181                                 parse2(cell->back(), FLAG_END, mode, false);
1182                         }
1183
1184                         else if (name == "tabular") {
1185                                 docstring const valign = parse_verbatim_option() + 'c';
1186                                 docstring const halign = parse_verbatim_item();
1187                                 cell->push_back(MathAtom(new InsetMathTabular(name, (char)valign[0], halign)));
1188                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1189                         }
1190
1191                         else if (name == "split" || name == "cases") {
1192                                 cell->push_back(createInsetMath(name));
1193                                 parse2(cell->back(), FLAG_END, mode, false);
1194                         }
1195
1196                         else if (name == "alignedat") {
1197                                 docstring const valign = parse_verbatim_option() + 'c';
1198                                 // ignore this for a while
1199                                 getArg('{', '}');
1200                                 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1201                                 parse2(cell->back(), FLAG_END, mode, false);
1202                         }
1203
1204                         else if (name == "math") {
1205                                 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1206                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1207                         }
1208
1209                         else if (name == "equation" || name == "equation*"
1210                                         || name == "displaymath") {
1211                                 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1212                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1213                         }
1214
1215                         else if (name == "eqnarray" || name == "eqnarray*") {
1216                                 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1217                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1218                         }
1219
1220                         else if (name == "align" || name == "align*") {
1221                                 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1222                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1223                         }
1224
1225                         else if (name == "flalign" || name == "flalign*") {
1226                                 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1227                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1228                         }
1229
1230                         else if (name == "alignat" || name == "alignat*") {
1231                                 // ignore this for a while
1232                                 getArg('{', '}');
1233                                 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1234                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1235                         }
1236
1237                         else if (name == "xalignat" || name == "xalignat*") {
1238                                 // ignore this for a while
1239                                 getArg('{', '}');
1240                                 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1241                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1242                         }
1243
1244                         else if (name == "xxalignat") {
1245                                 // ignore this for a while
1246                                 getArg('{', '}');
1247                                 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1248                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1249                         }
1250
1251                         else if (name == "multline" || name == "multline*") {
1252                                 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1253                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1254                         }
1255
1256                         else if (name == "gather" || name == "gather*") {
1257                                 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1258                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1259                         }
1260
1261                         else if (latexkeys const * l = in_word_set(name)) {
1262                                 if (l->inset == "matrix") {
1263                                         cell->push_back(createInsetMath(name));
1264                                         parse2(cell->back(), FLAG_END, mode, false);
1265                                 } else if (l->inset == "split") {
1266                                         docstring const valign = parse_verbatim_option() + 'c';
1267                                         cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1268                                         parse2(cell->back(), FLAG_END, mode, false);
1269                                 } else {
1270                                         dump();
1271                                         lyxerr << "found math environment `" << to_utf8(name)
1272                                                << "' in symbols file with unsupported inset `"
1273                                                << to_utf8(l->inset) << "'." << endl;
1274                                         // create generic environment inset
1275                                         cell->push_back(MathAtom(new InsetMathEnv(name)));
1276                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1277                                 }
1278                         }
1279
1280                         else {
1281                                 dump();
1282                                 lyxerr << "found unknown math environment '" << to_utf8(name)
1283                                         << "'" << endl;
1284                                 // create generic environment inset
1285                                 cell->push_back(MathAtom(new InsetMathEnv(name)));
1286                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1287                         }
1288                 }
1289
1290                 else if (t.cs() == "kern") {
1291                         // FIXME: A hack...
1292                         docstring s;
1293                         while (true) {
1294                                 Token const & t = getToken();
1295                                 if (!good()) {
1296                                         putback();
1297                                         break;
1298                                 }
1299                                 s += t.character();
1300                                 if (isValidLength(to_utf8(s)))
1301                                         break;
1302                         }
1303                         cell->push_back(MathAtom(new InsetMathKern(s)));
1304                 }
1305
1306                 else if (t.cs() == "label") {
1307                         // FIXME: This is swallowed in inline formulas
1308                         docstring label = parse_verbatim_item();
1309                         MathData ar;
1310                         asArray(label, ar);
1311                         if (grid.asHullInset()) {
1312                                 grid.asHullInset()->label(cellrow, label);
1313                         } else {
1314                                 cell->push_back(createInsetMath(t.cs()));
1315                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1316                         }
1317                 }
1318
1319                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1320                         MathAtom at = createInsetMath(t.cs());
1321                         at.nucleus()->cell(0) = *cell;
1322                         cell->clear();
1323                         parse(at.nucleus()->cell(1), flags, mode);
1324                         cell->push_back(at);
1325                         return;
1326                 }
1327
1328                 else if (t.cs() == "color") {
1329                         docstring const color = parse_verbatim_item();
1330                         cell->push_back(MathAtom(new InsetMathColor(true, color)));
1331                         parse(cell->back().nucleus()->cell(0), flags, mode);
1332                         return;
1333                 }
1334
1335                 else if (t.cs() == "textcolor") {
1336                         docstring const color = parse_verbatim_item();
1337                         cell->push_back(MathAtom(new InsetMathColor(false, color)));
1338                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1339                 }
1340
1341                 else if (t.cs() == "normalcolor") {
1342                         cell->push_back(createInsetMath(t.cs()));
1343                         parse(cell->back().nucleus()->cell(0), flags, mode);
1344                         return;
1345                 }
1346
1347                 else if (t.cs() == "substack") {
1348                         cell->push_back(createInsetMath(t.cs()));
1349                         parse2(cell->back(), FLAG_ITEM, mode, false);
1350                 }
1351
1352                 else if (t.cs() == "xymatrix") {
1353                         odocstringstream os;
1354                         while (good() && nextToken().cat() != catBegin)
1355                                 os << getToken().asInput();
1356                         cell->push_back(createInsetMath(t.cs() + os.str()));
1357                         parse2(cell->back(), FLAG_ITEM, mode, false);
1358                 }
1359
1360                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1361                         cell->push_back(createInsetMath(t.cs()));
1362                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1363                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1364                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1365                 }
1366
1367                 else if (t.cs() == "tag") {
1368                         if (nextToken().character() == '*') {
1369                                 getToken();
1370                                 cell->push_back(createInsetMath(t.cs() + '*'));
1371                         } else
1372                                 cell->push_back(createInsetMath(t.cs()));
1373                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1374                 }
1375
1376 #if 0
1377                 else if (t.cs() == "infer") {
1378                         MathData ar;
1379                         parse(ar, FLAG_OPTION, mode);
1380                         cell->push_back(createInsetMath(t.cs()));
1381                         parse2(cell->back(), FLAG_ITEM, mode, false);
1382                 }
1383
1384                 // Disabled
1385                 else if (1 && t.cs() == "ar") {
1386                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1387                         // try to read target
1388                         parse(p->cell(0), FLAG_OTPTION, mode);
1389                         // try to read label
1390                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1391                                 p->up_ = nextToken().cat() == catSuper;
1392                                 getToken();
1393                                 parse(p->cell(1), FLAG_ITEM, mode);
1394                                 //lyxerr << "read label: " << p->cell(1) << endl;
1395                         }
1396
1397                         cell->push_back(MathAtom(p.release()));
1398                         //lyxerr << "read cell: " << cell << endl;
1399                 }
1400 #endif
1401
1402                 else if (t.cs().size()) {
1403                         latexkeys const * l = in_word_set(t.cs());
1404                         if (l) {
1405                                 if (l->inset == "big") {
1406                                         skipSpaces();
1407                                         docstring const delim = getToken().asInput();
1408                                         if (InsetMathBig::isBigInsetDelim(delim))
1409                                                 cell->push_back(MathAtom(
1410                                                         new InsetMathBig(t.cs(), delim)));
1411                                         else {
1412                                                 cell->push_back(createInsetMath(t.cs()));
1413                                                 putback();
1414                                         }
1415                                 }
1416
1417                                 else if (l->inset == "font") {
1418                                         cell->push_back(createInsetMath(t.cs()));
1419                                         parse(cell->back().nucleus()->cell(0),
1420                                                 FLAG_ITEM, asMode(mode, l->extra));
1421                                 }
1422
1423                                 else if (l->inset == "oldfont") {
1424                                         cell->push_back(createInsetMath(t.cs()));
1425                                         parse(cell->back().nucleus()->cell(0),
1426                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1427                                         if (prevToken().cat() != catAlign &&
1428                                             prevToken().cs() != "\\")
1429                                                 return;
1430                                         putback();
1431                                 }
1432
1433                                 else if (l->inset == "style") {
1434                                         cell->push_back(createInsetMath(t.cs()));
1435                                         parse(cell->back().nucleus()->cell(0),
1436                                                 flags | FLAG_ALIGN, mode);
1437                                         if (prevToken().cat() != catAlign &&
1438                                             prevToken().cs() != "\\")
1439                                                 return;
1440                                         putback();
1441                                 }
1442
1443                                 else {
1444                                         MathAtom at = createInsetMath(t.cs());
1445                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1446                                                 parse(at.nucleus()->cell(i),
1447                                                         FLAG_ITEM, asMode(mode, l->extra));
1448                                         cell->push_back(at);
1449                                 }
1450                         }
1451
1452                         else {
1453                                 MathAtom at = createInsetMath(t.cs());
1454                                 InsetMath::mode_type m = mode;
1455                                 //if (m == InsetMath::UNDECIDED_MODE)
1456                                 //lyxerr << "default creation: m1: " << m << endl;
1457                                 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1458                                         m = at->currentMode();
1459                                 //lyxerr << "default creation: m2: " << m << endl;
1460                                 InsetMath::idx_type start = 0;
1461                                 // this fails on \bigg[...\bigg]
1462                                 //MathData opt;
1463                                 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1464                                 //if (opt.size()) {
1465                                 //      start = 1;
1466                                 //      at.nucleus()->cell(0) = opt;
1467                                 //}
1468                                 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1469                                         parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1470                                         skipSpaces();
1471                                 }
1472                                 cell->push_back(at);
1473                         }
1474                 }
1475
1476
1477                 if (flags & FLAG_LEAVE) {
1478                         flags &= ~FLAG_LEAVE;
1479                         break;
1480                 }
1481         }
1482 }
1483
1484
1485
1486 } // anonymous namespace
1487
1488
1489 void mathed_parse_cell(MathData & ar, docstring const & str)
1490 {
1491         Parser(str).parse(ar, 0, InsetMath::MATH_MODE);
1492 }
1493
1494
1495 void mathed_parse_cell(MathData & ar, istream & is)
1496 {
1497         Parser(is).parse(ar, 0, InsetMath::MATH_MODE);
1498 }
1499
1500
1501 bool mathed_parse_normal(MathAtom & t, docstring const & str)
1502 {
1503         return Parser(str).parse(t);
1504 }
1505
1506
1507 bool mathed_parse_normal(MathAtom & t, Lexer & lex)
1508 {
1509         return Parser(lex).parse(t);
1510 }
1511
1512
1513 void mathed_parse_normal(InsetMathGrid & grid, docstring const & str)
1514 {
1515         Parser(str).parse1(grid, 0, InsetMath::MATH_MODE, false);
1516 }
1517
1518
1519 void initParser()
1520 {
1521         fill(theCatcode, theCatcode + 128, catOther);
1522         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1523         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1524
1525         theCatcode[int('\\')] = catEscape;
1526         theCatcode[int('{')]  = catBegin;
1527         theCatcode[int('}')]  = catEnd;
1528         theCatcode[int('$')]  = catMath;
1529         theCatcode[int('&')]  = catAlign;
1530         theCatcode[int('\n')] = catNewline;
1531         theCatcode[int('#')]  = catParameter;
1532         theCatcode[int('^')]  = catSuper;
1533         theCatcode[int('_')]  = catSub;
1534         theCatcode[int(0x7f)] = catIgnore;
1535         theCatcode[int(' ')]  = catSpace;
1536         theCatcode[int('\t')] = catSpace;
1537         theCatcode[int('\r')] = catNewline;
1538         theCatcode[int('~')]  = catActive;
1539         theCatcode[int('%')]  = catComment;
1540 }
1541
1542
1543 } // namespace lyx