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