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