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