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