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