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