]> git.lyx.org Git - features.git/blob - src/mathed/MathParser.cpp
Fix bug #8464: stackrel with subscript.
[features.git] / src / mathed / MathParser.cpp
1 /**
2  * \file MathParser.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 /*
12
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
16
17   \newif\ifcomment
18   \commentfalse
19   \ifcomment
20           \def\makeamptab{\catcode`\&=4\relax}
21           \def\makeampletter{\catcode`\&=11\relax}
22     \def\b{\makeampletter\expandafter\makeamptab\bi}
23     \long\def\bi#1\e{}
24   \else
25     \def\b{}\def\e{}
26   \fi
27   ...
28
29   \[\begin{array}{ccc}
30 1
31 &
32
33   \end{array}\]
34
35 */
36
37
38 #include <config.h>
39
40 #include "MathParser.h"
41
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathCancelto.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnsureMath.h"
51 #include "InsetMathEnv.h"
52 #include "InsetMathFrac.h"
53 #include "InsetMathKern.h"
54 #include "MathMacro.h"
55 #include "InsetMathPar.h"
56 #include "InsetMathRef.h"
57 #include "InsetMathRoot.h"
58 #include "InsetMathScript.h"
59 #include "InsetMathSpace.h"
60 #include "InsetMathSplit.h"
61 #include "InsetMathSqrt.h"
62 #include "InsetMathStackrel.h"
63 #include "InsetMathString.h"
64 #include "InsetMathTabular.h"
65 #include "MathMacroTemplate.h"
66 #include "MathFactory.h"
67 #include "MathMacroArgument.h"
68 #include "MathSupport.h"
69
70 #include "Buffer.h"
71 #include "BufferParams.h"
72 #include "Encoding.h"
73 #include "Lexer.h"
74
75 #include "support/debug.h"
76 #include "support/convert.h"
77 #include "support/docstream.h"
78
79 #include <sstream>
80
81 //#define FILEDEBUG
82
83 using namespace std;
84
85 namespace lyx {
86
87 namespace {
88
89 InsetMath::mode_type asMode(InsetMath::mode_type oldmode, docstring const & str)
90 {
91         //lyxerr << "handling mode: '" << str << "'" << endl;
92         if (str == "mathmode")
93                 return InsetMath::MATH_MODE;
94         if (str == "textmode" || str == "forcetext")
95                 return InsetMath::TEXT_MODE;
96         return oldmode;
97 }
98
99
100 bool stared(docstring const & s)
101 {
102         size_t const n = s.size();
103         return n && s[n - 1] == '*';
104 }
105
106
107 docstring const repl(docstring const & oldstr, char_type const c,
108                      docstring const & macro, bool textmode = false)
109 {
110         docstring newstr;
111         size_t i;
112         size_t j;
113
114         for (i = 0, j = 0; i < oldstr.size(); ++i) {
115                 if (c == oldstr[i]) {
116                         newstr.append(oldstr, j, i - j);
117                         newstr.append(macro);
118                         j = i + 1;
119                         if (macro.size() > 2 && j < oldstr.size())
120                                 newstr += (textmode && oldstr[j] == ' ' ? '\\' : ' ');
121                 }
122         }
123
124         // Any substitution?
125         if (j == 0)
126                 return oldstr;
127
128         newstr.append(oldstr, j, i - j);
129         return newstr;
130 }
131
132
133 docstring escapeSpecialChars(docstring const & str, bool textmode)
134 {
135         docstring const backslash = textmode ? from_ascii("\\textbackslash")
136                                              : from_ascii("\\backslash");
137         docstring const caret = textmode ? from_ascii("\\textasciicircum")
138                                          : from_ascii("\\mathcircumflex");
139         docstring const tilde = textmode ? from_ascii("\\textasciitilde")
140                                          : from_ascii("\\sim");
141
142         return repl(repl(repl(repl(repl(repl(repl(repl(repl(repl(str,
143                         '\\', backslash, textmode),
144                         '^', caret, textmode),
145                         '~', tilde, textmode),
146                         '_', from_ascii("\\_")),
147                         '$', from_ascii("\\$")),
148                         '#', from_ascii("\\#")),
149                         '&', from_ascii("\\&")),
150                         '%', from_ascii("\\%")),
151                         '{', from_ascii("\\{")),
152                         '}', from_ascii("\\}"));
153 }
154
155
156 /*!
157  * Add the row \p cellrow to \p grid.
158  * \returns wether the row could be added. Adding a row can fail for
159  * environments like "equation" that have a fixed number of rows.
160  */
161 bool addRow(InsetMathGrid & grid, InsetMathGrid::row_type & cellrow,
162             docstring const & vskip, bool allow_newpage_ = true)
163 {
164         ++cellrow;
165         if (cellrow == grid.nrows()) {
166                 //lyxerr << "adding row " << cellrow << endl;
167                 grid.addRow(cellrow - 1);
168                 if (cellrow == grid.nrows()) {
169                         // We can't add a row to this grid, so let's
170                         // append the content of this cell to the previous
171                         // one.
172                         // This does not happen in well formed .lyx files,
173                         // but LyX versions 1.3.x and older could create
174                         // such files and tex2lyx can still do that.
175                         --cellrow;
176                         lyxerr << "ignoring extra row";
177                         if (!vskip.empty())
178                                 lyxerr << " with extra space " << to_utf8(vskip);
179                         if (!allow_newpage_)
180                                 lyxerr << " with no page break allowed";
181                         lyxerr << '.' << endl;
182                         return false;
183                 }
184         }
185         grid.vcrskip(Length(to_utf8(vskip)), cellrow - 1);
186         grid.rowinfo(cellrow - 1).allow_newpage_ = allow_newpage_;
187         return true;
188 }
189
190
191 /*!
192  * Add the column \p cellcol to \p grid.
193  * \returns wether the column could be added. Adding a column can fail for
194  * environments like "eqnarray" that have a fixed number of columns.
195  */
196 bool addCol(InsetMathGrid & grid, InsetMathGrid::col_type & cellcol)
197 {
198         ++cellcol;
199         if (cellcol == grid.ncols()) {
200                 //lyxerr << "adding column " << cellcol << endl;
201                 grid.addCol(cellcol);
202                 if (cellcol == grid.ncols()) {
203                         // We can't add a column to this grid, so let's
204                         // append the content of this cell to the previous
205                         // one.
206                         // This does not happen in well formed .lyx files,
207                         // but LyX versions 1.3.x and older could create
208                         // such files and tex2lyx can still do that.
209                         --cellcol;
210                         lyxerr << "ignoring extra column." << endl;
211                         return false;
212                 }
213         }
214         return true;
215 }
216
217
218 /*!
219  * Check whether the last row is empty and remove it if yes.
220  * Otherwise the following code
221  * \verbatim
222 \begin{array}{|c|c|}
223 \hline
224 1 & 2 \\ \hline
225 3 & 4 \\ \hline
226 \end{array}
227  * \endverbatim
228  * will result in a grid with 3 rows (+ the dummy row that is always present),
229  * because the last '\\' opens a new row.
230  * Note that this is only needed for inner-hull grid types, such as array
231  * or aligned, but not for outer-hull grid types, such as eqnarray or align.
232  */
233 void delEmptyLastRow(InsetMathGrid & grid)
234 {
235         InsetMathGrid::row_type const row = grid.nrows() - 1;
236         for (InsetMathGrid::col_type col = 0; col < grid.ncols(); ++col) {
237                 if (!grid.cell(grid.index(row, col)).empty())
238                         return;
239         }
240         // Copy the row information of the empty row (which would contain the
241         // last hline in the example above) to the dummy row and delete the
242         // empty row.
243         grid.rowinfo(row + 1) = grid.rowinfo(row);
244         grid.delRow(row);
245 }
246
247
248 /*!
249  * Tell whether the environment name corresponds to an inner-hull grid type.
250  */
251 bool innerHull(docstring const & name)
252 {
253         // For [bB]matrix, [vV]matrix, and pmatrix we can check the suffix only
254         return name == "array" || name == "cases" || name == "aligned"
255                 || name == "alignedat" || name == "gathered" || name == "split"
256                 || name == "subarray" || name == "tabular" || name == "matrix"
257                 || name == "smallmatrix" || name.substr(1) == "matrix";
258 }
259
260
261 // These are TeX's catcodes
262 enum CatCode {
263         catEscape,     // 0    backslash
264         catBegin,      // 1    {
265         catEnd,        // 2    }
266         catMath,       // 3    $
267         catAlign,      // 4    &
268         catNewline,    // 5    ^^M
269         catParameter,  // 6    #
270         catSuper,      // 7    ^
271         catSub,        // 8    _
272         catIgnore,     // 9
273         catSpace,      // 10   space
274         catLetter,     // 11   a-zA-Z
275         catOther,      // 12   none of the above
276         catActive,     // 13   ~
277         catComment,    // 14   %
278         catInvalid     // 15   <delete>
279 };
280
281 CatCode theCatcode[128];
282
283
284 inline CatCode catcode(char_type c)
285 {
286         /* The only characters that are not catOther lie in the pure ASCII
287          * range. Therefore theCatcode has only 128 entries.
288          * TeX itself deals with 8bit characters, so if needed this table
289          * could be enlarged to 256 entries.
290          * Any larger value does not make sense, since the fact that we use
291          * unicode internally does not change Knuth's TeX engine.
292          * Apart from that a table for the full 21bit UCS4 range would waste
293          * too much memory. */
294         if (c >= 128)
295                 return catOther;
296
297         return theCatcode[c];
298 }
299
300
301 enum {
302         FLAG_ALIGN      = 1 << 0,  //  next & or \\ ends the parsing process
303         FLAG_BRACE_LAST = 1 << 1,  //  next closing brace ends the parsing
304         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
305         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
306         FLAG_BRACK_LAST = 1 << 4,  //  next closing bracket ends the parsing
307         FLAG_TEXTMODE   = 1 << 5,  //  we are in a box
308         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced) token
309         FLAG_LEAVE      = 1 << 7,  //  leave the loop at the end
310         FLAG_SIMPLE     = 1 << 8,  //  next $ leaves the loop
311         FLAG_EQUATION   = 1 << 9,  //  next \] leaves the loop
312         FLAG_SIMPLE2    = 1 << 10, //  next \) leaves the loop
313         FLAG_OPTION     = 1 << 11, //  read [...] style option
314         FLAG_BRACED     = 1 << 12  //  read {...} style argument
315 };
316
317
318 //
319 // Helper class for parsing
320 //
321
322 class Token {
323 public:
324         ///
325         Token() : cs_(), char_(0), cat_(catIgnore) {}
326         ///
327         Token(char_type c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
328         ///
329         explicit Token(docstring const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
330
331         ///
332         docstring const & cs() const { return cs_; }
333         ///
334         CatCode cat() const { return cat_; }
335         ///
336         char_type character() const { return char_; }
337         ///
338         docstring asString() const { return !cs_.empty() ? cs_ : docstring(1, char_); }
339         ///
340         docstring asInput() const { return !cs_.empty() ? '\\' + cs_ : docstring(1, char_); }
341
342 private:
343         ///
344         docstring cs_;
345         ///
346         char_type char_;
347         ///
348         CatCode cat_;
349 };
350
351
352 ostream & operator<<(ostream & os, Token const & t)
353 {
354         if (!t.cs().empty()) {
355                 docstring const & cs = t.cs();
356                 // FIXME: For some strange reason, the stream operator instanciate
357                 // a new Token before outputting the contents of t.cs().
358                 // Because of this the line
359                 //     os << '\\' << cs;
360                 // below becomes recursive.
361                 // In order to avoid that we return early:
362                 if (cs == "\\")
363                         return os;
364                 os << '\\' << to_utf8(cs);
365         }
366         else if (t.cat() == catLetter)
367                 os << t.character();
368         else
369                 os << '[' << t.character() << ',' << t.cat() << ']';
370         return os;
371 }
372
373
374 class Parser {
375 public:
376         ///
377         typedef  InsetMath::mode_type mode_type;
378         ///
379         typedef  Parse::flags parse_mode;
380
381         ///
382         Parser(Lexer & lex, parse_mode mode, Buffer * buf);
383         /// Only use this for reading from .lyx file format, for the reason
384         /// see Parser::tokenize(istream &).
385         Parser(istream & is, parse_mode mode, Buffer * buf);
386         ///
387         Parser(docstring const & str, parse_mode mode, Buffer * buf);
388
389         ///
390         bool parse(MathAtom & at);
391         ///
392         bool parse(MathData & array, unsigned flags, mode_type mode);
393         ///
394         bool parse1(InsetMathGrid & grid, unsigned flags, mode_type mode,
395                 bool numbered);
396         ///
397         MathData parse(unsigned flags, mode_type mode);
398         ///
399         int lineno() const { return lineno_; }
400         ///
401         void putback();
402
403 private:
404         ///
405         void parse2(MathAtom & at, unsigned flags, mode_type mode, bool numbered);
406         /// get arg delimited by 'left' and 'right'
407         docstring getArg(char_type left, char_type right);
408         ///
409         char_type getChar();
410         ///
411         void error(string const & msg);
412         void error(docstring const & msg) { error(to_utf8(msg)); }
413         /// dump contents to screen
414         void dump() const;
415         /// Only use this for reading from .lyx file format (see
416         /// implementation for reason)
417         void tokenize(istream & is);
418         ///
419         void tokenize(docstring const & s);
420         ///
421         void skipSpaceTokens(idocstream & is, char_type c);
422         ///
423         void push_back(Token const & t);
424         ///
425         void pop_back();
426         ///
427         Token const & prevToken() const;
428         ///
429         Token const & nextToken() const;
430         ///
431         Token const & getToken();
432         /// skips spaces if any
433         void skipSpaces();
434         ///
435         void lex(docstring const & s);
436         ///
437         bool good() const;
438         ///
439         docstring parse_verbatim_item();
440         ///
441         docstring parse_verbatim_option();
442
443         ///
444         int lineno_;
445         ///
446         vector<Token> tokens_;
447         ///
448         unsigned pos_;
449         /// Stack of active environments
450         vector<docstring> environments_;
451         ///
452         parse_mode mode_;
453         ///
454         bool success_;
455         ///
456         Buffer * buffer_;
457 };
458
459
460 Parser::Parser(Lexer & lexer, parse_mode mode, Buffer * buf)
461         : lineno_(lexer.lineNumber()), pos_(0), mode_(mode), success_(true),
462           buffer_(buf)
463 {
464         tokenize(lexer.getStream());
465         lexer.eatLine();
466 }
467
468
469 Parser::Parser(istream & is, parse_mode mode, Buffer * buf)
470         : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
471 {
472         tokenize(is);
473 }
474
475
476 Parser::Parser(docstring const & str, parse_mode mode, Buffer * buf)
477         : lineno_(0), pos_(0), mode_(mode), success_(true), buffer_(buf)
478 {
479         tokenize(str);
480 }
481
482
483 void Parser::push_back(Token const & t)
484 {
485         tokens_.push_back(t);
486 }
487
488
489 void Parser::pop_back()
490 {
491         tokens_.pop_back();
492 }
493
494
495 Token const & Parser::prevToken() const
496 {
497         static const Token dummy;
498         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
499 }
500
501
502 Token const & Parser::nextToken() const
503 {
504         static const Token dummy;
505         return good() ? tokens_[pos_] : dummy;
506 }
507
508
509 Token const & Parser::getToken()
510 {
511         static const Token dummy;
512         //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << endl;
513         return good() ? tokens_[pos_++] : dummy;
514 }
515
516
517 void Parser::skipSpaces()
518 {
519         while (nextToken().cat() == catSpace || nextToken().cat() == catNewline)
520                 getToken();
521 }
522
523
524 void Parser::putback()
525 {
526         --pos_;
527 }
528
529
530 bool Parser::good() const
531 {
532         return pos_ < tokens_.size();
533 }
534
535
536 char_type Parser::getChar()
537 {
538         if (!good()) {
539                 error("The input stream is not well...");
540                 return 0;
541         }
542         return tokens_[pos_++].character();
543 }
544
545
546 docstring Parser::getArg(char_type left, char_type right)
547 {
548         docstring result;
549         skipSpaces();
550
551         if (!good())
552                 return result;
553
554         char_type c = getChar();
555
556         if (c != left)
557                 putback();
558         else
559                 while ((c = getChar()) != right && good())
560                         result += c;
561
562         return result;
563 }
564
565
566 void Parser::skipSpaceTokens(idocstream & is, char_type c)
567 {
568         // skip trailing spaces
569         while (catcode(c) == catSpace || catcode(c) == catNewline)
570                 if (!is.get(c))
571                         break;
572         //lyxerr << "putting back: " << c << endl;
573         is.putback(c);
574 }
575
576
577 void Parser::tokenize(istream & is)
578 {
579         // eat everything up to the next \end_inset or end of stream
580         // and store it in s for further tokenization
581         string s;
582         char c;
583         while (is.get(c)) {
584                 s += c;
585                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
586                         s = s.substr(0, s.size() - 10);
587                         break;
588                 }
589         }
590         // Remove the space after \end_inset
591         if (is.get(c) && c != ' ')
592                 is.unget();
593
594         // tokenize buffer
595         tokenize(from_utf8(s));
596 }
597
598
599 void Parser::tokenize(docstring const & buffer)
600 {
601         idocstringstream is(mode_ & Parse::VERBATIM
602                         ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
603                         : buffer, ios::in | ios::binary);
604
605         char_type c;
606         while (is.get(c)) {
607                 //lyxerr << "reading c: " << c << endl;
608
609                 switch (catcode(c)) {
610                         case catNewline: {
611                                 ++lineno_;
612                                 is.get(c);
613                                 if (catcode(c) == catNewline)
614                                         ; //push_back(Token("par"));
615                                 else {
616                                         push_back(Token('\n', catNewline));
617                                         is.putback(c);
618                                 }
619                                 break;
620                         }
621
622 /*
623                         case catComment: {
624                                 while (is.get(c) && catcode(c) != catNewline)
625                                         ;
626                                 ++lineno_;
627                                 break;
628                         }
629 */
630
631                         case catEscape: {
632                                 is.get(c);
633                                 if (!is) {
634                                         error("unexpected end of input");
635                                 } else {
636                                         if (c == '\n')
637                                                 c = ' ';
638                                         docstring s(1, c);
639                                         if (catcode(c) == catLetter) {
640                                                 // collect letters
641                                                 while (is.get(c) && catcode(c) == catLetter)
642                                                         s += c;
643                                                 skipSpaceTokens(is, c);
644                                         }
645                                         push_back(Token(s));
646                                 }
647                                 break;
648                         }
649
650                         case catSuper:
651                         case catSub: {
652                                 push_back(Token(c, catcode(c)));
653                                 is.get(c);
654                                 skipSpaceTokens(is, c);
655                                 break;
656                         }
657
658                         case catIgnore: {
659                                 if (!(mode_ & Parse::QUIET))
660                                         lyxerr << "ignoring a char: " << int(c) << endl;
661                                 break;
662                         }
663
664                         default:
665                                 push_back(Token(c, catcode(c)));
666                 }
667         }
668
669 #ifdef FILEDEBUG
670         dump();
671 #endif
672 }
673
674
675 void Parser::dump() const
676 {
677         lyxerr << "\nTokens: ";
678         for (unsigned i = 0; i < tokens_.size(); ++i) {
679                 if (i == pos_)
680                         lyxerr << " <#> ";
681                 lyxerr << tokens_[i];
682         }
683         lyxerr << " pos: " << pos_ << endl;
684 }
685
686
687 void Parser::error(string const & msg)
688 {
689         success_ = false;
690         if (!(mode_ & Parse::QUIET)) {
691                 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
692                        << msg << endl;
693                 dump();
694         }
695 }
696
697
698 bool Parser::parse(MathAtom & at)
699 {
700         skipSpaces();
701         MathData ar(buffer_);
702         parse(ar, false, InsetMath::UNDECIDED_MODE);
703         if (ar.size() != 1 || ar.front()->getType() == hullNone) {
704                 if (!(mode_ & Parse::QUIET))
705                         lyxerr << "unusual contents found: " << ar << endl;
706                 at = MathAtom(new InsetMathPar(buffer_, ar));
707                 //if (at->nargs() > 0)
708                 //      at.nucleus()->cell(0) = ar;
709                 //else
710                 //      lyxerr << "unusual contents found: " << ar << endl;
711                 success_ = false;
712         } else
713                 at = ar[0];
714         return success_;
715 }
716
717
718 docstring Parser::parse_verbatim_option()
719 {
720         skipSpaces();
721         docstring res;
722         if (nextToken().character() == '[') {
723                 Token t = getToken();
724                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
725                         if (t.cat() == catBegin) {
726                                 putback();
727                                 res += '{' + parse_verbatim_item() + '}';
728                         } else
729                                 res += t.asInput();
730                 }
731         }
732         return res;
733 }
734
735
736 docstring Parser::parse_verbatim_item()
737 {
738         skipSpaces();
739         docstring res;
740         if (nextToken().cat() == catBegin) {
741                 Token t = getToken();
742                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
743                         if (t.cat() == catBegin) {
744                                 putback();
745                                 res += '{' + parse_verbatim_item() + '}';
746                         }
747                         else
748                                 res += t.asInput();
749                 }
750         }
751         return res;
752 }
753
754
755 MathData Parser::parse(unsigned flags, mode_type mode)
756 {
757         MathData ar(buffer_);
758         parse(ar, flags, mode);
759         return ar;
760 }
761
762
763 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
764 {
765         InsetMathGrid grid(buffer_, 1, 1);
766         parse1(grid, flags, mode, false);
767         array = grid.cell(0);
768         return success_;
769 }
770
771
772 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
773         const bool numbered)
774 {
775         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
776 }
777
778
779 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
780         const mode_type mode, const bool numbered)
781 {
782         int limits = 0;
783         InsetMathGrid::row_type cellrow = 0;
784         InsetMathGrid::col_type cellcol = 0;
785         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
786         Buffer * buf = buffer_;
787
788         if (grid.asHullInset())
789                 grid.asHullInset()->numbered(cellrow, numbered);
790
791         //dump();
792         //lyxerr << " flags: " << flags << endl;
793         //lyxerr << " mode: " << mode  << endl;
794         //lyxerr << "grid: " << grid << endl;
795
796         while (good()) {
797                 Token const & t = getToken();
798
799 #ifdef FILEDEBUG
800                 lyxerr << "t: " << t << " flags: " << flags << endl;
801                 lyxerr << "mode: " << mode  << endl;
802                 cell->dump();
803                 lyxerr << endl;
804 #endif
805
806                 if (flags & FLAG_ITEM) {
807
808                         if (t.cat() == catBegin) {
809                                 // skip the brace and collect everything to the next matching
810                                 // closing brace
811                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
812                                 return success_;
813                         }
814
815                         // handle only this single token, leave the loop if done
816                         flags = FLAG_LEAVE;
817                 }
818
819
820                 if (flags & FLAG_BRACED) {
821                         if (t.cat() == catSpace)
822                                 continue;
823
824                         if (t.cat() != catBegin) {
825                                 error("opening brace expected");
826                                 return success_;
827                         }
828
829                         // skip the brace and collect everything to the next matching
830                         // closing brace
831                         flags = FLAG_BRACE_LAST;
832                 }
833
834
835                 if (flags & FLAG_OPTION) {
836                         if (t.cat() == catOther && t.character() == '[') {
837                                 MathData ar;
838                                 parse(ar, FLAG_BRACK_LAST, mode);
839                                 cell->append(ar);
840                         } else {
841                                 // no option found, put back token and we are done
842                                 putback();
843                         }
844                         return success_;
845                 }
846
847                 //
848                 // cat codes
849                 //
850                 if (t.cat() == catMath) {
851                         if (mode != InsetMath::MATH_MODE) {
852                                 // we are inside some text mode thingy, so opening new math is allowed
853                                 Token const & n = getToken();
854                                 if (n.cat() == catMath) {
855                                         // TeX's $$...$$ syntax for displayed math
856                                         if (mode == InsetMath::UNDECIDED_MODE) {
857                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
858                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
859                                                 getToken(); // skip the second '$' token
860                                         } else {
861                                                 // This is not an outer hull and display math is
862                                                 // not allowed inside text mode environments.
863                                                 error("bad math environment");
864                                                 break;
865                                         }
866                                 } else {
867                                         // simple $...$  stuff
868                                         putback();
869                                         if (mode == InsetMath::UNDECIDED_MODE) {
870                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
871                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
872                                         } else {
873                                                 // Don't create nested math hulls (bug #5392)
874                                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
875                                                 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
876                                         }
877                                 }
878                         }
879
880                         else if (flags & FLAG_SIMPLE) {
881                                 // this is the end of the formula
882                                 return success_;
883                         }
884
885                         else {
886                                 Token const & n = getToken();
887                                 if (n.cat() == catMath) {
888                                         error("something strange in the parser");
889                                         break;
890                                 } else {
891                                         // This is inline math ($...$), but the parser thinks we are
892                                         // already in math mode and latex would issue an error, unless we
893                                         // are inside a text mode user macro. We have no way to tell, so
894                                         // let's play safe by using \ensuremath, as it will work in any case.
895                                         putback();
896                                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
897                                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
898                                 }
899                         }
900                 }
901
902                 else if (t.cat() == catLetter)
903                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
904
905                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
906                         if (cell->empty() || cell->back()->getChar() != ' ')
907                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
908                 }
909
910                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
911                         if (cell->empty() || cell->back()->getChar() != ' ')
912                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
913                 }
914
915                 else if (t.cat() == catParameter) {
916                         Token const & n = getToken();
917                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
918                 }
919
920                 else if (t.cat() == catActive)
921                         cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
922
923                 else if (t.cat() == catBegin) {
924                         MathData ar;
925                         parse(ar, FLAG_BRACE_LAST, mode);
926                         // do not create a BraceInset if they were written by LyX
927                         // this helps to keep the annoyance of  "a choose b"  to a minimum
928                         if (ar.size() == 1 && ar[0]->extraBraces())
929                                 cell->append(ar);
930                         else
931                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
932                 }
933
934                 else if (t.cat() == catEnd) {
935                         if (flags & FLAG_BRACE_LAST)
936                                 return success_;
937                         error("found '}' unexpectedly");
938                         //LASSERT(false, /**/);
939                         //add(cell, '}', LM_TC_TEX);
940                 }
941
942                 else if (t.cat() == catAlign) {
943                         //lyxerr << " column now " << (cellcol + 1)
944                         //       << " max: " << grid.ncols() << endl;
945                         if (flags & FLAG_ALIGN)
946                                 return success_;
947                         if (addCol(grid, cellcol))
948                                 cell = &grid.cell(grid.index(cellrow, cellcol));
949                 }
950
951                 else if (t.cat() == catSuper || t.cat() == catSub) {
952                         bool up = (t.cat() == catSuper);
953                         // we need no new script inset if the last thing was a scriptinset,
954                         // which has that script already not the same script already
955                         if (cell->empty())
956                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
957                         else if (cell->back()->asScriptInset() &&
958                                         !cell->back()->asScriptInset()->has(up))
959                                 cell->back().nucleus()->asScriptInset()->ensure(up);
960                         else if (cell->back()->asScriptInset())
961                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
962                         else
963                                 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
964                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
965                         // special handling of {}-bases
966                         // Here we could remove the brace inset for things
967                         // like {a'}^2 and add the braces back in
968                         // InsetMathScript::write().
969                         // We do not do it, since it is not possible to detect
970                         // reliably whether the braces are needed because the
971                         // nucleus contains more than one symbol, or whether
972                         // they are needed for unknown commands like \xx{a}_0
973                         // or \yy{a}{b}_0. This was done in revision 14819
974                         // in an unreliable way. See this thread
975                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
976                         // for more details.
977                         // However, we remove empty braces because they look
978                         // ugly on screen and we are sure that they were added
979                         // by the write() method (and will be re-added on save).
980                         if (p->nuc().size() == 1 &&
981                             p->nuc().back()->asBraceInset() &&
982                             p->nuc().back()->asBraceInset()->cell(0).empty())
983                                 p->nuc().erase(0);
984
985                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
986                         if (limits) {
987                                 p->limits(limits);
988                                 limits = 0;
989                         }
990                 }
991
992                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
993                         //lyxerr << "finished reading option" << endl;
994                         return success_;
995                 }
996
997                 else if (t.cat() == catOther) {
998                         char_type c = t.character();
999                         if (isAsciiOrMathAlpha(c)
1000                             || mode_ & Parse::VERBATIM
1001                             || !(mode_ & Parse::USETEXT)
1002                             || mode == InsetMath::TEXT_MODE) {
1003                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1004                         } else {
1005                                 MathAtom at = createInsetMath("text", buf);
1006                                 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1007                                 while (nextToken().cat() == catOther
1008                                        && !isAsciiOrMathAlpha(nextToken().character())) {
1009                                         c = getToken().character();
1010                                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1011                                 }
1012                                 cell->push_back(at);
1013                         }
1014                 }
1015
1016                 else if (t.cat() == catComment) {
1017                         docstring s;
1018                         while (good()) {
1019                                 Token const & t = getToken();
1020                                 if (t.cat() == catNewline)
1021                                         break;
1022                                 s += t.asInput();
1023                         }
1024                         cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1025                         skipSpaces();
1026                 }
1027
1028                 //
1029                 // control sequences
1030                 //
1031
1032                 else if (t.cs() == "lyxlock") {
1033                         if (!cell->empty())
1034                                 cell->back().nucleus()->lock(true);
1035                 }
1036
1037                 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1038                          t.cs() == "def") {
1039                         if (t.cs() == "global")
1040                                 getToken();
1041                         
1042                         // get name
1043                         docstring name = getToken().cs();
1044                         
1045                         // read parameters
1046                         int nargs = 0;
1047                         docstring pars;
1048                         while (good() && nextToken().cat() != catBegin) {
1049                                 pars += getToken().cs();
1050                                 ++nargs;
1051                         }
1052                         nargs /= 2;
1053                         
1054                         // read definition
1055                         MathData def;
1056                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1057                         
1058                         // is a version for display attached?
1059                         skipSpaces();
1060                         MathData display;
1061                         if (nextToken().cat() == catBegin)
1062                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1063                         
1064                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1065                                 name, nargs, 0, MacroTypeDef,
1066                                 vector<MathData>(), def, display)));
1067
1068                         if (buf && (mode_ & Parse::TRACKMACRO))
1069                                 buf->usermacros.insert(name);
1070                 }
1071                 
1072                 else if (t.cs() == "newcommand" ||
1073                          t.cs() == "renewcommand" ||
1074                          t.cs() == "newlyxcommand") {
1075                         // get name
1076                         if (getToken().cat() != catBegin) {
1077                                 error("'{' in \\newcommand expected (1) ");
1078                                 return success_;
1079                         }
1080                         docstring name = getToken().cs();
1081                         if (getToken().cat() != catEnd) {
1082                                 error("'}' in \\newcommand expected");
1083                                 return success_;
1084                         }
1085                                 
1086                         // get arity
1087                         docstring const arg = getArg('[', ']');
1088                         int nargs = 0;
1089                         if (!arg.empty())
1090                                 nargs = convert<int>(arg);
1091                                 
1092                         // optional argument given?
1093                         skipSpaces();
1094                         int optionals = 0;
1095                         vector<MathData> optionalValues;
1096                         while (nextToken().character() == '[') {
1097                                 getToken();
1098                                 optionalValues.push_back(MathData());
1099                                 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1100                                 ++optionals;
1101                         }
1102                         
1103                         MathData def;
1104                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1105                         
1106                         // is a version for display attached?
1107                         skipSpaces();
1108                         MathData display;
1109                         if (nextToken().cat() == catBegin)
1110                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1111                         
1112                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1113                                 name, nargs, optionals, MacroTypeNewcommand,
1114                                 optionalValues, def, display)));
1115
1116                         if (buf && (mode_ & Parse::TRACKMACRO))
1117                                 buf->usermacros.insert(name);
1118                 }
1119                 
1120                 else if (t.cs() == "newcommandx" ||
1121                          t.cs() == "renewcommandx") {
1122                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1123                         // get name
1124                         docstring name;
1125                         if (nextToken().cat() == catBegin) {
1126                                 getToken();
1127                                 name = getToken().cs();
1128                                 if (getToken().cat() != catEnd) {
1129                                         error("'}' in \\newcommandx expected");
1130                                         return success_;
1131                                 }
1132                         } else
1133                                 name = getToken().cs();
1134                                 
1135                         // get arity
1136                         docstring const arg = getArg('[', ']');
1137                         if (arg.empty()) {
1138                                 error("[num] in \\newcommandx expected");
1139                                 return success_;
1140                         }
1141                         int nargs = convert<int>(arg);
1142                         
1143                         // get options
1144                         int optionals = 0;
1145                         vector<MathData> optionalValues;
1146                         if (nextToken().character() == '[') {
1147                                 // skip '['
1148                                 getToken();
1149                                         
1150                                 // handle 'opt=value' options, separated by ','.
1151                                 skipSpaces();
1152                                 while (nextToken().character() != ']' && good()) {
1153                                         if (nextToken().character() >= '1'
1154                                             && nextToken().character() <= '9') {
1155                                                 // optional value -> get parameter number
1156                                                 int n = getChar() - '0';
1157                                                 if (n > nargs) {
1158                                                         error("Arity of \\newcommandx too low "
1159                                                               "for given optional parameter.");
1160                                                         return success_;
1161                                                 }
1162                                                 
1163                                                 // skip '='
1164                                                 if (getToken().character() != '=') {
1165                                                         error("'=' and optional parameter value "
1166                                                               "expected for \\newcommandx");
1167                                                         return success_;
1168                                                 }
1169                                                 
1170                                                 // get value
1171                                                 int optNum = max(size_t(n), optionalValues.size());
1172                                                 optionalValues.resize(optNum);
1173                                                 optionalValues[n - 1].clear();
1174                                                 while (nextToken().character() != ']'
1175                                                        && nextToken().character() != ',') {
1176                                                         MathData data;
1177                                                         parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1178                                                         optionalValues[n - 1].append(data);
1179                                                 }
1180                                                 optionals = max(n, optionals);
1181                                         } else if (nextToken().cat() == catLetter) {
1182                                                 // we in fact ignore every non-optional
1183                                                 // parameter
1184                                                 
1185                                                 // get option name
1186                                                 docstring opt;
1187                                                 while (nextToken().cat() == catLetter)
1188                                                         opt += getChar();
1189                                         
1190                                                 // value?
1191                                                 skipSpaces();
1192                                                 MathData value;
1193                                                 if (nextToken().character() == '=') {
1194                                                         getToken();
1195                                                         while (nextToken().character() != ']'
1196                                                                 && nextToken().character() != ',')
1197                                                                 parse(value, FLAG_ITEM, 
1198                                                                       InsetMath::UNDECIDED_MODE);
1199                                                 }
1200                                         } else {
1201                                                 error("option for \\newcommandx expected");
1202                                                 return success_;
1203                                         }
1204                                         
1205                                         // skip komma
1206                                         skipSpaces();
1207                                         if (nextToken().character() == ',') {
1208                                                 getChar();
1209                                                 skipSpaces();
1210                                         } else if (nextToken().character() != ']') {
1211                                                 error("Expecting ',' or ']' in options "
1212                                                       "of \\newcommandx");
1213                                                 return success_;
1214                                         }
1215                                 }
1216                                 
1217                                 // skip ']'
1218                                 if (!good())
1219                                         return success_;
1220                                 getToken();
1221                         }
1222
1223                         // get definition
1224                         MathData def;
1225                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1226
1227                         // is a version for display attached?
1228                         skipSpaces();
1229                         MathData display;
1230                         if (nextToken().cat() == catBegin)
1231                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1232
1233                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1234                                 name, nargs, optionals, MacroTypeNewcommandx,
1235                                 optionalValues, def, display)));
1236
1237                         if (buf && (mode_ & Parse::TRACKMACRO))
1238                                 buf->usermacros.insert(name);
1239                 }
1240
1241                 else if (t.cs() == "(") {
1242                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1243                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1244                 }
1245
1246                 else if (t.cs() == "[") {
1247                         if (mode != InsetMath::UNDECIDED_MODE) {
1248                                 error("bad math environment");
1249                                 break;
1250                         }
1251                         cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1252                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1253                 }
1254
1255                 else if (t.cs() == "protect")
1256                         // ignore \\protect, will hopefully be re-added during output
1257                         ;
1258
1259                 else if (t.cs() == "end") {
1260                         if (flags & FLAG_END) {
1261                                 // eat environment name
1262                                 docstring const name = getArg('{', '}');
1263                                 if (environments_.empty())
1264                                         error("'found \\end{" + name +
1265                                               "}' without matching '\\begin{" +
1266                                               name + "}'");
1267                                 else if (name != environments_.back())
1268                                         error("'\\end{" + name +
1269                                               "}' does not match '\\begin{" +
1270                                               environments_.back() + "}'");
1271                                 else {
1272                                         environments_.pop_back();
1273                                         // Delete empty last row in matrix
1274                                         // like insets.
1275                                         // If you abuse InsetMathGrid for
1276                                         // non-matrix like structures you
1277                                         // probably need to refine this test.
1278                                         // Right now we only have to test for
1279                                         // single line hull insets.
1280                                         if (grid.nrows() > 1 && innerHull(name))
1281                                                 delEmptyLastRow(grid);
1282                                         return success_;
1283                                 }
1284                         } else
1285                                 error("found 'end' unexpectedly");
1286                 }
1287
1288                 else if (t.cs() == ")") {
1289                         if (flags & FLAG_SIMPLE2)
1290                                 return success_;
1291                         error("found '\\)' unexpectedly");
1292                 }
1293
1294                 else if (t.cs() == "]") {
1295                         if (flags & FLAG_EQUATION)
1296                                 return success_;
1297                         error("found '\\]' unexpectedly");
1298                 }
1299
1300                 else if (t.cs() == "\\") {
1301                         if (flags & FLAG_ALIGN)
1302                                 return success_;
1303                         bool added = false;
1304                         if (nextToken().asInput() == "*") {
1305                                 getToken();
1306                                 added = addRow(grid, cellrow, docstring(), false);
1307                         } else if (good())
1308                                 added = addRow(grid, cellrow, getArg('[', ']'));
1309                         else
1310                                 error("missing token after \\\\");
1311                         if (added) {
1312                                 cellcol = 0;
1313                                 if (grid.asHullInset())
1314                                         grid.asHullInset()->numbered(
1315                                                         cellrow, numbered);
1316                                 cell = &grid.cell(grid.index(cellrow,
1317                                                              cellcol));
1318                         }
1319                 }
1320
1321 #if 0
1322                 else if (t.cs() == "multicolumn") {
1323                         // extract column count and insert dummy cells
1324                         MathData count;
1325                         parse(count, FLAG_ITEM, mode);
1326                         int cols = 1;
1327                         if (!extractNumber(count, cols)) {
1328                                 success_ = false;
1329                                 lyxerr << " can't extract number of cells from " << count << endl;
1330                         }
1331                         // resize the table if necessary
1332                         for (int i = 0; i < cols; ++i) {
1333                                 if (addCol(grid, cellcol)) {
1334                                         cell = &grid.cell(grid.index(
1335                                                         cellrow, cellcol));
1336                                         // mark this as dummy
1337                                         grid.cellinfo(grid.index(
1338                                                 cellrow, cellcol)).dummy_ = true;
1339                                 }
1340                         }
1341                         // the last cell is the real thing, not a dummy
1342                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1343
1344                         // read special alignment
1345                         MathData align;
1346                         parse(align, FLAG_ITEM, mode);
1347                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1348
1349                         // parse the remaining contents into the "real" cell
1350                         parse(*cell, FLAG_ITEM, mode);
1351                 }
1352 #endif
1353
1354                 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1355                         CatCode const cat = nextToken().cat();
1356                         if (cat == catSuper || cat == catSub)
1357                                 limits = t.cs() == "limits" ? 1 : -1;
1358                         else {
1359                                 MathAtom at = createInsetMath(t.cs(), buf);
1360                                 cell->push_back(at);
1361                         }
1362                 }
1363
1364                 else if (t.cs() == "nonumber") {
1365                         if (grid.asHullInset())
1366                                 grid.asHullInset()->numbered(cellrow, false);
1367                 }
1368
1369                 else if (t.cs() == "number") {
1370                         if (grid.asHullInset())
1371                                 grid.asHullInset()->numbered(cellrow, true);
1372                 }
1373
1374                 else if (t.cs() == "hline") {
1375                         grid.rowinfo(cellrow).lines_ ++;
1376                 }
1377
1378                 else if (t.cs() == "sqrt") {
1379                         MathData ar;
1380                         parse(ar, FLAG_OPTION, mode);
1381                         if (!ar.empty()) {
1382                                 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1383                                 cell->back().nucleus()->cell(0) = ar;
1384                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1385                         } else {
1386                                 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1387                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1388                         }
1389                 }
1390
1391                 else if (t.cs() == "cancelto") {
1392                         MathData ar;
1393                         parse(ar, FLAG_ITEM, mode);
1394                                 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1395                                 cell->back().nucleus()->cell(1) = ar;
1396                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1397                 }
1398
1399                 else if (t.cs() == "unit") {
1400                         // Allowed formats \unit[val]{unit}
1401                         MathData ar;
1402                         parse(ar, FLAG_OPTION, mode);
1403                         if (!ar.empty()) {
1404                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1405                                 cell->back().nucleus()->cell(0) = ar;
1406                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1407                         } else {
1408                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1409                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1410                         }
1411                 }
1412
1413                 else if (t.cs() == "unitfrac") {
1414                         // Here allowed formats are \unitfrac[val]{num}{denom}
1415                         MathData ar;
1416                         parse(ar, FLAG_OPTION, mode);
1417                         if (!ar.empty()) {
1418                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1419                                 cell->back().nucleus()->cell(2) = ar;
1420                         } else {
1421                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1422                         }
1423                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1424                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1425                 }
1426
1427                 else if (t.cs() == "cfrac") {
1428                         // allowed formats are \cfrac[pos]{num}{denom}
1429                         docstring const arg = getArg('[', ']');
1430                         //lyxerr << "got so far: '" << arg << "'" << endl;                              
1431                                 if (arg == "l")
1432                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1433                                 else if (arg == "r")
1434                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1435                                 else if (arg.empty() || arg == "c")
1436                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1437                                 else {
1438                                         error("found invalid optional argument");
1439                                         break;
1440                                 }
1441                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1442                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1443                 }
1444
1445                 else if (t.cs() == "stackrel") {
1446                         // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1447                         MathData ar;
1448                         parse(ar, FLAG_OPTION, mode);
1449                         cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1450                         if (!ar.empty())
1451                                 cell->back().nucleus()->cell(2) = ar;
1452                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1453                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1454                 }
1455
1456                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1457                         cell->push_back(createInsetMath(t.cs(), buf));
1458                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1459                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1460                 }
1461
1462                 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1463                           || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1464                         cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1465                         docstring const opt = parse_verbatim_option();
1466                         docstring const ref = parse_verbatim_item();
1467                         if (!opt.empty()) {
1468                                 cell->back().nucleus()->cell(1).push_back(
1469                                         MathAtom(new InsetMathString(opt)));
1470                         }
1471                         cell->back().nucleus()->cell(0).push_back(
1472                                         MathAtom(new InsetMathString(ref)));
1473                 }
1474
1475                 else if (t.cs() == "left") {
1476                         skipSpaces();
1477                         Token const & tl = getToken();
1478                         // \| and \Vert are equivalent, and InsetMathDelim
1479                         // can't handle \|
1480                         // FIXME: fix this in InsetMathDelim itself!
1481                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1482                         MathData ar;
1483                         parse(ar, FLAG_RIGHT, mode);
1484                         if (!good())
1485                                 break;
1486                         skipSpaces();
1487                         Token const & tr = getToken();
1488                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1489                         cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1490                 }
1491
1492                 else if (t.cs() == "right") {
1493                         if (flags & FLAG_RIGHT)
1494                                 return success_;
1495                         //lyxerr << "got so far: '" << cell << "'" << endl;
1496                         error("Unmatched right delimiter");
1497                         return success_;
1498                 }
1499
1500                 else if (t.cs() == "begin") {
1501                         docstring const name = getArg('{', '}');
1502                         environments_.push_back(name);
1503
1504                         if (name == "array" || name == "subarray") {
1505                                 docstring const valign = parse_verbatim_option() + 'c';
1506                                 docstring const halign = parse_verbatim_item();
1507                                 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1508                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1509                                 parse2(cell->back(), FLAG_END, mode, false);
1510                         }
1511
1512                         else if (name == "tabular") {
1513                                 docstring const valign = parse_verbatim_option() + 'c';
1514                                 docstring const halign = parse_verbatim_item();
1515                                 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1516                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1517                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1518                         }
1519
1520                         else if (name == "split" || name == "cases") {
1521                                 cell->push_back(createInsetMath(name, buf));
1522                                 parse2(cell->back(), FLAG_END, mode, false);
1523                         }
1524
1525                         else if (name == "alignedat") {
1526                                 docstring const valign = parse_verbatim_option() + 'c';
1527                                 // ignore this for a while
1528                                 getArg('{', '}');
1529                                 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1530                                 parse2(cell->back(), FLAG_END, mode, false);
1531                         }
1532
1533                         else if (name == "math") {
1534                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1535                                 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1536                         }
1537
1538                         else if (name == "equation" || name == "equation*"
1539                                         || name == "displaymath") {
1540                                 if (mode != InsetMath::UNDECIDED_MODE) {
1541                                         error("bad math environment");
1542                                         break;
1543                                 }
1544                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1545                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1546                         }
1547
1548                         else if (name == "eqnarray" || name == "eqnarray*") {
1549                                 if (mode != InsetMath::UNDECIDED_MODE) {
1550                                         error("bad math environment");
1551                                         break;
1552                                 }
1553                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1554                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1555                         }
1556
1557                         else if (name == "align" || name == "align*") {
1558                                 if (mode != InsetMath::UNDECIDED_MODE) {
1559                                         error("bad math environment");
1560                                         break;
1561                                 }
1562                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1563                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1564                         }
1565
1566                         else if (name == "flalign" || name == "flalign*") {
1567                                 if (mode != InsetMath::UNDECIDED_MODE) {
1568                                         error("bad math environment");
1569                                         break;
1570                                 }
1571                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1572                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1573                         }
1574
1575                         else if (name == "alignat" || name == "alignat*") {
1576                                 if (mode != InsetMath::UNDECIDED_MODE) {
1577                                         error("bad math environment");
1578                                         break;
1579                                 }
1580                                 // ignore this for a while
1581                                 getArg('{', '}');
1582                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1583                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1584                         }
1585
1586                         else if (name == "xalignat" || name == "xalignat*") {
1587                                 if (mode != InsetMath::UNDECIDED_MODE) {
1588                                         error("bad math environment");
1589                                         break;
1590                                 }
1591                                 // ignore this for a while
1592                                 getArg('{', '}');
1593                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1594                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1595                         }
1596
1597                         else if (name == "xxalignat") {
1598                                 if (mode != InsetMath::UNDECIDED_MODE) {
1599                                         error("bad math environment");
1600                                         break;
1601                                 }
1602                                 // ignore this for a while
1603                                 getArg('{', '}');
1604                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1605                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1606                         }
1607
1608                         else if (name == "multline" || name == "multline*") {
1609                                 if (mode != InsetMath::UNDECIDED_MODE) {
1610                                         error("bad math environment");
1611                                         break;
1612                                 }
1613                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1614                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1615                         }
1616
1617                         else if (name == "gather" || name == "gather*") {
1618                                 if (mode != InsetMath::UNDECIDED_MODE) {
1619                                         error("bad math environment");
1620                                         break;
1621                                 }
1622                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1623                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1624                         }
1625
1626                         else if (latexkeys const * l = in_word_set(name)) {
1627                                 if (l->inset == "matrix") {
1628                                         cell->push_back(createInsetMath(name, buf));
1629                                         parse2(cell->back(), FLAG_END, mode, false);
1630                                 } else if (l->inset == "split") {
1631                                         docstring const valign = parse_verbatim_option() + 'c';
1632                                         cell->push_back(MathAtom(
1633                                                 new InsetMathSplit(buf, name, (char)valign[0])));
1634                                         parse2(cell->back(), FLAG_END, mode, false);
1635                                 } else {
1636                                         success_ = false;
1637                                         if (!(mode_ & Parse::QUIET)) {
1638                                                 dump();
1639                                                 lyxerr << "found math environment `"
1640                                                        << to_utf8(name)
1641                                                        << "' in symbols file with unsupported inset `"
1642                                                        << to_utf8(l->inset)
1643                                                        << "'." << endl;
1644                                         }
1645                                         // create generic environment inset
1646                                         cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1647                                         parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1648                                 }
1649                         }
1650
1651                         else {
1652                                 success_ = false;
1653                                 if (!(mode_ & Parse::QUIET)) {
1654                                         dump();
1655                                         lyxerr << "found unknown math environment '"
1656                                                << to_utf8(name) << "'" << endl;
1657                                 }
1658                                 // create generic environment inset
1659                                 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1660                                 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1661                         }
1662                 }
1663
1664                 else if (t.cs() == "kern") {
1665                         // FIXME: A hack...
1666                         docstring s;
1667                         int num_tokens = 0;
1668                         while (true) {
1669                                 Token const & t = getToken();
1670                                 ++num_tokens;
1671                                 if (!good()) {
1672                                         s.clear();
1673                                         while (num_tokens--)
1674                                                 putback();
1675                                         break;
1676                                 }
1677                                 s += t.character();
1678                                 if (isValidLength(to_utf8(s)))
1679                                         break;
1680                         }
1681                         if (s.empty())
1682                                 cell->push_back(MathAtom(new InsetMathKern));
1683                         else
1684                                 cell->push_back(MathAtom(new InsetMathKern(s)));
1685                 }
1686
1687                 else if (t.cs() == "label") {
1688                         // FIXME: This is swallowed in inline formulas
1689                         docstring label = parse_verbatim_item();
1690                         MathData ar;
1691                         asArray(label, ar);
1692                         if (grid.asHullInset()) {
1693                                 grid.asHullInset()->label(cellrow, label);
1694                         } else {
1695                                 cell->push_back(createInsetMath(t.cs(), buf));
1696                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1697                         }
1698                 }
1699
1700                 else if (t.cs() == "choose" || t.cs() == "over"
1701                                 || t.cs() == "atop" || t.cs() == "brace"
1702                                 || t.cs() == "brack") {
1703                         MathAtom at = createInsetMath(t.cs(), buf);
1704                         at.nucleus()->cell(0) = *cell;
1705                         cell->clear();
1706                         parse(at.nucleus()->cell(1), flags, mode);
1707                         cell->push_back(at);
1708                         return success_;
1709                 }
1710
1711                 else if (t.cs() == "color") {
1712                         docstring const color = parse_verbatim_item();
1713                         cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1714                         parse(cell->back().nucleus()->cell(0), flags, mode);
1715                         return success_;
1716                 }
1717
1718                 else if (t.cs() == "textcolor") {
1719                         docstring const color = parse_verbatim_item();
1720                         cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1721                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1722                 }
1723
1724                 else if (t.cs() == "normalcolor") {
1725                         cell->push_back(createInsetMath(t.cs(), buf));
1726                         parse(cell->back().nucleus()->cell(0), flags, mode);
1727                         return success_;
1728                 }
1729
1730                 else if (t.cs() == "substack") {
1731                         cell->push_back(createInsetMath(t.cs(), buf));
1732                         parse2(cell->back(), FLAG_ITEM, mode, false);
1733                         // Delete empty last row if present
1734                         InsetMathGrid & subgrid =
1735                                 *(cell->back().nucleus()->asGridInset());
1736                         if (subgrid.nrows() > 1)
1737                                 delEmptyLastRow(subgrid);
1738                 }
1739
1740                 else if (t.cs() == "xymatrix") {
1741                         odocstringstream os;
1742                         while (good() && nextToken().cat() != catBegin)
1743                                 os << getToken().asInput();
1744                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1745                         parse2(cell->back(), FLAG_ITEM, mode, false);
1746                         // Delete empty last row if present
1747                         InsetMathGrid & subgrid =
1748                                 *(cell->back().nucleus()->asGridInset());
1749                         if (subgrid.nrows() > 1)
1750                                 delEmptyLastRow(subgrid);
1751                 }
1752
1753                 else if (t.cs() == "Diagram") {
1754                         odocstringstream os;
1755                         while (good() && nextToken().cat() != catBegin)
1756                                 os << getToken().asInput();
1757                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1758                         parse2(cell->back(), FLAG_ITEM, mode, false);
1759                 }
1760
1761                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1762                         cell->push_back(createInsetMath(t.cs(), buf));
1763                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1764                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1765                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1766                 }
1767
1768                 else if (t.cs() == "tag") {
1769                         if (nextToken().character() == '*') {
1770                                 getToken();
1771                                 cell->push_back(createInsetMath(t.cs() + '*', buf));
1772                         } else
1773                                 cell->push_back(createInsetMath(t.cs(), buf));
1774                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1775                 }
1776
1777                 else if (t.cs() == "hspace") {
1778                         bool const prot =  nextToken().character() == '*';
1779                         if (prot)
1780                                 getToken();
1781                         docstring const name = t.cs();
1782                         docstring const arg = parse_verbatim_item();
1783                         Length length;
1784                         if (prot && arg == "\\fill")
1785                                 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1786                         else if (isValidLength(to_utf8(arg), &length))
1787                                 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1788                         else {
1789                                 // Since the Length class cannot use length variables
1790                                 // we must not create an InsetMathSpace.
1791                                 cell->push_back(MathAtom(new MathMacro(buf, name)));
1792                                 MathData ar;
1793                                 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1794                                 cell->append(ar);
1795                         }
1796                 }
1797
1798 #if 0
1799                 else if (t.cs() == "infer") {
1800                         MathData ar;
1801                         parse(ar, FLAG_OPTION, mode);
1802                         cell->push_back(createInsetMath(t.cs(), buf));
1803                         parse2(cell->back(), FLAG_ITEM, mode, false);
1804                 }
1805
1806                 // Disabled
1807                 else if (1 && t.cs() == "ar") {
1808                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1809                         // try to read target
1810                         parse(p->cell(0), FLAG_OTPTION, mode);
1811                         // try to read label
1812                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1813                                 p->up_ = nextToken().cat() == catSuper;
1814                                 getToken();
1815                                 parse(p->cell(1), FLAG_ITEM, mode);
1816                                 //lyxerr << "read label: " << p->cell(1) << endl;
1817                         }
1818
1819                         cell->push_back(MathAtom(p.release()));
1820                         //lyxerr << "read cell: " << cell << endl;
1821                 }
1822 #endif
1823
1824                 else if (t.cs() == "lyxmathsym") {
1825                         skipSpaces();
1826                         if (getToken().cat() != catBegin) {
1827                                 error("'{' expected in \\" + t.cs());
1828                                 return success_;
1829                         }
1830                         int count = 0;
1831                         docstring cmd;
1832                         CatCode cat = nextToken().cat();
1833                         while (good() && (count || cat != catEnd)) {
1834                                 if (cat == catBegin)
1835                                         ++count;
1836                                 else if (cat == catEnd)
1837                                         --count;
1838                                 cmd += getToken().asInput();
1839                                 cat = nextToken().cat();
1840                         }
1841                         if (getToken().cat() != catEnd) {
1842                                 error("'}' expected in \\" + t.cs());
1843                                 return success_;
1844                         }
1845                         bool termination;
1846                         docstring rem;
1847                         do {
1848                                 cmd = Encodings::fromLaTeXCommand(cmd,
1849                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
1850                                         termination, rem);
1851                                 for (size_t i = 0; i < cmd.size(); ++i)
1852                                         cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1853                                 if (!rem.empty()) {
1854                                         char_type c = rem[0];
1855                                         cell->push_back(MathAtom(new InsetMathChar(c)));
1856                                         cmd = rem.substr(1);
1857                                         rem.clear();
1858                                 } else
1859                                         cmd.clear();
1860                         } while (!cmd.empty());
1861                 }
1862
1863                 else if (!t.cs().empty()) {
1864                         bool const no_mhchem =
1865                                 (t.cs() == "ce" || t.cs() == "cf")
1866                                 && buf && buf->params().use_package("mhchem") ==
1867                                                 BufferParams::package_off;
1868
1869                         bool const is_user_macro = no_mhchem ||
1870                                 (buf && (mode_ & Parse::TRACKMACRO
1871                                          ? buf->usermacros.count(t.cs()) != 0
1872                                          : buf->getMacro(t.cs(), false) != 0));
1873
1874                         latexkeys const * l = in_word_set(t.cs());
1875                         if (l && !is_user_macro) {
1876                                 if (l->inset == "big") {
1877                                         skipSpaces();
1878                                         docstring const delim = getToken().asInput();
1879                                         if (InsetMathBig::isBigInsetDelim(delim))
1880                                                 cell->push_back(MathAtom(
1881                                                         new InsetMathBig(t.cs(), delim)));
1882                                         else {
1883                                                 cell->push_back(createInsetMath(t.cs(), buf));
1884                                                 putback();
1885                                         }
1886                                 }
1887
1888                                 else if (l->inset == "font") {
1889                                         cell->push_back(createInsetMath(t.cs(), buf));
1890                                         parse(cell->back().nucleus()->cell(0),
1891                                                 FLAG_ITEM, asMode(mode, l->extra));
1892                                 }
1893
1894                                 else if (l->inset == "oldfont") {
1895                                         cell->push_back(createInsetMath(t.cs(), buf));
1896                                         parse(cell->back().nucleus()->cell(0),
1897                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1898                                         if (prevToken().cat() != catAlign &&
1899                                             prevToken().cs() != "\\")
1900                                                 return success_;
1901                                         putback();
1902                                 }
1903
1904                                 else if (l->inset == "style") {
1905                                         cell->push_back(createInsetMath(t.cs(), buf));
1906                                         parse(cell->back().nucleus()->cell(0),
1907                                                 flags | FLAG_ALIGN, mode);
1908                                         if (prevToken().cat() != catAlign &&
1909                                             prevToken().cs() != "\\")
1910                                                 return success_;
1911                                         putback();
1912                                 }
1913
1914                                 else {
1915                                         MathAtom at = createInsetMath(t.cs(), buf);
1916                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1917                                                 parse(at.nucleus()->cell(i),
1918                                                         FLAG_ITEM, asMode(mode, l->extra));
1919                                         cell->push_back(at);
1920                                 }
1921                         }
1922
1923                         else {
1924                                 bool is_unicode_symbol = false;
1925                                 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
1926                                         int num_tokens = 0;
1927                                         docstring cmd = prevToken().asInput();
1928                                         CatCode cat = nextToken().cat();
1929                                         if (cat == catBegin) {
1930                                                 int count = 0;
1931                                                 while (good() && (count || cat != catEnd)) {
1932                                                         cat = nextToken().cat();
1933                                                         cmd += getToken().asInput();
1934                                                         ++num_tokens;
1935                                                         if (cat == catBegin)
1936                                                                 ++count;
1937                                                         else if (cat == catEnd)
1938                                                                 --count;
1939                                                 }
1940                                         }
1941                                         bool is_combining;
1942                                         bool termination;
1943                                         char_type c = Encodings::fromLaTeXCommand(cmd,
1944                                                 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1945                                                 is_combining, termination);
1946                                         if (is_combining) {
1947                                                 if (cat == catLetter)
1948                                                         cmd += '{';
1949                                                 cmd += getToken().asInput();
1950                                                 ++num_tokens;
1951                                                 if (cat == catLetter)
1952                                                         cmd += '}';
1953                                                 c = Encodings::fromLaTeXCommand(cmd,
1954                                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
1955                                                         is_combining, termination);
1956                                         }
1957                                         if (c) {
1958                                                 if (termination) {
1959                                                         if (nextToken().cat() == catBegin) {
1960                                                                 getToken();
1961                                                                 if (nextToken().cat() == catEnd) {
1962                                                                         getToken();
1963                                                                         num_tokens += 2;
1964                                                                 } else
1965                                                                         putback();
1966                                                         } else {
1967                                                                 while (nextToken().cat() == catSpace) {
1968                                                                         getToken();
1969                                                                         ++num_tokens;
1970                                                                 }
1971                                                         }
1972                                                 }
1973                                                 is_unicode_symbol = true;
1974                                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1975                                         } else {
1976                                                 while (num_tokens--)
1977                                                         putback();
1978                                         }
1979                                 }
1980                                 if (!is_unicode_symbol) {
1981                                         MathAtom at = is_user_macro ?
1982                                                 MathAtom(new MathMacro(buf, t.cs()))
1983                                                 : createInsetMath(t.cs(), buf);
1984                                         InsetMath::mode_type m = mode;
1985                                         //if (m == InsetMath::UNDECIDED_MODE)
1986                                         //lyxerr << "default creation: m1: " << m << endl;
1987                                         if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1988                                                 m = at->currentMode();
1989                                         //lyxerr << "default creation: m2: " << m << endl;
1990                                         InsetMath::idx_type start = 0;
1991                                         // this fails on \bigg[...\bigg]
1992                                         //MathData opt;
1993                                         //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1994                                         //if (!opt.empty()) {
1995                                         //      start = 1;
1996                                         //      at.nucleus()->cell(0) = opt;
1997                                         //}
1998                                         for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1999                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2000                                                 skipSpaces();
2001                                         }
2002                                         cell->push_back(at);
2003                                 }
2004                         }
2005                 }
2006
2007
2008                 if (flags & FLAG_LEAVE) {
2009                         flags &= ~FLAG_LEAVE;
2010                         break;
2011                 }
2012         }
2013         return success_;
2014 }
2015
2016
2017
2018 } // anonymous namespace
2019
2020
2021 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2022 {
2023         return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2024                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2025 }
2026
2027
2028 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2029 {
2030         return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2031                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2032 }
2033
2034
2035 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2036                          Parse::flags f)
2037 {
2038         return Parser(str, f, buf).parse(t);
2039 }
2040
2041
2042 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2043                          Parse::flags f)
2044 {
2045         return Parser(lex, f, buf).parse(t);
2046 }
2047
2048
2049 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2050                          Parse::flags f)
2051 {
2052         return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2053                         InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2054 }
2055
2056
2057 void initParser()
2058 {
2059         fill(theCatcode, theCatcode + 128, catOther);
2060         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2061         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2062
2063         theCatcode[int('\\')] = catEscape;
2064         theCatcode[int('{')]  = catBegin;
2065         theCatcode[int('}')]  = catEnd;
2066         theCatcode[int('$')]  = catMath;
2067         theCatcode[int('&')]  = catAlign;
2068         theCatcode[int('\n')] = catNewline;
2069         theCatcode[int('#')]  = catParameter;
2070         theCatcode[int('^')]  = catSuper;
2071         theCatcode[int('_')]  = catSub;
2072         theCatcode[int(0x7f)] = catIgnore;
2073         theCatcode[int(' ')]  = catSpace;
2074         theCatcode[int('\t')] = catSpace;
2075         theCatcode[int('\r')] = catNewline;
2076         theCatcode[int('~')]  = catActive;
2077         theCatcode[int('%')]  = catComment;
2078 }
2079
2080
2081 } // namespace lyx