]> git.lyx.org Git - lyx.git/blob - src/mathed/MathParser.cpp
fc707e5a9ff4bded7710a911442a8a4f7053459f
[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.addRow(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         return tokens_[pos_++].character();
469 }
470
471
472 docstring Parser::getArg(char_type left, char_type right)
473 {
474         skipSpaces();
475
476         docstring result;
477         char_type c = getChar();
478
479         if (c != left)
480                 putback();
481         else
482                 while ((c = getChar()) != right && good())
483                         result += c;
484
485         return result;
486 }
487
488
489 void Parser::skipSpaceTokens(idocstream & is, char_type c)
490 {
491         // skip trailing spaces
492         while (catcode(c) == catSpace || catcode(c) == catNewline)
493                 if (!is.get(c))
494                         break;
495         //lyxerr << "putting back: " << c << endl;
496         is.putback(c);
497 }
498
499
500 void Parser::tokenize(istream & is)
501 {
502         // eat everything up to the next \end_inset or end of stream
503         // and store it in s for further tokenization
504         string s;
505         char c;
506         while (is.get(c)) {
507                 s += c;
508                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
509                         s = s.substr(0, s.size() - 10);
510                         break;
511                 }
512         }
513         // Remove the space after \end_inset
514         if (is.get(c) && c != ' ')
515                 is.unget();
516
517         // tokenize buffer
518         tokenize(from_utf8(s));
519 }
520
521
522 void Parser::tokenize(docstring const & buffer)
523 {
524         idocstringstream is(buffer, ios::in | ios::binary);
525
526         char_type c;
527         while (is.get(c)) {
528                 //lyxerr << "reading c: " << c << endl;
529
530                 switch (catcode(c)) {
531                         case catNewline: {
532                                 ++lineno_;
533                                 is.get(c);
534                                 if (catcode(c) == catNewline)
535                                         ; //push_back(Token("par"));
536                                 else {
537                                         push_back(Token('\n', catNewline));
538                                         is.putback(c);
539                                 }
540                                 break;
541                         }
542
543 /*
544                         case catComment: {
545                                 while (is.get(c) && catcode(c) != catNewline)
546                                         ;
547                                 ++lineno_;
548                                 break;
549                         }
550 */
551
552                         case catEscape: {
553                                 is.get(c);
554                                 if (!is) {
555                                         error("unexpected end of input");
556                                 } else {
557                                         docstring s(1, c);
558                                         if (catcode(c) == catLetter) {
559                                                 // collect letters
560                                                 while (is.get(c) && catcode(c) == catLetter)
561                                                         s += c;
562                                                 skipSpaceTokens(is, c);
563                                         }
564                                         push_back(Token(s));
565                                 }
566                                 break;
567                         }
568
569                         case catSuper:
570                         case catSub: {
571                                 push_back(Token(c, catcode(c)));
572                                 is.get(c);
573                                 skipSpaceTokens(is, c);
574                                 break;
575                         }
576
577                         case catIgnore: {
578                                 lyxerr << "ignoring a char: " << int(c) << endl;
579                                 break;
580                         }
581
582                         default:
583                                 push_back(Token(c, catcode(c)));
584                 }
585         }
586
587 #ifdef FILEDEBUG
588         dump();
589 #endif
590 }
591
592
593 void Parser::dump() const
594 {
595         lyxerr << "\nTokens: ";
596         for (unsigned i = 0; i < tokens_.size(); ++i) {
597                 if (i == pos_)
598                         lyxerr << " <#> ";
599                 lyxerr << tokens_[i];
600         }
601         lyxerr << " pos: " << pos_ << endl;
602 }
603
604
605 void Parser::error(string const & msg)
606 {
607         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
608         dump();
609         //exit(1);
610 }
611
612
613 bool Parser::parse(MathAtom & at)
614 {
615         skipSpaces();
616         MathData ar;
617         parse(ar, false, InsetMath::UNDECIDED_MODE);
618         if (ar.size() != 1 || ar.front()->getType() == hullNone) {
619                 lyxerr << "unusual contents found: " << ar << endl;
620                 at = MathAtom(new InsetMathPar(ar));
621                 //if (at->nargs() > 0)
622                 //      at.nucleus()->cell(0) = ar;
623                 //else
624                 //      lyxerr << "unusual contents found: " << ar << endl;
625                 return true;
626         }
627         at = ar[0];
628         return true;
629 }
630
631
632 docstring Parser::parse_verbatim_option()
633 {
634         skipSpaces();
635         docstring res;
636         if (nextToken().character() == '[') {
637                 Token t = getToken();
638                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
639                         if (t.cat() == catBegin) {
640                                 putback();
641                                 res += '{' + parse_verbatim_item() + '}';
642                         } else
643                                 res += t.asString();
644                 }
645         }
646         return res;
647 }
648
649
650 docstring Parser::parse_verbatim_item()
651 {
652         skipSpaces();
653         docstring res;
654         if (nextToken().cat() == catBegin) {
655                 Token t = getToken();
656                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
657                         if (t.cat() == catBegin) {
658                                 putback();
659                                 res += '{' + parse_verbatim_item() + '}';
660                         }
661                         else
662                                 res += t.asString();
663                 }
664         }
665         return res;
666 }
667
668
669 MathData Parser::parse(unsigned flags, mode_type mode)
670 {
671         MathData ar;
672         parse(ar, flags, mode);
673         return ar;
674 }
675
676
677 void Parser::parse(MathData & array, unsigned flags, mode_type mode)
678 {
679         InsetMathGrid grid(1, 1);
680         parse1(grid, flags, mode, false);
681         array = grid.cell(0);
682 }
683
684
685 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
686         const bool numbered)
687 {
688         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
689 }
690
691
692 void Parser::parse1(InsetMathGrid & grid, unsigned flags,
693         const mode_type mode, const bool numbered)
694 {
695         int limits = 0;
696         InsetMathGrid::row_type cellrow = 0;
697         InsetMathGrid::col_type cellcol = 0;
698         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
699
700         if (grid.asHullInset())
701                 grid.asHullInset()->numbered(cellrow, numbered);
702
703         //dump();
704         //lyxerr << " flags: " << flags << endl;
705         //lyxerr << " mode: " << mode  << endl;
706         //lyxerr << "grid: " << grid << endl;
707
708         while (good()) {
709                 Token const & t = getToken();
710
711 #ifdef FILEDEBUG
712                 lyxerr << "t: " << t << " flags: " << flags << endl;
713                 lyxerr << "mode: " << mode  << endl;
714                 cell->dump();
715                 lyxerr << endl;
716 #endif
717
718                 if (flags & FLAG_ITEM) {
719
720                         if (t.cat() == catBegin) {
721                                 // skip the brace and collect everything to the next matching
722                                 // closing brace
723                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
724                                 return;
725                         }
726
727                         // handle only this single token, leave the loop if done
728                         flags = FLAG_LEAVE;
729                 }
730
731
732                 if (flags & FLAG_BRACED) {
733                         if (t.cat() == catSpace)
734                                 continue;
735
736                         if (t.cat() != catBegin) {
737                                 error("opening brace expected");
738                                 return;
739                         }
740
741                         // skip the brace and collect everything to the next matching
742                         // closing brace
743                         flags = FLAG_BRACE_LAST;
744                 }
745
746
747                 if (flags & FLAG_OPTION) {
748                         if (t.cat() == catOther && t.character() == '[') {
749                                 MathData ar;
750                                 parse(ar, FLAG_BRACK_LAST, mode);
751                                 cell->append(ar);
752                         } else {
753                                 // no option found, put back token and we are done
754                                 putback();
755                         }
756                         return;
757                 }
758
759                 //
760                 // cat codes
761                 //
762                 if (t.cat() == catMath) {
763                         if (mode != InsetMath::MATH_MODE) {
764                                 // we are inside some text mode thingy, so opening new math is allowed
765                                 Token const & n = getToken();
766                                 if (n.cat() == catMath) {
767                                         // TeX's $$...$$ syntax for displayed math
768                                         cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
769                                         parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
770                                         getToken(); // skip the second '$' token
771                                 } else {
772                                         // simple $...$  stuff
773                                         putback();
774                                         cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
775                                         parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
776                                 }
777                         }
778
779                         else if (flags & FLAG_SIMPLE) {
780                                 // this is the end of the formula
781                                 return;
782                         }
783
784                         else {
785                                 error("something strange in the parser");
786                                 break;
787                         }
788                 }
789
790                 else if (t.cat() == catLetter)
791                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
792
793                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
794                         if (cell->empty() || cell->back()->getChar() != ' ')
795                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
796                 }
797
798                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
799                         if (cell->empty() || cell->back()->getChar() != ' ')
800                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
801                 }
802
803                 else if (t.cat() == catParameter) {
804                         Token const & n = getToken();
805                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
806                 }
807
808                 else if (t.cat() == catActive)
809                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
810
811                 else if (t.cat() == catBegin) {
812                         MathData ar;
813                         parse(ar, FLAG_BRACE_LAST, mode);
814                         // do not create a BraceInset if they were written by LyX
815                         // this helps to keep the annoyance of  "a choose b"  to a minimum
816                         if (ar.size() == 1 && ar[0]->extraBraces())
817                                 cell->append(ar);
818                         else
819                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
820                 }
821
822                 else if (t.cat() == catEnd) {
823                         if (flags & FLAG_BRACE_LAST)
824                                 return;
825                         error("found '}' unexpectedly");
826                         //BOOST_ASSERT(false);
827                         //add(cell, '}', LM_TC_TEX);
828                 }
829
830                 else if (t.cat() == catAlign) {
831                         //lyxerr << " column now " << (cellcol + 1)
832                         //       << " max: " << grid.ncols() << endl;
833                         if (flags & FLAG_ALIGN)
834                                 return;
835                         if (addCol(grid, cellcol))
836                                 cell = &grid.cell(grid.index(cellrow, cellcol));
837                 }
838
839                 else if (t.cat() == catSuper || t.cat() == catSub) {
840                         bool up = (t.cat() == catSuper);
841                         // we need no new script inset if the last thing was a scriptinset,
842                         // which has that script already not the same script already
843                         if (!cell->size())
844                                 cell->push_back(MathAtom(new InsetMathScript(up)));
845                         else if (cell->back()->asScriptInset() &&
846                                         !cell->back()->asScriptInset()->has(up))
847                                 cell->back().nucleus()->asScriptInset()->ensure(up);
848                         else if (cell->back()->asScriptInset())
849                                 cell->push_back(MathAtom(new InsetMathScript(up)));
850                         else
851                                 cell->back() = MathAtom(new InsetMathScript(cell->back(), up));
852                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
853                         // special handling of {}-bases
854                         // Here we could remove the brace inset for things
855                         // like {a'}^2 and add the braces back in
856                         // InsetMathScript::write().
857                         // We do not do it, since it is not possible to detect
858                         // reliably whether the braces are needed because the
859                         // nucleus contains more than one symbol, or whether
860                         // they are needed for unknown commands like \xx{a}_0
861                         // or \yy{a}{b}_0. This was done in revision 14819
862                         // in an unreliable way. See this thread
863                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
864                         // for more details.
865                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
866                         if (limits) {
867                                 p->limits(limits);
868                                 limits = 0;
869                         }
870                 }
871
872                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
873                         //lyxerr << "finished reading option" << endl;
874                         return;
875                 }
876
877                 else if (t.cat() == catOther)
878                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
879
880                 else if (t.cat() == catComment) {
881                         docstring s;
882                         while (good()) {
883                                 Token const & t = getToken();
884                                 if (t.cat() == catNewline)
885                                         break;
886                                 s += t.asString();
887                         }
888                         cell->push_back(MathAtom(new InsetMathComment(s)));
889                         skipSpaces();
890                 }
891
892                 //
893                 // control sequences
894                 //
895
896                 else if (t.cs() == "lyxlock") {
897                         if (cell->size())
898                                 cell->back().nucleus()->lock(true);
899                 }
900
901                 else if (t.cs() == "def" ||
902                         t.cs() == "newcommand" ||
903                         t.cs() == "renewcommand")
904                 {
905                         docstring const type = t.cs();
906                         docstring name;
907                         int nargs = 0;
908                         if (t.cs() == "def") {
909                                 // get name
910                                 name = getToken().cs();
911
912                                 // read parameter
913                                 docstring pars;
914                                 while (good() && nextToken().cat() != catBegin) {
915                                         pars += getToken().cs();
916                                         ++nargs;
917                                 }
918                                 nargs /= 2;
919                                 //lyxerr << "read \\def parameter list '" << pars << "'" << endl;
920
921                         } else { // t.cs() == "newcommand" || t.cs() == "renewcommand"
922
923                                 if (getToken().cat() != catBegin) {
924                                         error("'{' in \\newcommand expected (1) ");
925                                         return;
926                                 }
927
928                                 name = getToken().cs();
929
930                                 if (getToken().cat() != catEnd) {
931                                         error("'}' in \\newcommand expected");
932                                         return;
933                                 }
934
935                                 docstring const arg = getArg('[', ']');
936                                 if (!arg.empty())
937                                         nargs = convert<int>(arg);
938
939                         }
940
941                         MathData ar1;
942                         parse(ar1, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
943
944                         // we cannot handle recursive stuff at all
945                         //MathData test;
946                         //test.push_back(createInsetMath(name));
947                         //if (ar1.contains(test)) {
948                         //      error("we cannot handle recursive macros at all.");
949                         //      return;
950                         //}
951
952                         // is a version for display attached?
953                         skipSpaces();
954                         MathData ar2;
955                         if (nextToken().cat() == catBegin)
956                                 parse(ar2, FLAG_ITEM, InsetMath::MATH_MODE);
957
958                         cell->push_back(MathAtom(new MathMacroTemplate(name, nargs, type,
959                                 ar1, ar2)));
960                 }
961
962                 else if (t.cs() == "(") {
963                         cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
964                         parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
965                 }
966
967                 else if (t.cs() == "[") {
968                         cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
969                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
970                 }
971
972                 else if (t.cs() == "protect")
973                         // ignore \\protect, will hopefully be re-added during output
974                         ;
975
976                 else if (t.cs() == "end") {
977                         if (flags & FLAG_END) {
978                                 // eat environment name
979                                 docstring const name = getArg('{', '}');
980                                 if (environments_.empty())
981                                         error("'found \\end{" + name +
982                                               "}' without matching '\\begin{" +
983                                               name + "}'");
984                                 else if (name != environments_.back())
985                                         error("'\\end{" + name +
986                                               "}' does not match '\\begin{" +
987                                               environments_.back() + "}'");
988                                 else {
989                                         environments_.pop_back();
990                                         // Delete empty last row in matrix
991                                         // like insets.
992                                         // If you abuse InsetMathGrid for
993                                         // non-matrix like structures you
994                                         // probably need to refine this test.
995                                         // Right now we only have to test for
996                                         // single line hull insets.
997                                         if (grid.nrows() > 1)
998                                                 delEmptyLastRow(grid);
999                                         return;
1000                                 }
1001                         } else
1002                                 error("found 'end' unexpectedly");
1003                 }
1004
1005                 else if (t.cs() == ")") {
1006                         if (flags & FLAG_SIMPLE2)
1007                                 return;
1008                         error("found '\\)' unexpectedly");
1009                 }
1010
1011                 else if (t.cs() == "]") {
1012                         if (flags & FLAG_EQUATION)
1013                                 return;
1014                         error("found '\\]' unexpectedly");
1015                 }
1016
1017                 else if (t.cs() == "\\") {
1018                         if (flags & FLAG_ALIGN)
1019                                 return;
1020                         bool added;
1021                         if (nextToken().asInput() == "*") {
1022                                 getToken();
1023                                 added = addRow(grid, cellrow, docstring(), false);
1024                         } else
1025                                 added = addRow(grid, cellrow, getArg('[', ']'));
1026                         if (added) {
1027                                 cellcol = 0;
1028                                 if (grid.asHullInset())
1029                                         grid.asHullInset()->numbered(
1030                                                         cellrow, numbered);
1031                                 cell = &grid.cell(grid.index(cellrow,
1032                                                              cellcol));
1033                         }
1034                 }
1035
1036 #if 0
1037                 else if (t.cs() == "multicolumn") {
1038                         // extract column count and insert dummy cells
1039                         MathData count;
1040                         parse(count, FLAG_ITEM, mode);
1041                         int cols = 1;
1042                         if (!extractNumber(count, cols)) {
1043                                 lyxerr << " can't extract number of cells from " << count << endl;
1044                         }
1045                         // resize the table if necessary
1046                         for (int i = 0; i < cols; ++i) {
1047                                 if (addCol(grid, cellcol)) {
1048                                         cell = &grid.cell(grid.index(
1049                                                         cellrow, cellcol));
1050                                         // mark this as dummy
1051                                         grid.cellinfo(grid.index(
1052                                                 cellrow, cellcol)).dummy_ = true;
1053                                 }
1054                         }
1055                         // the last cell is the real thing, not a dummy
1056                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1057
1058                         // read special alignment
1059                         MathData align;
1060                         parse(align, FLAG_ITEM, mode);
1061                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1062
1063                         // parse the remaining contents into the "real" cell
1064                         parse(*cell, FLAG_ITEM, mode);
1065                 }
1066 #endif
1067
1068                 else if (t.cs() == "limits")
1069                         limits = 1;
1070
1071                 else if (t.cs() == "nolimits")
1072                         limits = -1;
1073
1074                 else if (t.cs() == "nonumber") {
1075                         if (grid.asHullInset())
1076                                 grid.asHullInset()->numbered(cellrow, false);
1077                 }
1078
1079                 else if (t.cs() == "number") {
1080                         if (grid.asHullInset())
1081                                 grid.asHullInset()->numbered(cellrow, true);
1082                 }
1083
1084                 else if (t.cs() == "hline") {
1085                         grid.rowinfo(cellrow).lines_ ++;
1086                 }
1087
1088                 else if (t.cs() == "sqrt") {
1089                         MathData ar;
1090                         parse(ar, FLAG_OPTION, mode);
1091                         if (ar.size()) {
1092                                 cell->push_back(MathAtom(new InsetMathRoot));
1093                                 cell->back().nucleus()->cell(0) = ar;
1094                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1095                         } else {
1096                                 cell->push_back(MathAtom(new InsetMathSqrt));
1097                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1098                         }
1099                 }
1100
1101                 else if (t.cs() == "unit") {
1102                         // Allowed formats \unit[val]{unit}
1103                         MathData ar;
1104                         parse(ar, FLAG_OPTION, mode);
1105                         if (ar.size()) {
1106                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT)));
1107                                 cell->back().nucleus()->cell(0) = ar;
1108                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1109                         } else {
1110                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNIT, 1)));
1111                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1112                         }
1113                 }
1114                 else if (t.cs() == "unitfrac") {
1115                         // Here allowed formats are \unitfrac[val]{num}{denom}
1116                         MathData ar;
1117                         parse(ar, FLAG_OPTION, mode);
1118                         if (ar.size()) {
1119                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC, 3)));
1120                                 cell->back().nucleus()->cell(2) = ar;
1121                         } else {
1122                                 cell->push_back(MathAtom(new InsetMathFrac(InsetMathFrac::UNITFRAC)));
1123                         }
1124                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1125                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1126                 }
1127
1128                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1129                         cell->push_back(createInsetMath(t.cs()));
1130                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1131                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1132                 }
1133
1134                 else if (t.cs() == "ref" || t.cs() == "prettyref" ||
1135                                 t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1136                         cell->push_back(MathAtom(new InsetMathRef(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() == "left") {
1142                         skipSpaces();
1143                         Token const & tl = getToken();
1144                         // \| and \Vert are equivalent, and InsetMathDelim
1145                         // can't handle \|
1146                         // FIXME: fix this in InsetMathDelim itself!
1147                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1148                         MathData ar;
1149                         parse(ar, FLAG_RIGHT, mode);
1150                         if (!good())
1151                                 break;
1152                         skipSpaces();
1153                         Token const & tr = getToken();
1154                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1155                         cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1156                 }
1157
1158                 else if (t.cs() == "right") {
1159                         if (flags & FLAG_RIGHT)
1160                                 return;
1161                         //lyxerr << "got so far: '" << cell << "'" << endl;
1162                         error("Unmatched right delimiter");
1163                         return;
1164                 }
1165
1166                 else if (t.cs() == "begin") {
1167                         docstring const name = getArg('{', '}');
1168                         environments_.push_back(name);
1169
1170                         if (name == "array" || name == "subarray") {
1171                                 docstring const valign = parse_verbatim_option() + 'c';
1172                                 docstring const halign = parse_verbatim_item();
1173                                 cell->push_back(MathAtom(new InsetMathArray(name, (char)valign[0], halign)));
1174                                 parse2(cell->back(), FLAG_END, mode, false);
1175                         }
1176
1177                         else if (name == "tabular") {
1178                                 docstring const valign = parse_verbatim_option() + 'c';
1179                                 docstring const halign = parse_verbatim_item();
1180                                 cell->push_back(MathAtom(new InsetMathTabular(name, (char)valign[0], halign)));
1181                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1182                         }
1183
1184                         else if (name == "split" || name == "cases") {
1185                                 cell->push_back(createInsetMath(name));
1186                                 parse2(cell->back(), FLAG_END, mode, false);
1187                         }
1188
1189                         else if (name == "alignedat") {
1190                                 docstring const valign = parse_verbatim_option() + 'c';
1191                                 // ignore this for a while
1192                                 getArg('{', '}');
1193                                 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1194                                 parse2(cell->back(), FLAG_END, mode, false);
1195                         }
1196
1197                         else if (name == "math") {
1198                                 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1199                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1200                         }
1201
1202                         else if (name == "equation" || name == "equation*"
1203                                         || name == "displaymath") {
1204                                 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1205                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1206                         }
1207
1208                         else if (name == "eqnarray" || name == "eqnarray*") {
1209                                 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1210                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1211                         }
1212
1213                         else if (name == "align" || name == "align*") {
1214                                 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1215                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1216                         }
1217
1218                         else if (name == "flalign" || name == "flalign*") {
1219                                 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1220                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1221                         }
1222
1223                         else if (name == "alignat" || name == "alignat*") {
1224                                 // ignore this for a while
1225                                 getArg('{', '}');
1226                                 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1227                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1228                         }
1229
1230                         else if (name == "xalignat" || name == "xalignat*") {
1231                                 // ignore this for a while
1232                                 getArg('{', '}');
1233                                 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1234                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1235                         }
1236
1237                         else if (name == "xxalignat") {
1238                                 // ignore this for a while
1239                                 getArg('{', '}');
1240                                 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1241                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1242                         }
1243
1244                         else if (name == "multline" || name == "multline*") {
1245                                 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1246                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1247                         }
1248
1249                         else if (name == "gather" || name == "gather*") {
1250                                 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1251                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1252                         }
1253
1254                         else if (latexkeys const * l = in_word_set(name)) {
1255                                 if (l->inset == "matrix") {
1256                                         cell->push_back(createInsetMath(name));
1257                                         parse2(cell->back(), FLAG_END, mode, false);
1258                                 } else if (l->inset == "split") {
1259                                         docstring const valign = parse_verbatim_option() + 'c';
1260                                         cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1261                                         parse2(cell->back(), FLAG_END, mode, false);
1262                                 } else {
1263                                         dump();
1264                                         lyxerr << "found math environment `" << to_utf8(name)
1265                                                << "' in symbols file with unsupported inset `"
1266                                                << to_utf8(l->inset) << "'." << endl;
1267                                         // create generic environment inset
1268                                         cell->push_back(MathAtom(new InsetMathEnv(name)));
1269                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1270                                 }
1271                         }
1272
1273                         else {
1274                                 dump();
1275                                 lyxerr << "found unknown math environment '" << to_utf8(name)
1276                                         << "'" << endl;
1277                                 // create generic environment inset
1278                                 cell->push_back(MathAtom(new InsetMathEnv(name)));
1279                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1280                         }
1281                 }
1282
1283                 else if (t.cs() == "kern") {
1284                         // FIXME: A hack...
1285                         docstring s;
1286                         while (true) {
1287                                 Token const & t = getToken();
1288                                 if (!good()) {
1289                                         putback();
1290                                         break;
1291                                 }
1292                                 s += t.character();
1293                                 if (isValidLength(to_utf8(s)))
1294                                         break;
1295                         }
1296                         cell->push_back(MathAtom(new InsetMathKern(s)));
1297                 }
1298
1299                 else if (t.cs() == "label") {
1300                         // FIXME: This is swallowed in inline formulas
1301                         docstring label = parse_verbatim_item();
1302                         MathData ar;
1303                         asArray(label, ar);
1304                         if (grid.asHullInset()) {
1305                                 grid.asHullInset()->label(cellrow, label);
1306                         } else {
1307                                 cell->push_back(createInsetMath(t.cs()));
1308                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1309                         }
1310                 }
1311
1312                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1313                         MathAtom at = createInsetMath(t.cs());
1314                         at.nucleus()->cell(0) = *cell;
1315                         cell->clear();
1316                         parse(at.nucleus()->cell(1), flags, mode);
1317                         cell->push_back(at);
1318                         return;
1319                 }
1320
1321                 else if (t.cs() == "color") {
1322                         docstring const color = parse_verbatim_item();
1323                         cell->push_back(MathAtom(new InsetMathColor(true, color)));
1324                         parse(cell->back().nucleus()->cell(0), flags, mode);
1325                         return;
1326                 }
1327
1328                 else if (t.cs() == "textcolor") {
1329                         docstring const color = parse_verbatim_item();
1330                         cell->push_back(MathAtom(new InsetMathColor(false, color)));
1331                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1332                 }
1333
1334                 else if (t.cs() == "normalcolor") {
1335                         cell->push_back(createInsetMath(t.cs()));
1336                         parse(cell->back().nucleus()->cell(0), flags, mode);
1337                         return;
1338                 }
1339
1340                 else if (t.cs() == "substack") {
1341                         cell->push_back(createInsetMath(t.cs()));
1342                         parse2(cell->back(), FLAG_ITEM, mode, false);
1343                 }
1344
1345                 else if (t.cs() == "xymatrix") {
1346                         odocstringstream os;
1347                         while (good() && nextToken().cat() != catBegin)
1348                                 os << getToken().asInput();
1349                         cell->push_back(createInsetMath(t.cs() + os.str()));
1350                         parse2(cell->back(), FLAG_ITEM, mode, false);
1351                 }
1352
1353                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1354                         cell->push_back(createInsetMath(t.cs()));
1355                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1356                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1357                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1358                 }
1359
1360                 else if (t.cs() == "tag") {
1361                         if (nextToken().character() == '*') {
1362                                 getToken();
1363                                 cell->push_back(createInsetMath(t.cs() + '*'));
1364                         } else
1365                                 cell->push_back(createInsetMath(t.cs()));
1366                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1367                 }
1368
1369 #if 0
1370                 else if (t.cs() == "infer") {
1371                         MathData ar;
1372                         parse(ar, FLAG_OPTION, mode);
1373                         cell->push_back(createInsetMath(t.cs()));
1374                         parse2(cell->back(), FLAG_ITEM, mode, false);
1375                 }
1376
1377                 // Disabled
1378                 else if (1 && t.cs() == "ar") {
1379                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1380                         // try to read target
1381                         parse(p->cell(0), FLAG_OTPTION, mode);
1382                         // try to read label
1383                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1384                                 p->up_ = nextToken().cat() == catSuper;
1385                                 getToken();
1386                                 parse(p->cell(1), FLAG_ITEM, mode);
1387                                 //lyxerr << "read label: " << p->cell(1) << endl;
1388                         }
1389
1390                         cell->push_back(MathAtom(p.release()));
1391                         //lyxerr << "read cell: " << cell << endl;
1392                 }
1393 #endif
1394
1395                 else if (t.cs().size()) {
1396                         latexkeys const * l = in_word_set(t.cs());
1397                         if (l) {
1398                                 if (l->inset == "big") {
1399                                         skipSpaces();
1400                                         docstring const delim = getToken().asInput();
1401                                         if (InsetMathBig::isBigInsetDelim(delim))
1402                                                 cell->push_back(MathAtom(
1403                                                         new InsetMathBig(t.cs(), delim)));
1404                                         else {
1405                                                 cell->push_back(createInsetMath(t.cs()));
1406                                                 putback();
1407                                         }
1408                                 }
1409
1410                                 else if (l->inset == "font") {
1411                                         cell->push_back(createInsetMath(t.cs()));
1412                                         parse(cell->back().nucleus()->cell(0),
1413                                                 FLAG_ITEM, asMode(mode, l->extra));
1414                                 }
1415
1416                                 else if (l->inset == "oldfont") {
1417                                         cell->push_back(createInsetMath(t.cs()));
1418                                         parse(cell->back().nucleus()->cell(0),
1419                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1420                                         if (prevToken().cat() != catAlign &&
1421                                             prevToken().cs() != "\\")
1422                                                 return;
1423                                         putback();
1424                                 }
1425
1426                                 else if (l->inset == "style") {
1427                                         cell->push_back(createInsetMath(t.cs()));
1428                                         parse(cell->back().nucleus()->cell(0),
1429                                                 flags | FLAG_ALIGN, mode);
1430                                         if (prevToken().cat() != catAlign &&
1431                                             prevToken().cs() != "\\")
1432                                                 return;
1433                                         putback();
1434                                 }
1435
1436                                 else {
1437                                         MathAtom at = createInsetMath(t.cs());
1438                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1439                                                 parse(at.nucleus()->cell(i),
1440                                                         FLAG_ITEM, asMode(mode, l->extra));
1441                                         cell->push_back(at);
1442                                 }
1443                         }
1444
1445                         else {
1446                                 MathAtom at = createInsetMath(t.cs());
1447                                 InsetMath::mode_type m = mode;
1448                                 //if (m == InsetMath::UNDECIDED_MODE)
1449                                 //lyxerr << "default creation: m1: " << m << endl;
1450                                 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1451                                         m = at->currentMode();
1452                                 //lyxerr << "default creation: m2: " << m << endl;
1453                                 InsetMath::idx_type start = 0;
1454                                 // this fails on \bigg[...\bigg]
1455                                 //MathData opt;
1456                                 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1457                                 //if (opt.size()) {
1458                                 //      start = 1;
1459                                 //      at.nucleus()->cell(0) = opt;
1460                                 //}
1461                                 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1462                                         parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1463                                         skipSpaces();
1464                                 }
1465                                 cell->push_back(at);
1466                         }
1467                 }
1468
1469
1470                 if (flags & FLAG_LEAVE) {
1471                         flags &= ~FLAG_LEAVE;
1472                         break;
1473                 }
1474         }
1475 }
1476
1477
1478
1479 } // anonymous namespace
1480
1481
1482 void mathed_parse_cell(MathData & ar, docstring const & str)
1483 {
1484         Parser(str).parse(ar, 0, InsetMath::MATH_MODE);
1485 }
1486
1487
1488 void mathed_parse_cell(MathData & ar, istream & is)
1489 {
1490         Parser(is).parse(ar, 0, InsetMath::MATH_MODE);
1491 }
1492
1493
1494 bool mathed_parse_normal(MathAtom & t, docstring const & str)
1495 {
1496         return Parser(str).parse(t);
1497 }
1498
1499
1500 bool mathed_parse_normal(MathAtom & t, Lexer & lex)
1501 {
1502         return Parser(lex).parse(t);
1503 }
1504
1505
1506 void mathed_parse_normal(InsetMathGrid & grid, docstring const & str)
1507 {
1508         Parser(str).parse1(grid, 0, InsetMath::MATH_MODE, false);
1509 }
1510
1511
1512 void initParser()
1513 {
1514         fill(theCatcode, theCatcode + 128, catOther);
1515         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1516         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1517
1518         theCatcode[int('\\')] = catEscape;
1519         theCatcode[int('{')]  = catBegin;
1520         theCatcode[int('}')]  = catEnd;
1521         theCatcode[int('$')]  = catMath;
1522         theCatcode[int('&')]  = catAlign;
1523         theCatcode[int('\n')] = catNewline;
1524         theCatcode[int('#')]  = catParameter;
1525         theCatcode[int('^')]  = catSuper;
1526         theCatcode[int('_')]  = catSub;
1527         theCatcode[int(0x7f)] = catIgnore;
1528         theCatcode[int(' ')]  = catSpace;
1529         theCatcode[int('\t')] = catSpace;
1530         theCatcode[int('\r')] = catNewline;
1531         theCatcode[int('~')]  = catActive;
1532         theCatcode[int('%')]  = catComment;
1533 }
1534
1535
1536 } // namespace lyx