]> git.lyx.org Git - lyx.git/blob - src/mathed/MathParser.C
Scons: update_po target, part one: language_l10n.pot
[lyx.git] / src / mathed / MathParser.C
1 /**
2  * \file MathParser.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 /*
12
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
16
17   \newif\ifcomment
18   \commentfalse
19   \ifcomment
20           \def\makeamptab{\catcode`\&=4\relax}
21           \def\makeampletter{\catcode`\&=11\relax}
22     \def\b{\makeampletter\expandafter\makeamptab\bi}
23     \long\def\bi#1\e{}
24   \else
25     \def\b{}\def\e{}
26   \fi
27
28   ...
29
30   \[\begin{array}{ccc}
31 1
32 &
33
34   \end{array}\]
35
36 */
37
38
39 #include <config.h>
40
41 #include "MathParser.h"
42
43 #include "InsetMathArray.h"
44 #include "InsetMathBig.h"
45 #include "InsetMathBrace.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnv.h"
51 #include "InsetMathKern.h"
52 #include "InsetMathMacro.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 "lyxlex.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(LyXLength(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 - 1);
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         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 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 << '\\' << 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(LyXLex & 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(MathArray & array, unsigned flags, mode_type mode);
327         ///
328         void parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
329                 bool numbered);
330         ///
331         MathArray 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(LyXLex & 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         MathArray 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 MathArray Parser::parse(unsigned flags, mode_type mode)
669 {
670         MathArray ar;
671         parse(ar, flags, mode);
672         return ar;
673 }
674
675
676 void Parser::parse(MathArray & 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         MathArray * 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                                 MathArray 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                         MathArray 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                         MathArray ar1;
941                         parse(ar1, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
942
943                         // we cannot handle recursive stuff at all
944                         //MathArray 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                         MathArray 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                         MathArray 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                         MathArray 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                         MathArray 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 RefInset(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                         MathArray ar;
1121                         parse(ar, FLAG_RIGHT, mode);
1122                         skipSpaces();
1123                         Token const & tr = getToken();
1124                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1125                         cell->push_back(MathAtom(new InsetMathDelim(l, r, ar)));
1126                 }
1127
1128                 else if (t.cs() == "right") {
1129                         if (flags & FLAG_RIGHT)
1130                                 return;
1131                         //lyxerr << "got so far: '" << cell << "'" << endl;
1132                         error("Unmatched right delimiter");
1133                         return;
1134                 }
1135
1136                 else if (t.cs() == "begin") {
1137                         docstring const name = getArg('{', '}');
1138                         environments_.push_back(name);
1139
1140                         if (name == "array" || name == "subarray") {
1141                                 docstring const valign = parse_verbatim_option() + 'c';
1142                                 docstring const halign = parse_verbatim_item();
1143                                 cell->push_back(MathAtom(new InsetMathArray(name, (char)valign[0], halign)));
1144                                 parse2(cell->back(), FLAG_END, mode, false);
1145                         }
1146
1147                         else if (name == "tabular") {
1148                                 docstring const valign = parse_verbatim_option() + 'c';
1149                                 docstring const halign = parse_verbatim_item();
1150                                 cell->push_back(MathAtom(new InsetMathTabular(name, (char)valign[0], halign)));
1151                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1152                         }
1153
1154                         else if (name == "split" || name == "cases") {
1155                                 cell->push_back(createInsetMath(name));
1156                                 parse2(cell->back(), FLAG_END, mode, false);
1157                         }
1158
1159                         else if (name == "alignedat") {
1160                                 docstring const valign = parse_verbatim_option() + 'c';
1161                                 // ignore this for a while
1162                                 getArg('{', '}');
1163                                 cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1164                                 parse2(cell->back(), FLAG_END, mode, false);
1165                         }
1166
1167                         else if (name == "math") {
1168                                 cell->push_back(MathAtom(new InsetMathHull(hullSimple)));
1169                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, true);
1170                         }
1171
1172                         else if (name == "equation" || name == "equation*"
1173                                         || name == "displaymath") {
1174                                 cell->push_back(MathAtom(new InsetMathHull(hullEquation)));
1175                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1176                         }
1177
1178                         else if (name == "eqnarray" || name == "eqnarray*") {
1179                                 cell->push_back(MathAtom(new InsetMathHull(hullEqnArray)));
1180                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1181                         }
1182
1183                         else if (name == "align" || name == "align*") {
1184                                 cell->push_back(MathAtom(new InsetMathHull(hullAlign)));
1185                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1186                         }
1187
1188                         else if (name == "flalign" || name == "flalign*") {
1189                                 cell->push_back(MathAtom(new InsetMathHull(hullFlAlign)));
1190                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1191                         }
1192
1193                         else if (name == "alignat" || name == "alignat*") {
1194                                 // ignore this for a while
1195                                 getArg('{', '}');
1196                                 cell->push_back(MathAtom(new InsetMathHull(hullAlignAt)));
1197                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1198                         }
1199
1200                         else if (name == "xalignat" || name == "xalignat*") {
1201                                 // ignore this for a while
1202                                 getArg('{', '}');
1203                                 cell->push_back(MathAtom(new InsetMathHull(hullXAlignAt)));
1204                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1205                         }
1206
1207                         else if (name == "xxalignat") {
1208                                 // ignore this for a while
1209                                 getArg('{', '}');
1210                                 cell->push_back(MathAtom(new InsetMathHull(hullXXAlignAt)));
1211                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1212                         }
1213
1214                         else if (name == "multline" || name == "multline*") {
1215                                 cell->push_back(MathAtom(new InsetMathHull(hullMultline)));
1216                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1217                         }
1218
1219                         else if (name == "gather" || name == "gather*") {
1220                                 cell->push_back(MathAtom(new InsetMathHull(hullGather)));
1221                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1222                         }
1223
1224                         else if (latexkeys const * l = in_word_set(name)) {
1225                                 if (l->inset == "matrix") {
1226                                         cell->push_back(createInsetMath(name));
1227                                         parse2(cell->back(), FLAG_END, mode, false);
1228                                 } else if (l->inset == "split") {
1229                                         docstring const valign = parse_verbatim_option() + 'c';
1230                                         cell->push_back(MathAtom(new InsetMathSplit(name, (char)valign[0])));
1231                                         parse2(cell->back(), FLAG_END, mode, false);
1232                                 } else {
1233                                         dump();
1234                                         lyxerr << "found math environment `" << name
1235                                                << "' in symbols file with unsupported inset `"
1236                                                << l->inset << "'." << endl;
1237                                         // create generic environment inset
1238                                         cell->push_back(MathAtom(new InsetMathEnv(name)));
1239                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1240                                 }
1241                         }
1242
1243                         else {
1244                                 dump();
1245                                 lyxerr << "found unknown math environment '" << name << "'" << endl;
1246                                 // create generic environment inset
1247                                 cell->push_back(MathAtom(new InsetMathEnv(name)));
1248                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1249                         }
1250                 }
1251
1252                 else if (t.cs() == "kern") {
1253 #ifdef WITH_WARNINGS
1254 #warning A hack...
1255 #endif
1256                         docstring s;
1257                         while (true) {
1258                                 Token const & t = getToken();
1259                                 if (!good()) {
1260                                         putback();
1261                                         break;
1262                                 }
1263                                 s += t.character();
1264                                 if (isValidLength(to_utf8(s)))
1265                                         break;
1266                         }
1267                         cell->push_back(MathAtom(new InsetMathKern(s)));
1268                 }
1269
1270                 else if (t.cs() == "label") {
1271                         // FIXME: This is swallowed in inline formulas
1272                         docstring label = parse_verbatim_item();
1273                         MathArray ar;
1274                         asArray(label, ar);
1275                         if (grid.asHullInset()) {
1276                                 grid.asHullInset()->label(cellrow, label);
1277                         } else {
1278                                 cell->push_back(createInsetMath(t.cs()));
1279                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1280                         }
1281                 }
1282
1283                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1284                         MathAtom at = createInsetMath(t.cs());
1285                         at.nucleus()->cell(0) = *cell;
1286                         cell->clear();
1287                         parse(at.nucleus()->cell(1), flags, mode);
1288                         cell->push_back(at);
1289                         return;
1290                 }
1291
1292                 else if (t.cs() == "color") {
1293                         docstring const color = parse_verbatim_item();
1294                         cell->push_back(MathAtom(new InsetMathColor(true, color)));
1295                         parse(cell->back().nucleus()->cell(0), flags, mode);
1296                         return;
1297                 }
1298
1299                 else if (t.cs() == "textcolor") {
1300                         docstring const color = parse_verbatim_item();
1301                         cell->push_back(MathAtom(new InsetMathColor(false, color)));
1302                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1303                 }
1304
1305                 else if (t.cs() == "normalcolor") {
1306                         cell->push_back(createInsetMath(t.cs()));
1307                         parse(cell->back().nucleus()->cell(0), flags, mode);
1308                         return;
1309                 }
1310
1311                 else if (t.cs() == "substack") {
1312                         cell->push_back(createInsetMath(t.cs()));
1313                         parse2(cell->back(), FLAG_ITEM, mode, false);
1314                 }
1315
1316                 else if (t.cs() == "xymatrix") {
1317                         odocstringstream os;
1318                         while (good() && nextToken().cat() != catBegin)
1319                                 os << getToken().asInput();
1320                         cell->push_back(createInsetMath(t.cs() + os.str()));
1321                         parse2(cell->back(), FLAG_ITEM, mode, false);
1322                 }
1323
1324                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1325                         cell->push_back(createInsetMath(t.cs()));
1326                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1327                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1328                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1329                 }
1330
1331                 else if (t.cs() == "tag") {
1332                         if (nextToken().character() == '*') {
1333                                 getToken();
1334                                 cell->push_back(createInsetMath(t.cs() + '*'));
1335                         } else
1336                                 cell->push_back(createInsetMath(t.cs()));
1337                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1338                 }
1339
1340 #if 0
1341                 else if (t.cs() == "infer") {
1342                         MathArray ar;
1343                         parse(ar, FLAG_OPTION, mode);
1344                         cell->push_back(createInsetMath(t.cs()));
1345                         parse2(cell->back(), FLAG_ITEM, mode, false);
1346                 }
1347
1348                 // Disabled
1349                 else if (1 && t.cs() == "ar") {
1350                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1351                         // try to read target
1352                         parse(p->cell(0), FLAG_OTPTION, mode);
1353                         // try to read label
1354                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1355                                 p->up_ = nextToken().cat() == catSuper;
1356                                 getToken();
1357                                 parse(p->cell(1), FLAG_ITEM, mode);
1358                                 //lyxerr << "read label: " << p->cell(1) << endl;
1359                         }
1360
1361                         cell->push_back(MathAtom(p.release()));
1362                         //lyxerr << "read cell: " << cell << endl;
1363                 }
1364 #endif
1365
1366                 else if (t.cs().size()) {
1367                         latexkeys const * l = in_word_set(t.cs());
1368                         if (l) {
1369                                 if (l->inset == "big") {
1370                                         skipSpaces();
1371                                         docstring const delim = getToken().asInput();
1372                                         if (InsetMathBig::isBigInsetDelim(delim))
1373                                                 cell->push_back(MathAtom(
1374                                                         new InsetMathBig(t.cs(), delim)));
1375                                         else {
1376                                                 cell->push_back(createInsetMath(t.cs()));
1377                                                 putback();
1378                                         }
1379                                 }
1380
1381                                 else if (l->inset == "font") {
1382                                         cell->push_back(createInsetMath(t.cs()));
1383                                         parse(cell->back().nucleus()->cell(0),
1384                                                 FLAG_ITEM, asMode(mode, l->extra));
1385                                 }
1386
1387                                 else if (l->inset == "oldfont") {
1388                                         cell->push_back(createInsetMath(t.cs()));
1389                                         parse(cell->back().nucleus()->cell(0),
1390                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1391                                         if (prevToken().cat() != catAlign &&
1392                                             prevToken().cs() != "\\")
1393                                                 return;
1394                                         putback();
1395                                 }
1396
1397                                 else if (l->inset == "style") {
1398                                         cell->push_back(createInsetMath(t.cs()));
1399                                         parse(cell->back().nucleus()->cell(0),
1400                                                 flags | FLAG_ALIGN, mode);
1401                                         if (prevToken().cat() != catAlign &&
1402                                             prevToken().cs() != "\\")
1403                                                 return;
1404                                         putback();
1405                                 }
1406
1407                                 else {
1408                                         MathAtom at = createInsetMath(t.cs());
1409                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1410                                                 parse(at.nucleus()->cell(i),
1411                                                         FLAG_ITEM, asMode(mode, l->extra));
1412                                         cell->push_back(at);
1413                                 }
1414                         }
1415
1416                         else {
1417                                 MathAtom at = createInsetMath(t.cs());
1418                                 InsetMath::mode_type m = mode;
1419                                 //if (m == InsetMath::UNDECIDED_MODE)
1420                                 //lyxerr << "default creation: m1: " << m << endl;
1421                                 if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1422                                         m = at->currentMode();
1423                                 //lyxerr << "default creation: m2: " << m << endl;
1424                                 InsetMath::idx_type start = 0;
1425                                 // this fails on \bigg[...\bigg]
1426                                 //MathArray opt;
1427                                 //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1428                                 //if (opt.size()) {
1429                                 //      start = 1;
1430                                 //      at.nucleus()->cell(0) = opt;
1431                                 //}
1432                                 for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1433                                         parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1434                                         skipSpaces();
1435                                 }
1436                                 cell->push_back(at);
1437                         }
1438                 }
1439
1440
1441                 if (flags & FLAG_LEAVE) {
1442                         flags &= ~FLAG_LEAVE;
1443                         break;
1444                 }
1445         }
1446 }
1447
1448
1449
1450 } // anonymous namespace
1451
1452
1453 void mathed_parse_cell(MathArray & ar, docstring const & str)
1454 {
1455         Parser(str).parse(ar, 0, InsetMath::MATH_MODE);
1456 }
1457
1458
1459 void mathed_parse_cell(MathArray & ar, istream & is)
1460 {
1461         Parser(is).parse(ar, 0, InsetMath::MATH_MODE);
1462 }
1463
1464
1465 bool mathed_parse_normal(MathAtom & t, docstring const & str)
1466 {
1467         return Parser(str).parse(t);
1468 }
1469
1470
1471 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1472 {
1473         return Parser(lex).parse(t);
1474 }
1475
1476
1477 void mathed_parse_normal(InsetMathGrid & grid, docstring const & str)
1478 {
1479         Parser(str).parse1(grid, 0, InsetMath::MATH_MODE, false);
1480 }
1481
1482
1483 void initParser()
1484 {
1485         fill(theCatcode, theCatcode + 128, catOther);
1486         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
1487         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
1488
1489         theCatcode[int('\\')] = catEscape;
1490         theCatcode[int('{')]  = catBegin;
1491         theCatcode[int('}')]  = catEnd;
1492         theCatcode[int('$')]  = catMath;
1493         theCatcode[int('&')]  = catAlign;
1494         theCatcode[int('\n')] = catNewline;
1495         theCatcode[int('#')]  = catParameter;
1496         theCatcode[int('^')]  = catSuper;
1497         theCatcode[int('_')]  = catSub;
1498         theCatcode[int(0x7f)] = catIgnore;
1499         theCatcode[int(' ')]  = catSpace;
1500         theCatcode[int('\t')] = catSpace;
1501         theCatcode[int('\r')] = catNewline;
1502         theCatcode[int('~')]  = catActive;
1503         theCatcode[int('%')]  = catComment;
1504 }
1505
1506
1507 } // namespace lyx