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