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