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