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