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