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