]> git.lyx.org Git - lyx.git/blob - src/mathed/MathParser.cpp
Linearize macros in box edit mode too.
[lyx.git] / src / mathed / MathParser.cpp
1 /**
2  * \file MathParser.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 /*
12
13 If someone desperately needs partial "structures" (such as a few
14 cells of an array inset or similar) (s)he could uses the
15 following hack as starting point to write some macros:
16
17   \newif\ifcomment
18   \commentfalse
19   \ifcomment
20           \def\makeamptab{\catcode`\&=4\relax}
21           \def\makeampletter{\catcode`\&=11\relax}
22     \def\b{\makeampletter\expandafter\makeamptab\bi}
23     \long\def\bi#1\e{}
24   \else
25     \def\b{}\def\e{}
26   \fi
27   ...
28
29   \[\begin{array}{ccc}
30 1
31 &
32
33   \end{array}\]
34
35 */
36
37
38 #include <config.h>
39
40 #include "MathParser.h"
41
42 #include "InsetMathArray.h"
43 #include "InsetMathBig.h"
44 #include "InsetMathBrace.h"
45 #include "InsetMathCancelto.h"
46 #include "InsetMathChar.h"
47 #include "InsetMathColor.h"
48 #include "InsetMathComment.h"
49 #include "InsetMathDelim.h"
50 #include "InsetMathEnsureMath.h"
51 #include "InsetMathEnv.h"
52 #include "InsetMathFrac.h"
53 #include "InsetMathKern.h"
54 #include "MathMacro.h"
55 #include "InsetMathPar.h"
56 #include "InsetMathRef.h"
57 #include "InsetMathRoot.h"
58 #include "InsetMathScript.h"
59 #include "InsetMathSideset.h"
60 #include "InsetMathSpace.h"
61 #include "InsetMathSplit.h"
62 #include "InsetMathSqrt.h"
63 #include "InsetMathStackrel.h"
64 #include "InsetMathString.h"
65 #include "InsetMathTabular.h"
66 #include "MathMacroTemplate.h"
67 #include "MathExtern.h"
68 #include "MathFactory.h"
69 #include "MathMacroArgument.h"
70 #include "MathSupport.h"
71
72 #include "Buffer.h"
73 #include "BufferParams.h"
74 #include "Encoding.h"
75 #include "Lexer.h"
76
77 #include "support/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 wether 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 wether 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 instanciate
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                 Token t = getToken();
748                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
749                         if (t.cat() == catBegin) {
750                                 putback();
751                                 res += '{' + parse_verbatim_item() + '}';
752                         } else
753                                 res += t.asInput();
754                 }
755         }
756         return res;
757 }
758
759
760 docstring Parser::parse_verbatim_item()
761 {
762         skipSpaces();
763         docstring res;
764         if (nextToken().cat() == catBegin) {
765                 Token t = getToken();
766                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
767                         if (t.cat() == catBegin) {
768                                 putback();
769                                 res += '{' + parse_verbatim_item() + '}';
770                         }
771                         else
772                                 res += t.asInput();
773                 }
774         }
775         return res;
776 }
777
778
779 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
780 {
781         InsetMathGrid grid(buffer_, 1, 1);
782         parse1(grid, flags, mode, false);
783         array = grid.cell(0);
784         return success_;
785 }
786
787
788 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
789         const bool numbered)
790 {
791         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
792 }
793
794
795 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
796         const mode_type mode, const bool numbered)
797 {
798         int limits = 0;
799         InsetMathGrid::row_type cellrow = 0;
800         InsetMathGrid::col_type cellcol = 0;
801         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
802         Buffer * buf = buffer_;
803
804         if (grid.asHullInset())
805                 grid.asHullInset()->numbered(cellrow, numbered);
806
807         //dump();
808         //lyxerr << " flags: " << flags << endl;
809         //lyxerr << " mode: " << mode  << endl;
810         //lyxerr << "grid: " << grid << endl;
811
812         while (good()) {
813                 Token const & t = getToken();
814
815 #ifdef FILEDEBUG
816                 lyxerr << "t: " << t << " flags: " << flags << endl;
817                 lyxerr << "mode: " << mode  << endl;
818                 cell->dump();
819                 lyxerr << endl;
820 #endif
821
822                 if (flags & FLAG_ITEM) {
823
824                         if (t.cat() == catBegin) {
825                                 // skip the brace and collect everything to the next matching
826                                 // closing brace
827                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
828                                 return success_;
829                         }
830
831                         // handle only this single token, leave the loop if done
832                         flags = FLAG_LEAVE;
833                 }
834
835
836                 if (flags & FLAG_BRACED) {
837                         if (t.cat() == catSpace)
838                                 continue;
839
840                         if (t.cat() != catBegin) {
841                                 error("opening brace expected");
842                                 return success_;
843                         }
844
845                         // skip the brace and collect everything to the next matching
846                         // closing brace
847                         flags = FLAG_BRACE_LAST;
848                 }
849
850
851                 if (flags & FLAG_OPTION) {
852                         if (t.cat() == catOther && t.character() == '[') {
853                                 MathData ar;
854                                 parse(ar, FLAG_BRACK_LAST, mode);
855                                 cell->append(ar);
856                         } else {
857                                 // no option found, put back token and we are done
858                                 putback();
859                         }
860                         return success_;
861                 }
862
863                 //
864                 // cat codes
865                 //
866                 if (t.cat() == catMath) {
867                         if (mode != InsetMath::MATH_MODE) {
868                                 // we are inside some text mode thingy, so opening new math is allowed
869                                 Token const & n = getToken();
870                                 if (n.cat() == catMath) {
871                                         // TeX's $$...$$ syntax for displayed math
872                                         if (mode == InsetMath::UNDECIDED_MODE) {
873                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
874                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
875                                                 getToken(); // skip the second '$' token
876                                         } else {
877                                                 // This is not an outer hull and display math is
878                                                 // not allowed inside text mode environments.
879                                                 error("bad math environment $$");
880                                                 break;
881                                         }
882                                 } else {
883                                         // simple $...$  stuff
884                                         putback();
885                                         if (mode == InsetMath::UNDECIDED_MODE) {
886                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
887                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
888                                         } else {
889                                                 // Don't create nested math hulls (bug #5392)
890                                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
891                                                 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
892                                         }
893                                 }
894                         }
895
896                         else if (flags & FLAG_SIMPLE) {
897                                 // this is the end of the formula
898                                 return success_;
899                         }
900
901                         else {
902                                 Token const & n = getToken();
903                                 if (n.cat() == catMath) {
904                                         error("something strange in the parser");
905                                         break;
906                                 } else {
907                                         // This is inline math ($...$), but the parser thinks we are
908                                         // already in math mode and latex would issue an error, unless we
909                                         // are inside a text mode user macro. We have no way to tell, so
910                                         // let's play safe by using \ensuremath, as it will work in any case.
911                                         putback();
912                                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
913                                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
914                                 }
915                         }
916                 }
917
918                 else if (t.cat() == catLetter)
919                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
920
921                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
922                         if (cell->empty() || cell->back()->getChar() != ' ')
923                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
924                 }
925
926                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
927                         if (cell->empty() || cell->back()->getChar() != ' ')
928                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
929                 }
930
931                 else if (t.cat() == catParameter) {
932                         Token const & n = nextToken();
933                         char_type c = n.character();
934                         if (c && '0' < c && c <= '9') {
935                                 cell->push_back(MathAtom(new MathMacroArgument(c - '0')));
936                                 getToken();
937                         } else
938                                 cell->push_back(MathAtom(new InsetMathHash()));
939                 }
940
941                 else if (t.cat() == catActive)
942                         cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
943
944                 else if (t.cat() == catBegin) {
945                         MathData ar;
946                         parse(ar, FLAG_BRACE_LAST, mode);
947                         // do not create a BraceInset if they were written by LyX
948                         // this helps to keep the annoyance of  "a choose b"  to a minimum
949                         if (ar.size() == 1 && ar[0]->extraBraces())
950                                 cell->append(ar);
951                         else
952                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
953                 }
954
955                 else if (t.cat() == catEnd) {
956                         if (flags & FLAG_BRACE_LAST)
957                                 return success_;
958                         error("found '}' unexpectedly");
959                         //LASSERT(false, /**/);
960                         //add(cell, '}', LM_TC_TEX);
961                 }
962
963                 else if (t.cat() == catAlign) {
964                         //lyxerr << " column now " << (cellcol + 1)
965                         //       << " max: " << grid.ncols() << endl;
966                         if (flags & FLAG_ALIGN)
967                                 return success_;
968                         if (addCol(grid, cellcol))
969                                 cell = &grid.cell(grid.index(cellrow, cellcol));
970                 }
971
972                 else if (t.cat() == catSuper || t.cat() == catSub) {
973                         bool up = (t.cat() == catSuper);
974                         // we need no new script inset if the last thing was a scriptinset,
975                         // which has that script already not the same script already
976                         if (cell->empty())
977                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
978                         else if (cell->back()->asScriptInset() &&
979                                         !cell->back()->asScriptInset()->has(up))
980                                 cell->back().nucleus()->asScriptInset()->ensure(up);
981                         else if (cell->back()->asScriptInset())
982                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
983                         else
984                                 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
985                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
986                         // special handling of {}-bases
987                         // Here we could remove the brace inset for things
988                         // like {a'}^2 and add the braces back in
989                         // InsetMathScript::write().
990                         // We do not do it, since it is not possible to detect
991                         // reliably whether the braces are needed because the
992                         // nucleus contains more than one symbol, or whether
993                         // they are needed for unknown commands like \xx{a}_0
994                         // or \yy{a}{b}_0. This was done in revision 14819
995                         // in an unreliable way. See this thread
996                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
997                         // for more details.
998                         // However, we remove empty braces because they look
999                         // ugly on screen and we are sure that they were added
1000                         // by the write() method (and will be re-added on save).
1001                         if (p->nuc().size() == 1 &&
1002                             p->nuc().back()->asBraceInset() &&
1003                             p->nuc().back()->asBraceInset()->cell(0).empty())
1004                                 p->nuc().erase(0);
1005
1006                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
1007                         if (limits) {
1008                                 p->limits(limits);
1009                                 limits = 0;
1010                         }
1011                 }
1012
1013                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
1014                         //lyxerr << "finished reading option" << endl;
1015                         return success_;
1016                 }
1017
1018                 else if (t.cat() == catOther) {
1019                         char_type c = t.character();
1020                         if (isAsciiOrMathAlpha(c)
1021                             || mode_ & Parse::VERBATIM
1022                             || !(mode_ & Parse::USETEXT)
1023                             || mode == InsetMath::TEXT_MODE) {
1024                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1025                         } else {
1026                                 MathAtom at = createInsetMath("text", buf);
1027                                 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1028                                 while (nextToken().cat() == catOther
1029                                        && !isAsciiOrMathAlpha(nextToken().character())) {
1030                                         c = getToken().character();
1031                                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1032                                 }
1033                                 cell->push_back(at);
1034                         }
1035                 }
1036
1037                 else if (t.cat() == catComment) {
1038                         docstring s;
1039                         while (good()) {
1040                                 Token const & t = getToken();
1041                                 if (t.cat() == catNewline)
1042                                         break;
1043                                 s += t.asInput();
1044                         }
1045                         cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1046                         skipSpaces();
1047                 }
1048
1049                 //
1050                 // control sequences
1051                 //
1052
1053                 else if (t.cs() == "lyxlock") {
1054                         if (!cell->empty())
1055                                 cell->back().nucleus()->lock(true);
1056                 }
1057
1058                 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1059                          t.cs() == "def") {
1060                         if (t.cs() == "global")
1061                                 getToken();
1062
1063                         // get name
1064                         docstring name = getToken().cs();
1065
1066                         // read parameters
1067                         int nargs = 0;
1068                         docstring pars;
1069                         while (good() && nextToken().cat() != catBegin) {
1070                                 pars += getToken().cs();
1071                                 ++nargs;
1072                         }
1073                         nargs /= 2;
1074
1075                         // read definition
1076                         MathData def;
1077                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1078
1079                         // is a version for display attached?
1080                         skipSpaces();
1081                         MathData display;
1082                         if (nextToken().cat() == catBegin)
1083                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1084
1085                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1086                                 name, nargs, 0, MacroTypeDef,
1087                                 vector<MathData>(), def, display)));
1088
1089                         if (buf && (mode_ & Parse::TRACKMACRO))
1090                                 buf->usermacros.insert(name);
1091                 }
1092
1093                 else if (t.cs() == "newcommand" ||
1094                          t.cs() == "renewcommand" ||
1095                          t.cs() == "newlyxcommand") {
1096                         // get name
1097                         if (getToken().cat() != catBegin) {
1098                                 error("'{' in \\newcommand expected (1) ");
1099                                 return success_;
1100                         }
1101                         docstring name = getToken().cs();
1102                         if (getToken().cat() != catEnd) {
1103                                 error("'}' in \\newcommand expected");
1104                                 return success_;
1105                         }
1106
1107                         // get arity
1108                         docstring const arg = getArg('[', ']');
1109                         int nargs = 0;
1110                         if (!arg.empty())
1111                                 nargs = convert<int>(arg);
1112
1113                         // optional argument given?
1114                         skipSpaces();
1115                         int optionals = 0;
1116                         vector<MathData> optionalValues;
1117                         while (nextToken().character() == '[') {
1118                                 getToken();
1119                                 optionalValues.push_back(MathData());
1120                                 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1121                                 ++optionals;
1122                         }
1123
1124                         MathData def;
1125                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1126
1127                         // is a version for display attached?
1128                         skipSpaces();
1129                         MathData display;
1130                         if (nextToken().cat() == catBegin)
1131                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1132
1133                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1134                                 name, nargs, optionals, MacroTypeNewcommand,
1135                                 optionalValues, def, display)));
1136
1137                         if (buf && (mode_ & Parse::TRACKMACRO))
1138                                 buf->usermacros.insert(name);
1139                 }
1140
1141                 else if (t.cs() == "newcommandx" ||
1142                          t.cs() == "renewcommandx") {
1143                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1144                         // get name
1145                         docstring name;
1146                         if (nextToken().cat() == catBegin) {
1147                                 getToken();
1148                                 name = getToken().cs();
1149                                 if (getToken().cat() != catEnd) {
1150                                         error("'}' in \\newcommandx expected");
1151                                         return success_;
1152                                 }
1153                         } else
1154                                 name = getToken().cs();
1155
1156                         // get arity
1157                         docstring const arg = getArg('[', ']');
1158                         if (arg.empty()) {
1159                                 error("[num] in \\newcommandx expected");
1160                                 return success_;
1161                         }
1162                         int nargs = convert<int>(arg);
1163
1164                         // get options
1165                         int optionals = 0;
1166                         vector<MathData> optionalValues;
1167                         if (nextToken().character() == '[') {
1168                                 // skip '['
1169                                 getToken();
1170
1171                                 // handle 'opt=value' options, separated by ','.
1172                                 skipSpaces();
1173                                 while (nextToken().character() != ']' && good()) {
1174                                         if (nextToken().character() >= '1'
1175                                             && nextToken().character() <= '9') {
1176                                                 // optional value -> get parameter number
1177                                                 int n = getChar() - '0';
1178                                                 if (n > nargs) {
1179                                                         error("Arity of \\newcommandx too low "
1180                                                               "for given optional parameter.");
1181                                                         return success_;
1182                                                 }
1183
1184                                                 // skip '='
1185                                                 if (getToken().character() != '=') {
1186                                                         error("'=' and optional parameter value "
1187                                                               "expected for \\newcommandx");
1188                                                         return success_;
1189                                                 }
1190
1191                                                 // get value
1192                                                 int optNum = max(size_t(n), optionalValues.size());
1193                                                 optionalValues.resize(optNum);
1194                                                 optionalValues[n - 1].clear();
1195                                                 while (nextToken().character() != ']'
1196                                                        && nextToken().character() != ',') {
1197                                                         MathData data;
1198                                                         parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1199                                                         optionalValues[n - 1].append(data);
1200                                                 }
1201                                                 optionals = max(n, optionals);
1202                                         } else if (nextToken().cat() == catLetter) {
1203                                                 // we in fact ignore every non-optional
1204                                                 // parameter
1205
1206                                                 // get option name
1207                                                 docstring opt;
1208                                                 while (nextToken().cat() == catLetter)
1209                                                         opt += getChar();
1210
1211                                                 // value?
1212                                                 skipSpaces();
1213                                                 MathData value;
1214                                                 if (nextToken().character() == '=') {
1215                                                         getToken();
1216                                                         while (nextToken().character() != ']'
1217                                                                 && nextToken().character() != ',')
1218                                                                 parse(value, FLAG_ITEM,
1219                                                                       InsetMath::UNDECIDED_MODE);
1220                                                 }
1221                                         } else {
1222                                                 error("option for \\newcommandx expected");
1223                                                 return success_;
1224                                         }
1225
1226                                         // skip komma
1227                                         skipSpaces();
1228                                         if (nextToken().character() == ',') {
1229                                                 getChar();
1230                                                 skipSpaces();
1231                                         } else if (nextToken().character() != ']') {
1232                                                 error("Expecting ',' or ']' in options "
1233                                                       "of \\newcommandx");
1234                                                 return success_;
1235                                         }
1236                                 }
1237
1238                                 // skip ']'
1239                                 if (!good())
1240                                         return success_;
1241                                 getToken();
1242                         }
1243
1244                         // get definition
1245                         MathData def;
1246                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1247
1248                         // is a version for display attached?
1249                         skipSpaces();
1250                         MathData display;
1251                         if (nextToken().cat() == catBegin)
1252                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1253
1254                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1255                                 name, nargs, optionals, MacroTypeNewcommandx,
1256                                 optionalValues, def, display)));
1257
1258                         if (buf && (mode_ & Parse::TRACKMACRO))
1259                                 buf->usermacros.insert(name);
1260                 }
1261
1262                 else if (t.cs() == "(") {
1263                         if (mode == InsetMath::UNDECIDED_MODE) {
1264                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1265                                 parse2(cell->back(), FLAG_SIMPLE2, InsetMath::MATH_MODE, false);
1266                         } else {
1267                                 // Don't create nested math hulls (bug #5392)
1268                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1269                                 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1270                         }
1271                 }
1272
1273                 else if (t.cs() == "[") {
1274                         if (mode != InsetMath::UNDECIDED_MODE) {
1275                                 error("bad math environment [");
1276                                 break;
1277                         }
1278                         cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1279                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1280                 }
1281
1282                 else if (t.cs() == "protect")
1283                         // ignore \\protect, will hopefully be re-added during output
1284                         ;
1285
1286                 else if (t.cs() == "end") {
1287                         if (flags & FLAG_END) {
1288                                 // eat environment name
1289                                 docstring const name = getArg('{', '}');
1290                                 if (environments_.empty())
1291                                         error("'found \\end{" + name +
1292                                               "}' without matching '\\begin{" +
1293                                               name + "}'");
1294                                 else if (name != environments_.back())
1295                                         error("'\\end{" + name +
1296                                               "}' does not match '\\begin{" +
1297                                               environments_.back() + "}'");
1298                                 else {
1299                                         environments_.pop_back();
1300                                         // Delete empty last row in matrix
1301                                         // like insets.
1302                                         // If you abuse InsetMathGrid for
1303                                         // non-matrix like structures you
1304                                         // probably need to refine this test.
1305                                         // Right now we only have to test for
1306                                         // single line hull insets.
1307                                         if (grid.nrows() > 1 && innerHull(name))
1308                                                 delEmptyLastRow(grid);
1309                                         return success_;
1310                                 }
1311                         } else
1312                                 error("found 'end' unexpectedly");
1313                 }
1314
1315                 else if (t.cs() == ")") {
1316                         if (flags & FLAG_SIMPLE2)
1317                                 return success_;
1318                         error("found '\\)' unexpectedly");
1319                 }
1320
1321                 else if (t.cs() == "]") {
1322                         if (flags & FLAG_EQUATION)
1323                                 return success_;
1324                         error("found '\\]' unexpectedly");
1325                 }
1326
1327                 else if (t.cs() == "\\") {
1328                         if (flags & FLAG_ALIGN)
1329                                 return success_;
1330                         bool starred = false;
1331                         docstring arg;
1332                         if (nextToken().asInput() == "*") {
1333                                 getToken();
1334                                 starred = true;
1335                         } else if (nextToken().asInput() == "[")
1336                                 arg = getArg('[', ']');
1337                         else if (!good())
1338                                 error("missing token after \\\\");
1339                         // skip "{}" added in front of "[" (the
1340                         // counterpart is in InsetMathGrid::eolString())
1341                         // skip spaces because formula could come from tex2lyx
1342                         bool skipBraces = false;
1343                         pushPosition();
1344                         if (nextToken().cat() == catBegin) {
1345                                 getToken();
1346                                 if (nextToken().cat() == catEnd) {
1347                                         getToken();
1348                                         pushPosition();
1349                                         skipSpaces();
1350                                         if (nextToken().asInput() == "[")
1351                                                 skipBraces = true;
1352                                         popPosition();
1353                                 }
1354                         }
1355                         if (skipBraces)
1356                                 dropPosition();
1357                         else
1358                                 popPosition();
1359                         bool const added = addRow(grid, cellrow, arg, !starred);
1360                         if (added) {
1361                                 cellcol = 0;
1362                                 if (grid.asHullInset())
1363                                         grid.asHullInset()->numbered(
1364                                                         cellrow, numbered);
1365                                 cell = &grid.cell(grid.index(cellrow,
1366                                                              cellcol));
1367                         }
1368                 }
1369
1370                 else if (t.cs() == "multicolumn" && grid.handlesMulticolumn()) {
1371                         // if the columns are specified numerically,
1372                         // extract column count and insert dummy cells,
1373                         // otherwise parse it as an user macro
1374                         MathData count;
1375                         parse(count, FLAG_ITEM, mode);
1376                         int cols;
1377                         if (extractNumber(count, cols)) {
1378                                 // resize the table if necessary
1379                                 size_t first = grid.index(cellrow, cellcol);
1380                                 for (int i = 1; i < cols; ++i) {
1381                                         if (addCol(grid, cellcol)) {
1382                                                 size_t const idx = grid.index(cellrow, cellcol);
1383                                                 grid.cellinfo(idx).multi_ =
1384                                                         InsetMathGrid::CELL_PART_OF_MULTICOLUMN;
1385                                         }
1386                                 }
1387
1388                                 // the first cell is the real thing, not a dummy
1389                                 cell = &grid.cell(first);
1390                                 grid.cellinfo(first).multi_ =
1391                                         InsetMathGrid::CELL_BEGIN_OF_MULTICOLUMN;
1392
1393                                 // read special alignment
1394                                 MathData align;
1395                                 parse(align, FLAG_ITEM, mode);
1396                                 grid.cellinfo(first).align_ = asString(align);
1397
1398                                 // parse the remaining contents into the "real" cell
1399                                 parse(*cell, FLAG_ITEM, mode);
1400                         } else {
1401                                 MathAtom at = MathAtom(new MathMacro(buf, t.cs()));
1402                                 cell->push_back(at);
1403                                 cell->push_back(MathAtom(new InsetMathBrace(count)));
1404                         }
1405                 }
1406
1407                 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1408                         CatCode const cat = nextToken().cat();
1409                         if (cat == catSuper || cat == catSub)
1410                                 limits = t.cs() == "limits" ? 1 : -1;
1411                         else {
1412                                 MathAtom at = createInsetMath(t.cs(), buf);
1413                                 cell->push_back(at);
1414                         }
1415                 }
1416
1417                 // \notag is the same as \nonumber if amsmath is used
1418                 else if ((t.cs() == "nonumber" || t.cs() == "notag") &&
1419                          grid.asHullInset())
1420                         grid.asHullInset()->numbered(cellrow, false);
1421
1422                 else if (t.cs() == "number" && grid.asHullInset())
1423                         grid.asHullInset()->numbered(cellrow, true);
1424
1425                 else if (t.cs() == "hline") {
1426                         grid.rowinfo(cellrow).lines_ ++;
1427                 }
1428
1429                 else if (t.cs() == "sqrt") {
1430                         MathData ar;
1431                         parse(ar, FLAG_OPTION, mode);
1432                         if (!ar.empty()) {
1433                                 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1434                                 cell->back().nucleus()->cell(0) = ar;
1435                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1436                         } else {
1437                                 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1438                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1439                         }
1440                 }
1441
1442                 else if (t.cs() == "cancelto") {
1443                         MathData ar;
1444                         parse(ar, FLAG_ITEM, mode);
1445                                 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1446                                 cell->back().nucleus()->cell(1) = ar;
1447                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1448                 }
1449
1450                 else if (t.cs() == "unit") {
1451                         // Allowed formats \unit[val]{unit}
1452                         MathData ar;
1453                         parse(ar, FLAG_OPTION, mode);
1454                         if (!ar.empty()) {
1455                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1456                                 cell->back().nucleus()->cell(0) = ar;
1457                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1458                         } else {
1459                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1460                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1461                         }
1462                 }
1463
1464                 else if (t.cs() == "unitfrac") {
1465                         // Here allowed formats are \unitfrac[val]{num}{denom}
1466                         MathData ar;
1467                         parse(ar, FLAG_OPTION, mode);
1468                         if (!ar.empty()) {
1469                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1470                                 cell->back().nucleus()->cell(2) = ar;
1471                         } else {
1472                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1473                         }
1474                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1475                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1476                 }
1477
1478                 else if (t.cs() == "cfrac") {
1479                         // allowed formats are \cfrac[pos]{num}{denom}
1480                         docstring const arg = getArg('[', ']');
1481                         //lyxerr << "got so far: '" << arg << "'" << endl;
1482                                 if (arg == "l")
1483                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1484                                 else if (arg == "r")
1485                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1486                                 else if (arg.empty() || arg == "c")
1487                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1488                                 else {
1489                                         error("found invalid optional argument");
1490                                         break;
1491                                 }
1492                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1493                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1494                 }
1495
1496                 else if (t.cs() == "sideset") {
1497                         // Here allowed formats are \sideset{_{bl}^{tl}}{_{br}^{tr}}{operator}
1498                         MathData ar[2];
1499                         InsetMathScript * script[2] = {0, 0};
1500                         for (int i = 0; i < 2; ++i) {
1501                                 parse(ar[i], FLAG_ITEM, mode);
1502                                 if (ar[i].size() == 1)
1503                                         script[i] = ar[i][0].nucleus()->asScriptInset();
1504                         }
1505                         bool const hasscript[2] = {script[0] ? true : false, script[1] ? true : false};
1506                         cell->push_back(MathAtom(new InsetMathSideset(buf, hasscript[0], hasscript[1])));
1507                         if (hasscript[0]) {
1508                                 if (script[0]->hasDown())
1509                                         cell->back().nucleus()->cell(1) = script[0]->down();
1510                                 if (script[0]->hasUp())
1511                                         cell->back().nucleus()->cell(2) = script[0]->up();
1512                         } else
1513                                 cell->back().nucleus()->cell(1) = ar[0];
1514                         if (hasscript[1]) {
1515                                 if (script[1]->hasDown())
1516                                         cell->back().nucleus()->cell(2 + hasscript[0]) = script[1]->down();
1517                                 if (script[1]->hasUp())
1518                                         cell->back().nucleus()->cell(3 + hasscript[0]) = script[1]->up();
1519                         } else
1520                                 cell->back().nucleus()->cell(2 + hasscript[0]) = ar[1];
1521                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1522                 }
1523
1524                 else if (t.cs() == "stackrel") {
1525                         // Here allowed formats are \stackrel[subscript]{superscript}{operator}
1526                         MathData ar;
1527                         parse(ar, FLAG_OPTION, mode);
1528                         cell->push_back(MathAtom(new InsetMathStackrel(buf, !ar.empty())));
1529                         if (!ar.empty())
1530                                 cell->back().nucleus()->cell(2) = ar;
1531                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1532                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1533                 }
1534
1535                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1536                         cell->push_back(createInsetMath(t.cs(), buf));
1537                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1538                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1539                 }
1540
1541                 else if (t.cs() == "xhookrightarrow" || t.cs() == "xhookleftarrow" ||
1542                              t.cs() == "xRightarrow" || t.cs() == "xLeftarrow" ||
1543                                  t.cs() == "xleftrightarrow" || t.cs() == "xLeftrightarrow" ||
1544                                  t.cs() == "xrightharpoondown" || t.cs() == "xrightharpoonup" ||
1545                                  t.cs() == "xleftharpoondown" || t.cs() == "xleftharpoonup" ||
1546                                  t.cs() == "xleftrightharpoons" || t.cs() == "xrightleftharpoons" ||
1547                                  t.cs() == "xmapsto") {
1548                         cell->push_back(createInsetMath(t.cs(), buf));
1549                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1550                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1551                 }
1552
1553                 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1554                           || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1555                         cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1556                         docstring const opt = parse_verbatim_option();
1557                         docstring const ref = parse_verbatim_item();
1558                         if (!opt.empty()) {
1559                                 cell->back().nucleus()->cell(1).push_back(
1560                                         MathAtom(new InsetMathString(opt)));
1561                         }
1562                         cell->back().nucleus()->cell(0).push_back(
1563                                         MathAtom(new InsetMathString(ref)));
1564                 }
1565
1566                 else if (t.cs() == "left") {
1567                         skipSpaces();
1568                         Token const & tl = getToken();
1569                         // \| and \Vert are equivalent, and InsetMathDelim
1570                         // can't handle \|
1571                         // FIXME: fix this in InsetMathDelim itself!
1572                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1573                         MathData ar;
1574                         parse(ar, FLAG_RIGHT, mode);
1575                         if (!good())
1576                                 break;
1577                         skipSpaces();
1578                         Token const & tr = getToken();
1579                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1580                         cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1581                 }
1582
1583                 else if (t.cs() == "right") {
1584                         if (flags & FLAG_RIGHT)
1585                                 return success_;
1586                         //lyxerr << "got so far: '" << cell << "'" << endl;
1587                         error("Unmatched right delimiter");
1588                         return success_;
1589                 }
1590
1591                 else if (t.cs() == "begin") {
1592                         docstring const name = getArg('{', '}');
1593
1594                         if (name.empty()) {
1595                                 success_ = false;
1596                                 error("found invalid environment");
1597                                 return success_;
1598                         }
1599
1600                         environments_.push_back(name);
1601
1602                         if (name == "array" || name == "subarray") {
1603                                 docstring const valign = parse_verbatim_option() + 'c';
1604                                 docstring const halign = parse_verbatim_item();
1605                                 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1606                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1607                                 parse2(cell->back(), FLAG_END, mode, false);
1608                         }
1609
1610                         else if (name == "tabular") {
1611                                 docstring const valign = parse_verbatim_option() + 'c';
1612                                 docstring const halign = parse_verbatim_item();
1613                                 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1614                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1615                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1616                         }
1617
1618                         else if (name == "split" || name == "cases") {
1619                                 cell->push_back(createInsetMath(name, buf));
1620                                 parse2(cell->back(), FLAG_END, mode, false);
1621                         }
1622
1623                         else if (name == "alignedat") {
1624                                 docstring const valign = parse_verbatim_option() + 'c';
1625                                 // ignore this for a while
1626                                 getArg('{', '}');
1627                                 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1628                                 parse2(cell->back(), FLAG_END, mode, false);
1629                         }
1630
1631                         else if (name == "math") {
1632                                 if (mode == InsetMath::UNDECIDED_MODE) {
1633                                         cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
1634                                         parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, false);
1635                                 } else {
1636                                         // Don't create nested math hulls (bug #5392)
1637                                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1638                                         parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1639                                 }
1640                         }
1641
1642                         else if (name == "equation" || name == "equation*"
1643                                         || name == "displaymath") {
1644                                 if (mode != InsetMath::UNDECIDED_MODE) {
1645                                         error("bad math environment " + name);
1646                                         break;
1647                                 }
1648                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1649                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1650                         }
1651
1652                         else if (name == "eqnarray" || name == "eqnarray*") {
1653                                 if (mode != InsetMath::UNDECIDED_MODE) {
1654                                         error("bad math environment " + name);
1655                                         break;
1656                                 }
1657                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1658                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1659                         }
1660
1661                         else if (name == "align" || name == "align*") {
1662                                 if (mode == InsetMath::UNDECIDED_MODE) {
1663                                         cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1664                                         parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1665                                 } else {
1666                                         cell->push_back(MathAtom(new InsetMathSplit(buf, name,
1667                                                         'c', !stared(name))));
1668                                         parse2(cell->back(), FLAG_END, mode, !stared(name));
1669                                 }
1670                         }
1671
1672                         else if (name == "flalign" || name == "flalign*") {
1673                                 if (mode != InsetMath::UNDECIDED_MODE) {
1674                                         error("bad math environment " + name);
1675                                         break;
1676                                 }
1677                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1678                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1679                         }
1680
1681                         else if (name == "alignat" || name == "alignat*") {
1682                                 if (mode != InsetMath::UNDECIDED_MODE) {
1683                                         error("bad math environment " + name);
1684                                         break;
1685                                 }
1686                                 // ignore this for a while
1687                                 getArg('{', '}');
1688                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1689                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1690                         }
1691
1692                         else if (name == "xalignat" || name == "xalignat*") {
1693                                 if (mode != InsetMath::UNDECIDED_MODE) {
1694                                         error("bad math environment " + name);
1695                                         break;
1696                                 }
1697                                 // ignore this for a while
1698                                 getArg('{', '}');
1699                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1700                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1701                         }
1702
1703                         else if (name == "xxalignat") {
1704                                 if (mode != InsetMath::UNDECIDED_MODE) {
1705                                         error("bad math environment " + name);
1706                                         break;
1707                                 }
1708                                 // ignore this for a while
1709                                 getArg('{', '}');
1710                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1711                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1712                         }
1713
1714                         else if (name == "multline" || name == "multline*") {
1715                                 if (mode != InsetMath::UNDECIDED_MODE) {
1716                                         error("bad math environment " + name);
1717                                         break;
1718                                 }
1719                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1720                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1721                         }
1722
1723                         else if (name == "gather" || name == "gather*") {
1724                                 if (mode != InsetMath::UNDECIDED_MODE) {
1725                                         error("bad math environment " + name);
1726                                         break;
1727                                 }
1728                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1729                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1730                         }
1731
1732                         else if (latexkeys const * l = in_word_set(name)) {
1733                                 if (l->inset == "matrix") {
1734                                         cell->push_back(createInsetMath(name, buf));
1735                                         parse2(cell->back(), FLAG_END, mode, false);
1736                                 } else if (l->inset == "split") {
1737                                         docstring const valign = parse_verbatim_option() + 'c';
1738                                         cell->push_back(MathAtom(
1739                                                 new InsetMathSplit(buf, name, (char)valign[0])));
1740                                         parse2(cell->back(), FLAG_END, mode, false);
1741                                 } else {
1742                                         success_ = false;
1743                                         if (!(mode_ & Parse::QUIET)) {
1744                                                 dump();
1745                                                 lyxerr << "found math environment `"
1746                                                        << to_utf8(name)
1747                                                        << "' in symbols file with unsupported inset `"
1748                                                        << l->inset
1749                                                        << "'." << endl;
1750                                         }
1751                                         // create generic environment inset
1752                                         cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1753                                         parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1754                                 }
1755                         }
1756
1757                         else {
1758                                 success_ = false;
1759                                 if (!(mode_ & Parse::QUIET)) {
1760                                         dump();
1761                                         lyxerr << "found unknown math environment '"
1762                                                << to_utf8(name) << "'" << endl;
1763                                 }
1764                                 // create generic environment inset
1765                                 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1766                                 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1767                         }
1768                 }
1769
1770                 else if (t.cs() == "kern" || t.cs() == "mkern") {
1771                         // FIXME: A hack...
1772                         docstring s;
1773                         int num_tokens = 0;
1774                         while (true) {
1775                                 Token const & t = getToken();
1776                                 ++num_tokens;
1777                                 if (!good()) {
1778                                         s.clear();
1779                                         while (num_tokens--)
1780                                                 putback();
1781                                         break;
1782                                 }
1783                                 s += t.character();
1784                                 if (isValidLength(to_utf8(s)))
1785                                         break;
1786                         }
1787                         if (s.empty())
1788                                 cell->push_back(MathAtom(new MathMacro(buf, t.cs())));
1789                         else
1790                                 cell->push_back(MathAtom(new InsetMathKern(s)));
1791                 }
1792
1793                 else if (t.cs() == "label") {
1794                         // FIXME: This is swallowed in inline formulas
1795                         docstring label = parse_verbatim_item();
1796                         MathData ar;
1797                         asArray(label, ar);
1798                         if (grid.asHullInset()) {
1799                                 grid.asHullInset()->label(cellrow, label);
1800                         } else {
1801                                 cell->push_back(createInsetMath(t.cs(), buf));
1802                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1803                         }
1804                 }
1805
1806                 else if (t.cs() == "choose" || t.cs() == "over"
1807                                 || t.cs() == "atop" || t.cs() == "brace"
1808                                 || t.cs() == "brack") {
1809                         MathAtom at = createInsetMath(t.cs(), buf);
1810                         at.nucleus()->cell(0) = *cell;
1811                         cell->clear();
1812                         parse(at.nucleus()->cell(1), flags, mode);
1813                         cell->push_back(at);
1814                         return success_;
1815                 }
1816
1817                 else if (t.cs() == "color") {
1818                         docstring const color = parse_verbatim_item();
1819                         cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1820                         parse(cell->back().nucleus()->cell(0), flags, mode);
1821                         return success_;
1822                 }
1823
1824                 else if (t.cs() == "textcolor") {
1825                         docstring const color = parse_verbatim_item();
1826                         cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1827                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1828                 }
1829
1830                 else if (t.cs() == "normalcolor") {
1831                         cell->push_back(createInsetMath(t.cs(), buf));
1832                         parse(cell->back().nucleus()->cell(0), flags, mode);
1833                         return success_;
1834                 }
1835
1836                 else if (t.cs() == "substack") {
1837                         cell->push_back(createInsetMath(t.cs(), buf));
1838                         parse2(cell->back(), FLAG_ITEM, mode, false);
1839                         // Delete empty last row if present
1840                         InsetMathGrid & subgrid =
1841                                 *(cell->back().nucleus()->asGridInset());
1842                         if (subgrid.nrows() > 1)
1843                                 delEmptyLastRow(subgrid);
1844                 }
1845
1846                 else if (t.cs() == "xymatrix") {
1847                         odocstringstream os;
1848                         while (good() && nextToken().cat() != catBegin)
1849                                 os << getToken().asInput();
1850                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1851                         parse2(cell->back(), FLAG_ITEM, mode, false);
1852                         // Delete empty last row if present
1853                         InsetMathGrid & subgrid =
1854                                 *(cell->back().nucleus()->asGridInset());
1855                         if (subgrid.nrows() > 1)
1856                                 delEmptyLastRow(subgrid);
1857                 }
1858
1859                 else if (t.cs() == "Diagram") {
1860                         odocstringstream os;
1861                         while (good() && nextToken().cat() != catBegin)
1862                                 os << getToken().asInput();
1863                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1864                         parse2(cell->back(), FLAG_ITEM, mode, false);
1865                 }
1866
1867                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1868                         cell->push_back(createInsetMath(t.cs(), buf));
1869                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1870                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1871                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1872                 }
1873
1874                 else if (t.cs() == "tag") {
1875                         if (nextToken().character() == '*') {
1876                                 getToken();
1877                                 cell->push_back(createInsetMath(t.cs() + '*', buf));
1878                         } else
1879                                 cell->push_back(createInsetMath(t.cs(), buf));
1880                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1881                 }
1882
1883                 else if (t.cs() == "hspace") {
1884                         bool const prot =  nextToken().character() == '*';
1885                         if (prot)
1886                                 getToken();
1887                         docstring const name = t.cs();
1888                         docstring const arg = parse_verbatim_item();
1889                         Length length;
1890                         if (prot && arg == "\\fill")
1891                                 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1892                         else if (isValidLength(to_utf8(arg), &length))
1893                                 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1894                         else {
1895                                 // Since the Length class cannot use length variables
1896                                 // we must not create an InsetMathSpace.
1897                                 cell->push_back(MathAtom(new MathMacro(buf, name)));
1898                                 MathData ar;
1899                                 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1900                                 cell->append(ar);
1901                         }
1902                 }
1903
1904                 else if (t.cs() == "smash") {
1905                         skipSpaces();
1906                         if (nextToken().asInput() == "[") {
1907                                 // Since the phantom inset cannot handle optional arguments
1908                                 // other than b and t, we must not create an InsetMathPhantom
1909                                 // if opt is different from b and t (bug 8967).
1910                                 docstring const opt = parse_verbatim_option();
1911                                 if (opt == "t" || opt == "b") {
1912                                         cell->push_back(createInsetMath(t.cs() + opt, buf));
1913                                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1914                                 } else {
1915                                         docstring const arg = parse_verbatim_item();
1916                                         cell->push_back(MathAtom(new MathMacro(buf, t.cs())));
1917                                         MathData ar;
1918                                         mathed_parse_cell(ar, '[' + opt + ']', mode_);
1919                                         cell->append(ar);
1920                                         ar = MathData();
1921                                         mathed_parse_cell(ar, '{' + arg + '}', mode_);
1922                                         cell->append(ar);
1923                                 }
1924                         }
1925                         else {
1926                                 cell->push_back(createInsetMath(t.cs(), buf));
1927                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1928                         }
1929                 }
1930
1931 #if 0
1932                 else if (t.cs() == "infer") {
1933                         MathData ar;
1934                         parse(ar, FLAG_OPTION, mode);
1935                         cell->push_back(createInsetMath(t.cs(), buf));
1936                         parse2(cell->back(), FLAG_ITEM, mode, false);
1937                 }
1938 #endif
1939
1940                 else if (t.cs() == "lyxmathsym") {
1941                         skipSpaces();
1942                         if (getToken().cat() != catBegin) {
1943                                 error("'{' expected in \\" + t.cs());
1944                                 return success_;
1945                         }
1946                         int count = 0;
1947                         docstring cmd;
1948                         CatCode cat = nextToken().cat();
1949                         while (good() && (count || cat != catEnd)) {
1950                                 if (cat == catBegin)
1951                                         ++count;
1952                                 else if (cat == catEnd)
1953                                         --count;
1954                                 cmd += getToken().asInput();
1955                                 cat = nextToken().cat();
1956                         }
1957                         if (getToken().cat() != catEnd) {
1958                                 error("'}' expected in \\" + t.cs());
1959                                 return success_;
1960                         }
1961                         bool termination;
1962                         docstring rem;
1963                         do {
1964                                 cmd = Encodings::fromLaTeXCommand(cmd,
1965                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
1966                                         termination, rem);
1967                                 for (size_t i = 0; i < cmd.size(); ++i)
1968                                         cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1969                                 if (!rem.empty()) {
1970                                         char_type c = rem[0];
1971                                         cell->push_back(MathAtom(new InsetMathChar(c)));
1972                                         cmd = rem.substr(1);
1973                                         rem.clear();
1974                                 } else
1975                                         cmd.clear();
1976                         } while (!cmd.empty());
1977                 }
1978
1979                 else if (!t.cs().empty()) {
1980                         bool const no_mhchem =
1981                                 (t.cs() == "ce" || t.cs() == "cf")
1982                                 && buf && buf->params().use_package("mhchem") ==
1983                                                 BufferParams::package_off;
1984
1985                         bool const is_user_macro = no_mhchem ||
1986                                 (buf && (mode_ & Parse::TRACKMACRO
1987                                          ? buf->usermacros.count(t.cs()) != 0
1988                                          : buf->getMacro(t.cs(), false) != 0));
1989
1990                         latexkeys const * l = in_word_set(t.cs());
1991                         if (l && !is_user_macro) {
1992                                 if (l->inset == "big") {
1993                                         skipSpaces();
1994                                         docstring const delim = getToken().asInput();
1995                                         if (InsetMathBig::isBigInsetDelim(delim))
1996                                                 cell->push_back(MathAtom(
1997                                                         new InsetMathBig(t.cs(), delim)));
1998                                         else {
1999                                                 cell->push_back(createInsetMath(t.cs(), buf));
2000                                                 putback();
2001                                         }
2002                                 }
2003
2004                                 else if (l->inset == "font") {
2005                                         cell->push_back(createInsetMath(t.cs(), buf));
2006                                         parse(cell->back().nucleus()->cell(0),
2007                                                 FLAG_ITEM, asMode(mode, l->extra));
2008                                 }
2009
2010                                 else if (l->inset == "oldfont") {
2011                                         cell->push_back(createInsetMath(t.cs(), buf));
2012                                         parse(cell->back().nucleus()->cell(0),
2013                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
2014                                         if (prevToken().cat() != catAlign &&
2015                                             prevToken().cs() != "\\")
2016                                                 return success_;
2017                                         putback();
2018                                 }
2019
2020                                 else if (l->inset == "style") {
2021                                         cell->push_back(createInsetMath(t.cs(), buf));
2022                                         parse(cell->back().nucleus()->cell(0),
2023                                                 flags | FLAG_ALIGN, mode);
2024                                         if (prevToken().cat() != catAlign &&
2025                                             prevToken().cs() != "\\")
2026                                                 return success_;
2027                                         putback();
2028                                 }
2029
2030                                 else {
2031                                         MathAtom at = createInsetMath(t.cs(), buf);
2032                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
2033                                                 parse(at.nucleus()->cell(i),
2034                                                         FLAG_ITEM, asMode(mode, l->extra));
2035                                         cell->push_back(at);
2036                                 }
2037                         }
2038
2039                         else {
2040                                 bool is_unicode_symbol = false;
2041                                 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
2042                                         int num_tokens = 0;
2043                                         docstring cmd = prevToken().asInput();
2044                                         CatCode cat = nextToken().cat();
2045                                         if (cat == catBegin) {
2046                                                 int count = 0;
2047                                                 while (good() && (count || cat != catEnd)) {
2048                                                         cat = nextToken().cat();
2049                                                         cmd += getToken().asInput();
2050                                                         ++num_tokens;
2051                                                         if (cat == catBegin)
2052                                                                 ++count;
2053                                                         else if (cat == catEnd)
2054                                                                 --count;
2055                                                 }
2056                                         }
2057                                         bool is_combining;
2058                                         bool termination;
2059                                         char_type c = Encodings::fromLaTeXCommand(cmd,
2060                                                 Encodings::MATH_CMD | Encodings::TEXT_CMD,
2061                                                 is_combining, termination);
2062                                         if (is_combining) {
2063                                                 if (cat == catLetter)
2064                                                         cmd += '{';
2065                                                 cmd += getToken().asInput();
2066                                                 ++num_tokens;
2067                                                 if (cat == catLetter)
2068                                                         cmd += '}';
2069                                                 c = Encodings::fromLaTeXCommand(cmd,
2070                                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
2071                                                         is_combining, termination);
2072                                         }
2073                                         if (c) {
2074                                                 if (termination) {
2075                                                         if (nextToken().cat() == catBegin) {
2076                                                                 getToken();
2077                                                                 if (nextToken().cat() == catEnd) {
2078                                                                         getToken();
2079                                                                         num_tokens += 2;
2080                                                                 } else
2081                                                                         putback();
2082                                                         } else {
2083                                                                 while (nextToken().cat() == catSpace) {
2084                                                                         getToken();
2085                                                                         ++num_tokens;
2086                                                                 }
2087                                                         }
2088                                                 }
2089                                                 is_unicode_symbol = true;
2090                                                 cell->push_back(MathAtom(new InsetMathChar(c)));
2091                                         } else {
2092                                                 while (num_tokens--)
2093                                                         putback();
2094                                         }
2095                                 }
2096                                 if (!is_unicode_symbol) {
2097                                         MathAtom at = is_user_macro ?
2098                                                 MathAtom(new MathMacro(buf, t.cs()))
2099                                                 : createInsetMath(t.cs(), buf);
2100                                         InsetMath::mode_type m = mode;
2101                                         //if (m == InsetMath::UNDECIDED_MODE)
2102                                         //lyxerr << "default creation: m1: " << m << endl;
2103                                         if (at->currentMode() != InsetMath::UNDECIDED_MODE)
2104                                                 m = at->currentMode();
2105                                         //lyxerr << "default creation: m2: " << m << endl;
2106                                         InsetMath::idx_type start = 0;
2107                                         // this fails on \bigg[...\bigg]
2108                                         //MathData opt;
2109                                         //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
2110                                         //if (!opt.empty()) {
2111                                         //      start = 1;
2112                                         //      at.nucleus()->cell(0) = opt;
2113                                         //}
2114                                         for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
2115                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
2116                                                 if (mode == InsetMath::MATH_MODE)
2117                                                         skipSpaces();
2118                                         }
2119                                         cell->push_back(at);
2120                                 }
2121                         }
2122                 }
2123
2124
2125                 if (flags & FLAG_LEAVE) {
2126                         flags &= ~FLAG_LEAVE;
2127                         break;
2128                 }
2129         }
2130         return success_;
2131 }
2132
2133
2134
2135 } // anonymous namespace
2136
2137
2138 // FIXME This will likely need some work.
2139 char const * latexkeys::MathMLtype() const
2140 {
2141         if (extra == "mathord")
2142                 return "mi";
2143         return "mo";
2144 }
2145
2146
2147 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2148 {
2149         return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2150                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2151 }
2152
2153
2154 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2155 {
2156         return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2157                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2158 }
2159
2160
2161 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2162                          Parse::flags f)
2163 {
2164         return Parser(str, f, buf).parse(t);
2165 }
2166
2167
2168 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2169                          Parse::flags f)
2170 {
2171         return Parser(lex, f, buf).parse(t);
2172 }
2173
2174
2175 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2176                          Parse::flags f)
2177 {
2178         return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2179                         InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2180 }
2181
2182
2183 void initParser()
2184 {
2185         fill(theCatcode, theCatcode + 128, catOther);
2186         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2187         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2188
2189         theCatcode[int('\\')] = catEscape;
2190         theCatcode[int('{')]  = catBegin;
2191         theCatcode[int('}')]  = catEnd;
2192         theCatcode[int('$')]  = catMath;
2193         theCatcode[int('&')]  = catAlign;
2194         theCatcode[int('\n')] = catNewline;
2195         theCatcode[int('#')]  = catParameter;
2196         theCatcode[int('^')]  = catSuper;
2197         theCatcode[int('_')]  = catSub;
2198         theCatcode[int(0x7f)] = catIgnore;
2199         theCatcode[int(' ')]  = catSpace;
2200         theCatcode[int('\t')] = catSpace;
2201         theCatcode[int('\r')] = catNewline;
2202         theCatcode[int('~')]  = catActive;
2203         theCatcode[int('%')]  = catComment;
2204 }
2205
2206
2207 } // namespace lyx