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