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