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