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