]> git.lyx.org Git - lyx.git/blob - src/mathed/MathParser.cpp
Attempt to fix #8137 (arrived at r40862).
[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                 putback();
540                 return 0;
541         }
542         return tokens_[pos_++].character();
543 }
544
545
546 docstring Parser::getArg(char_type left, char_type right)
547 {
548         skipSpaces();
549
550         docstring result;
551         char_type c = getChar();
552
553         if (c != left)
554                 putback();
555         else
556                 while ((c = getChar()) != right && good())
557                         result += c;
558
559         return result;
560 }
561
562
563 void Parser::skipSpaceTokens(idocstream & is, char_type c)
564 {
565         // skip trailing spaces
566         while (catcode(c) == catSpace || catcode(c) == catNewline)
567                 if (!is.get(c))
568                         break;
569         //lyxerr << "putting back: " << c << endl;
570         is.putback(c);
571 }
572
573
574 void Parser::tokenize(istream & is)
575 {
576         // eat everything up to the next \end_inset or end of stream
577         // and store it in s for further tokenization
578         string s;
579         char c;
580         while (is.get(c)) {
581                 s += c;
582                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
583                         s = s.substr(0, s.size() - 10);
584                         break;
585                 }
586         }
587         // Remove the space after \end_inset
588         if (is.get(c) && c != ' ')
589                 is.unget();
590
591         // tokenize buffer
592         tokenize(from_utf8(s));
593 }
594
595
596 void Parser::tokenize(docstring const & buffer)
597 {
598         idocstringstream is(mode_ & Parse::VERBATIM
599                         ? escapeSpecialChars(buffer, mode_ & Parse::TEXTMODE)
600                         : buffer, ios::in | ios::binary);
601
602         char_type c;
603         while (is.get(c)) {
604                 //lyxerr << "reading c: " << c << endl;
605
606                 switch (catcode(c)) {
607                         case catNewline: {
608                                 ++lineno_;
609                                 is.get(c);
610                                 if (catcode(c) == catNewline)
611                                         ; //push_back(Token("par"));
612                                 else {
613                                         push_back(Token('\n', catNewline));
614                                         is.putback(c);
615                                 }
616                                 break;
617                         }
618
619 /*
620                         case catComment: {
621                                 while (is.get(c) && catcode(c) != catNewline)
622                                         ;
623                                 ++lineno_;
624                                 break;
625                         }
626 */
627
628                         case catEscape: {
629                                 is.get(c);
630                                 if (!is) {
631                                         error("unexpected end of input");
632                                 } else {
633                                         if (c == '\n')
634                                                 c = ' ';
635                                         docstring s(1, c);
636                                         if (catcode(c) == catLetter) {
637                                                 // collect letters
638                                                 while (is.get(c) && catcode(c) == catLetter)
639                                                         s += c;
640                                                 skipSpaceTokens(is, c);
641                                         }
642                                         push_back(Token(s));
643                                 }
644                                 break;
645                         }
646
647                         case catSuper:
648                         case catSub: {
649                                 push_back(Token(c, catcode(c)));
650                                 is.get(c);
651                                 skipSpaceTokens(is, c);
652                                 break;
653                         }
654
655                         case catIgnore: {
656                                 if (!(mode_ & Parse::QUIET))
657                                         lyxerr << "ignoring a char: " << int(c) << endl;
658                                 break;
659                         }
660
661                         default:
662                                 push_back(Token(c, catcode(c)));
663                 }
664         }
665
666 #ifdef FILEDEBUG
667         dump();
668 #endif
669 }
670
671
672 void Parser::dump() const
673 {
674         lyxerr << "\nTokens: ";
675         for (unsigned i = 0; i < tokens_.size(); ++i) {
676                 if (i == pos_)
677                         lyxerr << " <#> ";
678                 lyxerr << tokens_[i];
679         }
680         lyxerr << " pos: " << pos_ << endl;
681 }
682
683
684 void Parser::error(string const & msg)
685 {
686         success_ = false;
687         if (!(mode_ & Parse::QUIET)) {
688                 lyxerr << "Line ~" << lineno_ << ": Math parse error: "
689                        << msg << endl;
690                 dump();
691         }
692 }
693
694
695 bool Parser::parse(MathAtom & at)
696 {
697         skipSpaces();
698         MathData ar(buffer_);
699         parse(ar, false, InsetMath::UNDECIDED_MODE);
700         if (ar.size() != 1 || ar.front()->getType() == hullNone) {
701                 if (!(mode_ & Parse::QUIET))
702                         lyxerr << "unusual contents found: " << ar << endl;
703                 at = MathAtom(new InsetMathPar(buffer_, ar));
704                 //if (at->nargs() > 0)
705                 //      at.nucleus()->cell(0) = ar;
706                 //else
707                 //      lyxerr << "unusual contents found: " << ar << endl;
708                 success_ = false;
709         } else
710                 at = ar[0];
711         return success_;
712 }
713
714
715 docstring Parser::parse_verbatim_option()
716 {
717         skipSpaces();
718         docstring res;
719         if (nextToken().character() == '[') {
720                 Token t = getToken();
721                 for (Token t = getToken(); t.character() != ']' && good(); t = getToken()) {
722                         if (t.cat() == catBegin) {
723                                 putback();
724                                 res += '{' + parse_verbatim_item() + '}';
725                         } else
726                                 res += t.asInput();
727                 }
728         }
729         return res;
730 }
731
732
733 docstring Parser::parse_verbatim_item()
734 {
735         skipSpaces();
736         docstring res;
737         if (nextToken().cat() == catBegin) {
738                 Token t = getToken();
739                 for (Token t = getToken(); t.cat() != catEnd && good(); t = getToken()) {
740                         if (t.cat() == catBegin) {
741                                 putback();
742                                 res += '{' + parse_verbatim_item() + '}';
743                         }
744                         else
745                                 res += t.asInput();
746                 }
747         }
748         return res;
749 }
750
751
752 MathData Parser::parse(unsigned flags, mode_type mode)
753 {
754         MathData ar(buffer_);
755         parse(ar, flags, mode);
756         return ar;
757 }
758
759
760 bool Parser::parse(MathData & array, unsigned flags, mode_type mode)
761 {
762         InsetMathGrid grid(buffer_, 1, 1);
763         parse1(grid, flags, mode, false);
764         array = grid.cell(0);
765         return success_;
766 }
767
768
769 void Parser::parse2(MathAtom & at, const unsigned flags, const mode_type mode,
770         const bool numbered)
771 {
772         parse1(*(at.nucleus()->asGridInset()), flags, mode, numbered);
773 }
774
775
776 bool Parser::parse1(InsetMathGrid & grid, unsigned flags,
777         const mode_type mode, const bool numbered)
778 {
779         int limits = 0;
780         InsetMathGrid::row_type cellrow = 0;
781         InsetMathGrid::col_type cellcol = 0;
782         MathData * cell = &grid.cell(grid.index(cellrow, cellcol));
783         Buffer * buf = buffer_;
784
785         if (grid.asHullInset())
786                 grid.asHullInset()->numbered(cellrow, numbered);
787
788         //dump();
789         //lyxerr << " flags: " << flags << endl;
790         //lyxerr << " mode: " << mode  << endl;
791         //lyxerr << "grid: " << grid << endl;
792
793         while (good()) {
794                 Token const & t = getToken();
795
796 #ifdef FILEDEBUG
797                 lyxerr << "t: " << t << " flags: " << flags << endl;
798                 lyxerr << "mode: " << mode  << endl;
799                 cell->dump();
800                 lyxerr << endl;
801 #endif
802
803                 if (flags & FLAG_ITEM) {
804
805                         if (t.cat() == catBegin) {
806                                 // skip the brace and collect everything to the next matching
807                                 // closing brace
808                                 parse1(grid, FLAG_BRACE_LAST, mode, numbered);
809                                 return success_;
810                         }
811
812                         // handle only this single token, leave the loop if done
813                         flags = FLAG_LEAVE;
814                 }
815
816
817                 if (flags & FLAG_BRACED) {
818                         if (t.cat() == catSpace)
819                                 continue;
820
821                         if (t.cat() != catBegin) {
822                                 error("opening brace expected");
823                                 return success_;
824                         }
825
826                         // skip the brace and collect everything to the next matching
827                         // closing brace
828                         flags = FLAG_BRACE_LAST;
829                 }
830
831
832                 if (flags & FLAG_OPTION) {
833                         if (t.cat() == catOther && t.character() == '[') {
834                                 MathData ar;
835                                 parse(ar, FLAG_BRACK_LAST, mode);
836                                 cell->append(ar);
837                         } else {
838                                 // no option found, put back token and we are done
839                                 putback();
840                         }
841                         return success_;
842                 }
843
844                 //
845                 // cat codes
846                 //
847                 if (t.cat() == catMath) {
848                         if (mode != InsetMath::MATH_MODE) {
849                                 // we are inside some text mode thingy, so opening new math is allowed
850                                 Token const & n = getToken();
851                                 if (n.cat() == catMath) {
852                                         // TeX's $$...$$ syntax for displayed math
853                                         if (mode == InsetMath::UNDECIDED_MODE) {
854                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
855                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
856                                                 getToken(); // skip the second '$' token
857                                         } else {
858                                                 // This is not an outer hull and display math is
859                                                 // not allowed inside text mode environments.
860                                                 error("bad math environment");
861                                                 break;
862                                         }
863                                 } else {
864                                         // simple $...$  stuff
865                                         putback();
866                                         if (mode == InsetMath::UNDECIDED_MODE) {
867                                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullSimple)));
868                                                 parse2(cell->back(), FLAG_SIMPLE, InsetMath::MATH_MODE, false);
869                                         } else {
870                                                 // Don't create nested math hulls (bug #5392)
871                                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
872                                                 parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
873                                         }
874                                 }
875                         }
876
877                         else if (flags & FLAG_SIMPLE) {
878                                 // this is the end of the formula
879                                 return success_;
880                         }
881
882                         else {
883                                 Token const & n = getToken();
884                                 if (n.cat() == catMath) {
885                                         error("something strange in the parser");
886                                         break;
887                                 } else {
888                                         // This is inline math ($...$), but the parser thinks we are
889                                         // already in math mode and latex would issue an error, unless we
890                                         // are inside a text mode user macro. We have no way to tell, so
891                                         // let's play safe by using \ensuremath, as it will work in any case.
892                                         putback();
893                                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
894                                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE, InsetMath::MATH_MODE);
895                                 }
896                         }
897                 }
898
899                 else if (t.cat() == catLetter)
900                         cell->push_back(MathAtom(new InsetMathChar(t.character())));
901
902                 else if (t.cat() == catSpace && mode != InsetMath::MATH_MODE) {
903                         if (cell->empty() || cell->back()->getChar() != ' ')
904                                 cell->push_back(MathAtom(new InsetMathChar(t.character())));
905                 }
906
907                 else if (t.cat() == catNewline && mode != InsetMath::MATH_MODE) {
908                         if (cell->empty() || cell->back()->getChar() != ' ')
909                                 cell->push_back(MathAtom(new InsetMathChar(' ')));
910                 }
911
912                 else if (t.cat() == catParameter) {
913                         Token const & n = getToken();
914                         cell->push_back(MathAtom(new MathMacroArgument(n.character()-'0')));
915                 }
916
917                 else if (t.cat() == catActive)
918                         cell->push_back(MathAtom(new InsetMathSpace(string(1, t.character()), "")));
919
920                 else if (t.cat() == catBegin) {
921                         MathData ar;
922                         parse(ar, FLAG_BRACE_LAST, mode);
923                         // do not create a BraceInset if they were written by LyX
924                         // this helps to keep the annoyance of  "a choose b"  to a minimum
925                         if (ar.size() == 1 && ar[0]->extraBraces())
926                                 cell->append(ar);
927                         else
928                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
929                 }
930
931                 else if (t.cat() == catEnd) {
932                         if (flags & FLAG_BRACE_LAST)
933                                 return success_;
934                         error("found '}' unexpectedly");
935                         //LASSERT(false, /**/);
936                         //add(cell, '}', LM_TC_TEX);
937                 }
938
939                 else if (t.cat() == catAlign) {
940                         //lyxerr << " column now " << (cellcol + 1)
941                         //       << " max: " << grid.ncols() << endl;
942                         if (flags & FLAG_ALIGN)
943                                 return success_;
944                         if (addCol(grid, cellcol))
945                                 cell = &grid.cell(grid.index(cellrow, cellcol));
946                 }
947
948                 else if (t.cat() == catSuper || t.cat() == catSub) {
949                         bool up = (t.cat() == catSuper);
950                         // we need no new script inset if the last thing was a scriptinset,
951                         // which has that script already not the same script already
952                         if (!cell->size())
953                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
954                         else if (cell->back()->asScriptInset() &&
955                                         !cell->back()->asScriptInset()->has(up))
956                                 cell->back().nucleus()->asScriptInset()->ensure(up);
957                         else if (cell->back()->asScriptInset())
958                                 cell->push_back(MathAtom(new InsetMathScript(buf, up)));
959                         else
960                                 cell->back() = MathAtom(new InsetMathScript(buf, cell->back(), up));
961                         InsetMathScript * p = cell->back().nucleus()->asScriptInset();
962                         // special handling of {}-bases
963                         // Here we could remove the brace inset for things
964                         // like {a'}^2 and add the braces back in
965                         // InsetMathScript::write().
966                         // We do not do it, since it is not possible to detect
967                         // reliably whether the braces are needed because the
968                         // nucleus contains more than one symbol, or whether
969                         // they are needed for unknown commands like \xx{a}_0
970                         // or \yy{a}{b}_0. This was done in revision 14819
971                         // in an unreliable way. See this thread
972                         // http://www.mail-archive.com/lyx-devel%40lists.lyx.org/msg104917.html
973                         // for more details.
974                         // However, we remove empty braces because they look
975                         // ugly on screen and we are sure that they were added
976                         // by the write() method (and will be re-added on save).
977                         if (p->nuc().size() == 1 &&
978                             p->nuc().back()->asBraceInset() &&
979                             p->nuc().back()->asBraceInset()->cell(0).empty())
980                                 p->nuc().erase(0);
981
982                         parse(p->cell(p->idxOfScript(up)), FLAG_ITEM, mode);
983                         if (limits) {
984                                 p->limits(limits);
985                                 limits = 0;
986                         }
987                 }
988
989                 else if (t.character() == ']' && (flags & FLAG_BRACK_LAST)) {
990                         //lyxerr << "finished reading option" << endl;
991                         return success_;
992                 }
993
994                 else if (t.cat() == catOther) {
995                         char_type c = t.character();
996                         if (isAsciiOrMathAlpha(c)
997                             || mode_ & Parse::VERBATIM
998                             || !(mode_ & Parse::USETEXT)
999                             || mode == InsetMath::TEXT_MODE) {
1000                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1001                         } else {
1002                                 MathAtom at = createInsetMath("text", buf);
1003                                 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1004                                 while (nextToken().cat() == catOther
1005                                        && !isAsciiOrMathAlpha(nextToken().character())) {
1006                                         c = getToken().character();
1007                                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1008                                 }
1009                                 cell->push_back(at);
1010                         }
1011                 }
1012
1013                 else if (t.cat() == catComment) {
1014                         docstring s;
1015                         while (good()) {
1016                                 Token const & t = getToken();
1017                                 if (t.cat() == catNewline)
1018                                         break;
1019                                 s += t.asString();
1020                         }
1021                         cell->push_back(MathAtom(new InsetMathComment(buf, s)));
1022                         skipSpaces();
1023                 }
1024
1025                 //
1026                 // control sequences
1027                 //
1028
1029                 else if (t.cs() == "lyxlock") {
1030                         if (cell->size())
1031                                 cell->back().nucleus()->lock(true);
1032                 }
1033
1034                 else if ((t.cs() == "global" && nextToken().cs() == "def") ||
1035                          t.cs() == "def") {
1036                         if (t.cs() == "global")
1037                                 getToken();
1038                         
1039                         // get name
1040                         docstring name = getToken().cs();
1041                         
1042                         // read parameters
1043                         int nargs = 0;
1044                         docstring pars;
1045                         while (good() && nextToken().cat() != catBegin) {
1046                                 pars += getToken().cs();
1047                                 ++nargs;
1048                         }
1049                         nargs /= 2;
1050                         
1051                         // read definition
1052                         MathData def;
1053                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1054                         
1055                         // is a version for display attached?
1056                         skipSpaces();
1057                         MathData display;
1058                         if (nextToken().cat() == catBegin)
1059                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1060                         
1061                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1062                                 name, nargs, 0, MacroTypeDef,
1063                                 vector<MathData>(), def, display)));
1064
1065                         if (buf && (mode_ & Parse::TRACKMACRO))
1066                                 buf->usermacros.insert(name);
1067                 }
1068                 
1069                 else if (t.cs() == "newcommand" ||
1070                          t.cs() == "renewcommand" ||
1071                          t.cs() == "newlyxcommand") {
1072                         // get name
1073                         if (getToken().cat() != catBegin) {
1074                                 error("'{' in \\newcommand expected (1) ");
1075                                 return success_;
1076                         }
1077                         docstring name = getToken().cs();
1078                         if (getToken().cat() != catEnd) {
1079                                 error("'}' in \\newcommand expected");
1080                                 return success_;
1081                         }
1082                                 
1083                         // get arity
1084                         docstring const arg = getArg('[', ']');
1085                         int nargs = 0;
1086                         if (!arg.empty())
1087                                 nargs = convert<int>(arg);
1088                                 
1089                         // optional argument given?
1090                         skipSpaces();
1091                         int optionals = 0;
1092                         vector<MathData> optionalValues;
1093                         while (nextToken().character() == '[') {
1094                                 getToken();
1095                                 optionalValues.push_back(MathData());
1096                                 parse(optionalValues[optionals], FLAG_BRACK_LAST, mode);
1097                                 ++optionals;
1098                         }
1099                         
1100                         MathData def;
1101                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1102                         
1103                         // is a version for display attached?
1104                         skipSpaces();
1105                         MathData display;
1106                         if (nextToken().cat() == catBegin)
1107                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1108                         
1109                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1110                                 name, nargs, optionals, MacroTypeNewcommand,
1111                                 optionalValues, def, display)));
1112
1113                         if (buf && (mode_ & Parse::TRACKMACRO))
1114                                 buf->usermacros.insert(name);
1115                 }
1116                 
1117                 else if (t.cs() == "newcommandx" ||
1118                          t.cs() == "renewcommandx") {
1119                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1120                         // get name
1121                         docstring name;
1122                         if (nextToken().cat() == catBegin) {
1123                                 getToken();
1124                                 name = getToken().cs();
1125                                 if (getToken().cat() != catEnd) {
1126                                         error("'}' in \\newcommandx expected");
1127                                         return success_;
1128                                 }
1129                         } else
1130                                 name = getToken().cs();
1131                                 
1132                         // get arity
1133                         docstring const arg = getArg('[', ']');
1134                         if (arg.empty()) {
1135                                 error("[num] in \\newcommandx expected");
1136                                 return success_;
1137                         }
1138                         int nargs = convert<int>(arg);
1139                         
1140                         // get options
1141                         int optionals = 0;
1142                         vector<MathData> optionalValues;
1143                         if (nextToken().character() == '[') {
1144                                 // skip '['
1145                                 getToken();
1146                                         
1147                                 // handle 'opt=value' options, separated by ','.
1148                                 skipSpaces();
1149                                 while (nextToken().character() != ']' && good()) {
1150                                         if (nextToken().character() >= '1'
1151                                             && nextToken().character() <= '9') {
1152                                                 // optional value -> get parameter number
1153                                                 int n = getChar() - '0';
1154                                                 if (n > nargs) {
1155                                                         error("Arity of \\newcommandx too low "
1156                                                               "for given optional parameter.");
1157                                                         return success_;
1158                                                 }
1159                                                 
1160                                                 // skip '='
1161                                                 if (getToken().character() != '=') {
1162                                                         error("'=' and optional parameter value "
1163                                                               "expected for \\newcommandx");
1164                                                         return success_;
1165                                                 }
1166                                                 
1167                                                 // get value
1168                                                 int optNum = max(size_t(n), optionalValues.size());
1169                                                 optionalValues.resize(optNum);
1170                                                 optionalValues[n - 1].clear();
1171                                                 while (nextToken().character() != ']'
1172                                                        && nextToken().character() != ',') {
1173                                                         MathData data;
1174                                                         parse(data, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1175                                                         optionalValues[n - 1].append(data);
1176                                                 }
1177                                                 optionals = max(n, optionals);
1178                                         } else if (nextToken().cat() == catLetter) {
1179                                                 // we in fact ignore every non-optional
1180                                                 // parameter
1181                                                 
1182                                                 // get option name
1183                                                 docstring opt;
1184                                                 while (nextToken().cat() == catLetter)
1185                                                         opt += getChar();
1186                                         
1187                                                 // value?
1188                                                 skipSpaces();
1189                                                 MathData value;
1190                                                 if (nextToken().character() == '=') {
1191                                                         getToken();
1192                                                         while (nextToken().character() != ']'
1193                                                                 && nextToken().character() != ',')
1194                                                                 parse(value, FLAG_ITEM, 
1195                                                                       InsetMath::UNDECIDED_MODE);
1196                                                 }
1197                                         } else {
1198                                                 error("option for \\newcommandx expected");
1199                                                 return success_;
1200                                         }
1201                                         
1202                                         // skip komma
1203                                         skipSpaces();
1204                                         if (nextToken().character() == ',') {
1205                                                 getChar();
1206                                                 skipSpaces();
1207                                         } else if (nextToken().character() != ']') {
1208                                                 error("Expecting ',' or ']' in options "
1209                                                       "of \\newcommandx");
1210                                                 return success_;
1211                                         }
1212                                 }
1213                                 
1214                                 // skip ']'
1215                                 if (!good())
1216                                         return success_;
1217                                 getToken();
1218                         }
1219
1220                         // get definition
1221                         MathData def;
1222                         parse(def, FLAG_ITEM, InsetMath::UNDECIDED_MODE);
1223
1224                         // is a version for display attached?
1225                         skipSpaces();
1226                         MathData display;
1227                         if (nextToken().cat() == catBegin)
1228                                 parse(display, FLAG_ITEM, InsetMath::MATH_MODE);
1229
1230                         cell->push_back(MathAtom(new MathMacroTemplate(buf,
1231                                 name, nargs, optionals, MacroTypeNewcommandx,
1232                                 optionalValues, def, display)));
1233
1234                         if (buf && (mode_ & Parse::TRACKMACRO))
1235                                 buf->usermacros.insert(name);
1236                 }
1237
1238                 else if (t.cs() == "(") {
1239                         cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1240                         parse(cell->back().nucleus()->cell(0), FLAG_SIMPLE2, InsetMath::MATH_MODE);
1241                 }
1242
1243                 else if (t.cs() == "[") {
1244                         if (mode != InsetMath::UNDECIDED_MODE) {
1245                                 error("bad math environment");
1246                                 break;
1247                         }
1248                         cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1249                         parse2(cell->back(), FLAG_EQUATION, InsetMath::MATH_MODE, false);
1250                 }
1251
1252                 else if (t.cs() == "protect")
1253                         // ignore \\protect, will hopefully be re-added during output
1254                         ;
1255
1256                 else if (t.cs() == "end") {
1257                         if (flags & FLAG_END) {
1258                                 // eat environment name
1259                                 docstring const name = getArg('{', '}');
1260                                 if (environments_.empty())
1261                                         error("'found \\end{" + name +
1262                                               "}' without matching '\\begin{" +
1263                                               name + "}'");
1264                                 else if (name != environments_.back())
1265                                         error("'\\end{" + name +
1266                                               "}' does not match '\\begin{" +
1267                                               environments_.back() + "}'");
1268                                 else {
1269                                         environments_.pop_back();
1270                                         // Delete empty last row in matrix
1271                                         // like insets.
1272                                         // If you abuse InsetMathGrid for
1273                                         // non-matrix like structures you
1274                                         // probably need to refine this test.
1275                                         // Right now we only have to test for
1276                                         // single line hull insets.
1277                                         if (grid.nrows() > 1 && innerHull(name))
1278                                                 delEmptyLastRow(grid);
1279                                         return success_;
1280                                 }
1281                         } else
1282                                 error("found 'end' unexpectedly");
1283                 }
1284
1285                 else if (t.cs() == ")") {
1286                         if (flags & FLAG_SIMPLE2)
1287                                 return success_;
1288                         error("found '\\)' unexpectedly");
1289                 }
1290
1291                 else if (t.cs() == "]") {
1292                         if (flags & FLAG_EQUATION)
1293                                 return success_;
1294                         error("found '\\]' unexpectedly");
1295                 }
1296
1297                 else if (t.cs() == "\\") {
1298                         if (flags & FLAG_ALIGN)
1299                                 return success_;
1300                         bool added = false;
1301                         if (nextToken().asInput() == "*") {
1302                                 getToken();
1303                                 added = addRow(grid, cellrow, docstring(), false);
1304                         } else if (good())
1305                                 added = addRow(grid, cellrow, getArg('[', ']'));
1306                         else
1307                                 error("missing token after \\\\");
1308                         if (added) {
1309                                 cellcol = 0;
1310                                 if (grid.asHullInset())
1311                                         grid.asHullInset()->numbered(
1312                                                         cellrow, numbered);
1313                                 cell = &grid.cell(grid.index(cellrow,
1314                                                              cellcol));
1315                         }
1316                 }
1317
1318 #if 0
1319                 else if (t.cs() == "multicolumn") {
1320                         // extract column count and insert dummy cells
1321                         MathData count;
1322                         parse(count, FLAG_ITEM, mode);
1323                         int cols = 1;
1324                         if (!extractNumber(count, cols)) {
1325                                 success_ = false;
1326                                 lyxerr << " can't extract number of cells from " << count << endl;
1327                         }
1328                         // resize the table if necessary
1329                         for (int i = 0; i < cols; ++i) {
1330                                 if (addCol(grid, cellcol)) {
1331                                         cell = &grid.cell(grid.index(
1332                                                         cellrow, cellcol));
1333                                         // mark this as dummy
1334                                         grid.cellinfo(grid.index(
1335                                                 cellrow, cellcol)).dummy_ = true;
1336                                 }
1337                         }
1338                         // the last cell is the real thing, not a dummy
1339                         grid.cellinfo(grid.index(cellrow, cellcol)).dummy_ = false;
1340
1341                         // read special alignment
1342                         MathData align;
1343                         parse(align, FLAG_ITEM, mode);
1344                         //grid.cellinfo(grid.index(cellrow, cellcol)).align_ = extractString(align);
1345
1346                         // parse the remaining contents into the "real" cell
1347                         parse(*cell, FLAG_ITEM, mode);
1348                 }
1349 #endif
1350
1351                 else if (t.cs() == "limits" || t.cs() == "nolimits") {
1352                         CatCode const cat = nextToken().cat();
1353                         if (cat == catSuper || cat == catSub)
1354                                 limits = t.cs() == "limits" ? 1 : -1;
1355                         else {
1356                                 MathAtom at = createInsetMath(t.cs(), buf);
1357                                 cell->push_back(at);
1358                         }
1359                 }
1360
1361                 else if (t.cs() == "nonumber") {
1362                         if (grid.asHullInset())
1363                                 grid.asHullInset()->numbered(cellrow, false);
1364                 }
1365
1366                 else if (t.cs() == "number") {
1367                         if (grid.asHullInset())
1368                                 grid.asHullInset()->numbered(cellrow, true);
1369                 }
1370
1371                 else if (t.cs() == "hline") {
1372                         grid.rowinfo(cellrow).lines_ ++;
1373                 }
1374
1375                 else if (t.cs() == "sqrt") {
1376                         MathData ar;
1377                         parse(ar, FLAG_OPTION, mode);
1378                         if (ar.size()) {
1379                                 cell->push_back(MathAtom(new InsetMathRoot(buf)));
1380                                 cell->back().nucleus()->cell(0) = ar;
1381                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1382                         } else {
1383                                 cell->push_back(MathAtom(new InsetMathSqrt(buf)));
1384                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1385                         }
1386                 }
1387
1388                 else if (t.cs() == "cancelto") {
1389                         MathData ar;
1390                         parse(ar, FLAG_ITEM, mode);
1391                                 cell->push_back(MathAtom(new InsetMathCancelto(buf)));
1392                                 cell->back().nucleus()->cell(1) = ar;
1393                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1394                 }
1395
1396                 else if (t.cs() == "unit") {
1397                         // Allowed formats \unit[val]{unit}
1398                         MathData ar;
1399                         parse(ar, FLAG_OPTION, mode);
1400                         if (ar.size()) {
1401                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT)));
1402                                 cell->back().nucleus()->cell(0) = ar;
1403                                 parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1404                         } else {
1405                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1)));
1406                                 parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1407                         }
1408                 }
1409
1410                 else if (t.cs() == "unitfrac") {
1411                         // Here allowed formats are \unitfrac[val]{num}{denom}
1412                         MathData ar;
1413                         parse(ar, FLAG_OPTION, mode);
1414                         if (ar.size()) {
1415                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3)));
1416                                 cell->back().nucleus()->cell(2) = ar;
1417                         } else {
1418                                 cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC)));
1419                         }
1420                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1421                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1422                 }
1423
1424                 else if (t.cs() == "cfrac") {
1425                         // allowed formats are \cfrac[pos]{num}{denom}
1426                         docstring const arg = getArg('[', ']');
1427                         //lyxerr << "got so far: '" << arg << "'" << endl;                              
1428                                 if (arg == "l")
1429                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT)));
1430                                 else if (arg == "r")
1431                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT)));
1432                                 else if (arg.empty() || arg == "c")
1433                                         cell->push_back(MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC)));
1434                                 else {
1435                                         error("found invalid optional argument");
1436                                         break;
1437                                 }
1438                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1439                         parse(cell->back().nucleus()->cell(1), FLAG_ITEM, mode);
1440                 }
1441
1442                 else if (t.cs() == "xrightarrow" || t.cs() == "xleftarrow") {
1443                         cell->push_back(createInsetMath(t.cs(), buf));
1444                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, mode);
1445                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, mode);
1446                 }
1447
1448                 else if (t.cs() == "ref" || t.cs() == "eqref" || t.cs() == "prettyref"
1449                           || t.cs() == "pageref" || t.cs() == "vpageref" || t.cs() == "vref") {
1450                         cell->push_back(MathAtom(new InsetMathRef(buf, t.cs())));
1451                         docstring const opt = parse_verbatim_option();
1452                         docstring const ref = parse_verbatim_item();
1453                         if (!opt.empty()) {
1454                                 cell->back().nucleus()->cell(1).push_back(
1455                                         MathAtom(new InsetMathString(opt)));
1456                         }
1457                         cell->back().nucleus()->cell(0).push_back(
1458                                         MathAtom(new InsetMathString(ref)));
1459                 }
1460
1461                 else if (t.cs() == "left") {
1462                         skipSpaces();
1463                         Token const & tl = getToken();
1464                         // \| and \Vert are equivalent, and InsetMathDelim
1465                         // can't handle \|
1466                         // FIXME: fix this in InsetMathDelim itself!
1467                         docstring const l = tl.cs() == "|" ? from_ascii("Vert") : tl.asString();
1468                         MathData ar;
1469                         parse(ar, FLAG_RIGHT, mode);
1470                         if (!good())
1471                                 break;
1472                         skipSpaces();
1473                         Token const & tr = getToken();
1474                         docstring const r = tr.cs() == "|" ? from_ascii("Vert") : tr.asString();
1475                         cell->push_back(MathAtom(new InsetMathDelim(buf, l, r, ar)));
1476                 }
1477
1478                 else if (t.cs() == "right") {
1479                         if (flags & FLAG_RIGHT)
1480                                 return success_;
1481                         //lyxerr << "got so far: '" << cell << "'" << endl;
1482                         error("Unmatched right delimiter");
1483                         return success_;
1484                 }
1485
1486                 else if (t.cs() == "begin") {
1487                         docstring const name = getArg('{', '}');
1488                         environments_.push_back(name);
1489
1490                         if (name == "array" || name == "subarray") {
1491                                 docstring const valign = parse_verbatim_option() + 'c';
1492                                 docstring const halign = parse_verbatim_item();
1493                                 cell->push_back(MathAtom(new InsetMathArray(buf, name,
1494                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1495                                 parse2(cell->back(), FLAG_END, mode, false);
1496                         }
1497
1498                         else if (name == "tabular") {
1499                                 docstring const valign = parse_verbatim_option() + 'c';
1500                                 docstring const halign = parse_verbatim_item();
1501                                 cell->push_back(MathAtom(new InsetMathTabular(buf, name,
1502                                         InsetMathGrid::guessColumns(halign), 1, (char)valign[0], halign)));
1503                                 parse2(cell->back(), FLAG_END, InsetMath::TEXT_MODE, false);
1504                         }
1505
1506                         else if (name == "split" || name == "cases") {
1507                                 cell->push_back(createInsetMath(name, buf));
1508                                 parse2(cell->back(), FLAG_END, mode, false);
1509                         }
1510
1511                         else if (name == "alignedat") {
1512                                 docstring const valign = parse_verbatim_option() + 'c';
1513                                 // ignore this for a while
1514                                 getArg('{', '}');
1515                                 cell->push_back(MathAtom(new InsetMathSplit(buf, name, (char)valign[0])));
1516                                 parse2(cell->back(), FLAG_END, mode, false);
1517                         }
1518
1519                         else if (name == "math") {
1520                                 cell->push_back(MathAtom(new InsetMathEnsureMath(buf)));
1521                                 parse(cell->back().nucleus()->cell(0), FLAG_END, InsetMath::MATH_MODE);
1522                         }
1523
1524                         else if (name == "equation" || name == "equation*"
1525                                         || name == "displaymath") {
1526                                 if (mode != InsetMath::UNDECIDED_MODE) {
1527                                         error("bad math environment");
1528                                         break;
1529                                 }
1530                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEquation)));
1531                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, (name == "equation"));
1532                         }
1533
1534                         else if (name == "eqnarray" || name == "eqnarray*") {
1535                                 if (mode != InsetMath::UNDECIDED_MODE) {
1536                                         error("bad math environment");
1537                                         break;
1538                                 }
1539                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullEqnArray)));
1540                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1541                         }
1542
1543                         else if (name == "align" || name == "align*") {
1544                                 if (mode != InsetMath::UNDECIDED_MODE) {
1545                                         error("bad math environment");
1546                                         break;
1547                                 }
1548                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlign)));
1549                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1550                         }
1551
1552                         else if (name == "flalign" || name == "flalign*") {
1553                                 if (mode != InsetMath::UNDECIDED_MODE) {
1554                                         error("bad math environment");
1555                                         break;
1556                                 }
1557                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullFlAlign)));
1558                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1559                         }
1560
1561                         else if (name == "alignat" || name == "alignat*") {
1562                                 if (mode != InsetMath::UNDECIDED_MODE) {
1563                                         error("bad math environment");
1564                                         break;
1565                                 }
1566                                 // ignore this for a while
1567                                 getArg('{', '}');
1568                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullAlignAt)));
1569                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1570                         }
1571
1572                         else if (name == "xalignat" || name == "xalignat*") {
1573                                 if (mode != InsetMath::UNDECIDED_MODE) {
1574                                         error("bad math environment");
1575                                         break;
1576                                 }
1577                                 // ignore this for a while
1578                                 getArg('{', '}');
1579                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXAlignAt)));
1580                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1581                         }
1582
1583                         else if (name == "xxalignat") {
1584                                 if (mode != InsetMath::UNDECIDED_MODE) {
1585                                         error("bad math environment");
1586                                         break;
1587                                 }
1588                                 // ignore this for a while
1589                                 getArg('{', '}');
1590                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullXXAlignAt)));
1591                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1592                         }
1593
1594                         else if (name == "multline" || name == "multline*") {
1595                                 if (mode != InsetMath::UNDECIDED_MODE) {
1596                                         error("bad math environment");
1597                                         break;
1598                                 }
1599                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullMultline)));
1600                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1601                         }
1602
1603                         else if (name == "gather" || name == "gather*") {
1604                                 if (mode != InsetMath::UNDECIDED_MODE) {
1605                                         error("bad math environment");
1606                                         break;
1607                                 }
1608                                 cell->push_back(MathAtom(new InsetMathHull(buf, hullGather)));
1609                                 parse2(cell->back(), FLAG_END, InsetMath::MATH_MODE, !stared(name));
1610                         }
1611
1612                         else if (latexkeys const * l = in_word_set(name)) {
1613                                 if (l->inset == "matrix") {
1614                                         cell->push_back(createInsetMath(name, buf));
1615                                         parse2(cell->back(), FLAG_END, mode, false);
1616                                 } else if (l->inset == "split") {
1617                                         docstring const valign = parse_verbatim_option() + 'c';
1618                                         cell->push_back(MathAtom(
1619                                                 new InsetMathSplit(buf, name, (char)valign[0])));
1620                                         parse2(cell->back(), FLAG_END, mode, false);
1621                                 } else {
1622                                         success_ = false;
1623                                         if (!(mode_ & Parse::QUIET)) {
1624                                                 dump();
1625                                                 lyxerr << "found math environment `"
1626                                                        << to_utf8(name)
1627                                                        << "' in symbols file with unsupported inset `"
1628                                                        << to_utf8(l->inset)
1629                                                        << "'." << endl;
1630                                         }
1631                                         // create generic environment inset
1632                                         cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1633                                         parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1634                                 }
1635                         }
1636
1637                         else {
1638                                 success_ = false;
1639                                 if (!(mode_ & Parse::QUIET)) {
1640                                         dump();
1641                                         lyxerr << "found unknown math environment '"
1642                                                << to_utf8(name) << "'" << endl;
1643                                 }
1644                                 // create generic environment inset
1645                                 cell->push_back(MathAtom(new InsetMathEnv(buf, name)));
1646                                 parse(cell->back().nucleus()->cell(0), FLAG_END, mode);
1647                         }
1648                 }
1649
1650                 else if (t.cs() == "kern") {
1651                         // FIXME: A hack...
1652                         docstring s;
1653                         int num_tokens = 0;
1654                         while (true) {
1655                                 Token const & t = getToken();
1656                                 ++num_tokens;
1657                                 if (!good()) {
1658                                         s.clear();
1659                                         while (num_tokens--)
1660                                                 putback();
1661                                         break;
1662                                 }
1663                                 s += t.character();
1664                                 if (isValidLength(to_utf8(s)))
1665                                         break;
1666                         }
1667                         if (s.empty())
1668                                 cell->push_back(MathAtom(new InsetMathKern));
1669                         else
1670                                 cell->push_back(MathAtom(new InsetMathKern(s)));
1671                 }
1672
1673                 else if (t.cs() == "label") {
1674                         // FIXME: This is swallowed in inline formulas
1675                         docstring label = parse_verbatim_item();
1676                         MathData ar;
1677                         asArray(label, ar);
1678                         if (grid.asHullInset()) {
1679                                 grid.asHullInset()->label(cellrow, label);
1680                         } else {
1681                                 cell->push_back(createInsetMath(t.cs(), buf));
1682                                 cell->push_back(MathAtom(new InsetMathBrace(ar)));
1683                         }
1684                 }
1685
1686                 else if (t.cs() == "choose" || t.cs() == "over"
1687                                 || t.cs() == "atop" || t.cs() == "brace"
1688                                 || t.cs() == "brack") {
1689                         MathAtom at = createInsetMath(t.cs(), buf);
1690                         at.nucleus()->cell(0) = *cell;
1691                         cell->clear();
1692                         parse(at.nucleus()->cell(1), flags, mode);
1693                         cell->push_back(at);
1694                         return success_;
1695                 }
1696
1697                 else if (t.cs() == "color") {
1698                         docstring const color = parse_verbatim_item();
1699                         cell->push_back(MathAtom(new InsetMathColor(buf, true, color)));
1700                         parse(cell->back().nucleus()->cell(0), flags, mode);
1701                         return success_;
1702                 }
1703
1704                 else if (t.cs() == "textcolor") {
1705                         docstring const color = parse_verbatim_item();
1706                         cell->push_back(MathAtom(new InsetMathColor(buf, false, color)));
1707                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1708                 }
1709
1710                 else if (t.cs() == "normalcolor") {
1711                         cell->push_back(createInsetMath(t.cs(), buf));
1712                         parse(cell->back().nucleus()->cell(0), flags, mode);
1713                         return success_;
1714                 }
1715
1716                 else if (t.cs() == "substack") {
1717                         cell->push_back(createInsetMath(t.cs(), buf));
1718                         parse2(cell->back(), FLAG_ITEM, mode, false);
1719                         // Delete empty last row if present
1720                         InsetMathGrid & subgrid =
1721                                 *(cell->back().nucleus()->asGridInset());
1722                         if (subgrid.nrows() > 1)
1723                                 delEmptyLastRow(subgrid);
1724                 }
1725
1726                 else if (t.cs() == "xymatrix") {
1727                         odocstringstream os;
1728                         while (good() && nextToken().cat() != catBegin)
1729                                 os << getToken().asInput();
1730                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1731                         parse2(cell->back(), FLAG_ITEM, mode, false);
1732                         // Delete empty last row if present
1733                         InsetMathGrid & subgrid =
1734                                 *(cell->back().nucleus()->asGridInset());
1735                         if (subgrid.nrows() > 1)
1736                                 delEmptyLastRow(subgrid);
1737                 }
1738
1739                 else if (t.cs() == "Diagram") {
1740                         odocstringstream os;
1741                         while (good() && nextToken().cat() != catBegin)
1742                                 os << getToken().asInput();
1743                         cell->push_back(createInsetMath(t.cs() + os.str(), buf));
1744                         parse2(cell->back(), FLAG_ITEM, mode, false);
1745                 }
1746
1747                 else if (t.cs() == "framebox" || t.cs() == "makebox") {
1748                         cell->push_back(createInsetMath(t.cs(), buf));
1749                         parse(cell->back().nucleus()->cell(0), FLAG_OPTION, InsetMath::TEXT_MODE);
1750                         parse(cell->back().nucleus()->cell(1), FLAG_OPTION, InsetMath::TEXT_MODE);
1751                         parse(cell->back().nucleus()->cell(2), FLAG_ITEM, InsetMath::TEXT_MODE);
1752                 }
1753
1754                 else if (t.cs() == "tag") {
1755                         if (nextToken().character() == '*') {
1756                                 getToken();
1757                                 cell->push_back(createInsetMath(t.cs() + '*', buf));
1758                         } else
1759                                 cell->push_back(createInsetMath(t.cs(), buf));
1760                         parse(cell->back().nucleus()->cell(0), FLAG_ITEM, InsetMath::TEXT_MODE);
1761                 }
1762
1763                 else if (t.cs() == "hspace") {
1764                         bool const prot =  nextToken().character() == '*';
1765                         if (prot)
1766                                 getToken();
1767                         docstring const name = t.cs();
1768                         docstring const arg = parse_verbatim_item();
1769                         Length length;
1770                         if (prot && arg == "\\fill")
1771                                 cell->push_back(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1772                         else if (isValidLength(to_utf8(arg), &length))
1773                                 cell->push_back(MathAtom(new InsetMathSpace(length, prot)));
1774                         else {
1775                                 // Since the Length class cannot use length variables
1776                                 // we must not create an InsetMathSpace.
1777                                 cell->push_back(MathAtom(new MathMacro(buf, name)));
1778                                 MathData ar;
1779                                 mathed_parse_cell(ar, '{' + arg + '}', mode_);
1780                                 cell->append(ar);
1781                         }
1782                 }
1783
1784 #if 0
1785                 else if (t.cs() == "infer") {
1786                         MathData ar;
1787                         parse(ar, FLAG_OPTION, mode);
1788                         cell->push_back(createInsetMath(t.cs(), buf));
1789                         parse2(cell->back(), FLAG_ITEM, mode, false);
1790                 }
1791
1792                 // Disabled
1793                 else if (1 && t.cs() == "ar") {
1794                         auto_ptr<InsetMathXYArrow> p(new InsetMathXYArrow);
1795                         // try to read target
1796                         parse(p->cell(0), FLAG_OTPTION, mode);
1797                         // try to read label
1798                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1799                                 p->up_ = nextToken().cat() == catSuper;
1800                                 getToken();
1801                                 parse(p->cell(1), FLAG_ITEM, mode);
1802                                 //lyxerr << "read label: " << p->cell(1) << endl;
1803                         }
1804
1805                         cell->push_back(MathAtom(p.release()));
1806                         //lyxerr << "read cell: " << cell << endl;
1807                 }
1808 #endif
1809
1810                 else if (t.cs() == "lyxmathsym") {
1811                         skipSpaces();
1812                         if (getToken().cat() != catBegin) {
1813                                 error("'{' expected in \\" + t.cs());
1814                                 return success_;
1815                         }
1816                         int count = 0;
1817                         docstring cmd;
1818                         CatCode cat = nextToken().cat();
1819                         while (good() && (count || cat != catEnd)) {
1820                                 if (cat == catBegin)
1821                                         ++count;
1822                                 else if (cat == catEnd)
1823                                         --count;
1824                                 cmd += getToken().asInput();
1825                                 cat = nextToken().cat();
1826                         }
1827                         if (getToken().cat() != catEnd) {
1828                                 error("'}' expected in \\" + t.cs());
1829                                 return success_;
1830                         }
1831                         bool termination;
1832                         docstring rem;
1833                         do {
1834                                 cmd = Encodings::fromLaTeXCommand(cmd,
1835                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
1836                                         termination, rem);
1837                                 for (size_t i = 0; i < cmd.size(); ++i)
1838                                         cell->push_back(MathAtom(new InsetMathChar(cmd[i])));
1839                                 if (!rem.empty()) {
1840                                         char_type c = rem[0];
1841                                         cell->push_back(MathAtom(new InsetMathChar(c)));
1842                                         cmd = rem.substr(1);
1843                                         rem.clear();
1844                                 } else
1845                                         cmd.clear();
1846                         } while (cmd.size());
1847                 }
1848
1849                 else if (t.cs().size()) {
1850                         bool const no_mhchem =
1851                                 (t.cs() == "ce" || t.cs() == "cf")
1852                                 && buf && buf->params().use_package("mhchem") ==
1853                                                 BufferParams::package_off;
1854
1855                         bool const is_user_macro = no_mhchem ||
1856                                 (buf && (mode_ & Parse::TRACKMACRO
1857                                          ? buf->usermacros.count(t.cs()) != 0
1858                                          : buf->getMacro(t.cs(), false) != 0));
1859
1860                         latexkeys const * l = in_word_set(t.cs());
1861                         if (l && !is_user_macro) {
1862                                 if (l->inset == "big") {
1863                                         skipSpaces();
1864                                         docstring const delim = getToken().asInput();
1865                                         if (InsetMathBig::isBigInsetDelim(delim))
1866                                                 cell->push_back(MathAtom(
1867                                                         new InsetMathBig(t.cs(), delim)));
1868                                         else {
1869                                                 cell->push_back(createInsetMath(t.cs(), buf));
1870                                                 putback();
1871                                         }
1872                                 }
1873
1874                                 else if (l->inset == "font") {
1875                                         cell->push_back(createInsetMath(t.cs(), buf));
1876                                         parse(cell->back().nucleus()->cell(0),
1877                                                 FLAG_ITEM, asMode(mode, l->extra));
1878                                 }
1879
1880                                 else if (l->inset == "oldfont") {
1881                                         cell->push_back(createInsetMath(t.cs(), buf));
1882                                         parse(cell->back().nucleus()->cell(0),
1883                                                 flags | FLAG_ALIGN, asMode(mode, l->extra));
1884                                         if (prevToken().cat() != catAlign &&
1885                                             prevToken().cs() != "\\")
1886                                                 return success_;
1887                                         putback();
1888                                 }
1889
1890                                 else if (l->inset == "style") {
1891                                         cell->push_back(createInsetMath(t.cs(), buf));
1892                                         parse(cell->back().nucleus()->cell(0),
1893                                                 flags | FLAG_ALIGN, mode);
1894                                         if (prevToken().cat() != catAlign &&
1895                                             prevToken().cs() != "\\")
1896                                                 return success_;
1897                                         putback();
1898                                 }
1899
1900                                 else {
1901                                         MathAtom at = createInsetMath(t.cs(), buf);
1902                                         for (InsetMath::idx_type i = 0; i < at->nargs(); ++i)
1903                                                 parse(at.nucleus()->cell(i),
1904                                                         FLAG_ITEM, asMode(mode, l->extra));
1905                                         cell->push_back(at);
1906                                 }
1907                         }
1908
1909                         else {
1910                                 bool is_unicode_symbol = false;
1911                                 if (mode == InsetMath::TEXT_MODE && !is_user_macro) {
1912                                         int num_tokens = 0;
1913                                         docstring cmd = prevToken().asInput();
1914                                         CatCode cat = nextToken().cat();
1915                                         if (cat == catBegin) {
1916                                                 int count = 0;
1917                                                 while (good() && (count || cat != catEnd)) {
1918                                                         cat = nextToken().cat();
1919                                                         cmd += getToken().asInput();
1920                                                         ++num_tokens;
1921                                                         if (cat == catBegin)
1922                                                                 ++count;
1923                                                         else if (cat == catEnd)
1924                                                                 --count;
1925                                                 }
1926                                         }
1927                                         bool is_combining;
1928                                         bool termination;
1929                                         char_type c = Encodings::fromLaTeXCommand(cmd,
1930                                                 Encodings::MATH_CMD | Encodings::TEXT_CMD,
1931                                                 is_combining, termination);
1932                                         if (is_combining) {
1933                                                 if (cat == catLetter)
1934                                                         cmd += '{';
1935                                                 cmd += getToken().asInput();
1936                                                 ++num_tokens;
1937                                                 if (cat == catLetter)
1938                                                         cmd += '}';
1939                                                 c = Encodings::fromLaTeXCommand(cmd,
1940                                                         Encodings::MATH_CMD | Encodings::TEXT_CMD,
1941                                                         is_combining, termination);
1942                                         }
1943                                         if (c) {
1944                                                 if (termination) {
1945                                                         if (nextToken().cat() == catBegin) {
1946                                                                 getToken();
1947                                                                 if (nextToken().cat() == catEnd) {
1948                                                                         getToken();
1949                                                                         num_tokens += 2;
1950                                                                 } else
1951                                                                         putback();
1952                                                         } else {
1953                                                                 while (nextToken().cat() == catSpace) {
1954                                                                         getToken();
1955                                                                         ++num_tokens;
1956                                                                 }
1957                                                         }
1958                                                 }
1959                                                 is_unicode_symbol = true;
1960                                                 cell->push_back(MathAtom(new InsetMathChar(c)));
1961                                         } else {
1962                                                 while (num_tokens--)
1963                                                         putback();
1964                                         }
1965                                 }
1966                                 if (!is_unicode_symbol) {
1967                                         MathAtom at = is_user_macro ?
1968                                                 MathAtom(new MathMacro(buf, t.cs()))
1969                                                 : createInsetMath(t.cs(), buf);
1970                                         InsetMath::mode_type m = mode;
1971                                         //if (m == InsetMath::UNDECIDED_MODE)
1972                                         //lyxerr << "default creation: m1: " << m << endl;
1973                                         if (at->currentMode() != InsetMath::UNDECIDED_MODE)
1974                                                 m = at->currentMode();
1975                                         //lyxerr << "default creation: m2: " << m << endl;
1976                                         InsetMath::idx_type start = 0;
1977                                         // this fails on \bigg[...\bigg]
1978                                         //MathData opt;
1979                                         //parse(opt, FLAG_OPTION, InsetMath::VERBATIM_MODE);
1980                                         //if (opt.size()) {
1981                                         //      start = 1;
1982                                         //      at.nucleus()->cell(0) = opt;
1983                                         //}
1984                                         for (InsetMath::idx_type i = start; i < at->nargs(); ++i) {
1985                                                 parse(at.nucleus()->cell(i), FLAG_ITEM, m);
1986                                                 skipSpaces();
1987                                         }
1988                                         cell->push_back(at);
1989                                 }
1990                         }
1991                 }
1992
1993
1994                 if (flags & FLAG_LEAVE) {
1995                         flags &= ~FLAG_LEAVE;
1996                         break;
1997                 }
1998         }
1999         return success_;
2000 }
2001
2002
2003
2004 } // anonymous namespace
2005
2006
2007 bool mathed_parse_cell(MathData & ar, docstring const & str, Parse::flags f)
2008 {
2009         return Parser(str, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2010                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2011 }
2012
2013
2014 bool mathed_parse_cell(MathData & ar, istream & is, Parse::flags f)
2015 {
2016         return Parser(is, f, ar.buffer()).parse(ar, 0, f & Parse::TEXTMODE ?
2017                                 InsetMath::TEXT_MODE : InsetMath::MATH_MODE);
2018 }
2019
2020
2021 bool mathed_parse_normal(Buffer * buf, MathAtom & t, docstring const & str,
2022                          Parse::flags f)
2023 {
2024         return Parser(str, f, buf).parse(t);
2025 }
2026
2027
2028 bool mathed_parse_normal(Buffer * buf, MathAtom & t, Lexer & lex,
2029                          Parse::flags f)
2030 {
2031         return Parser(lex, f, buf).parse(t);
2032 }
2033
2034
2035 bool mathed_parse_normal(InsetMathGrid & grid, docstring const & str,
2036                          Parse::flags f)
2037 {
2038         return Parser(str, f, &grid.buffer()).parse1(grid, 0, f & Parse::TEXTMODE ?
2039                         InsetMath::TEXT_MODE : InsetMath::MATH_MODE, false);
2040 }
2041
2042
2043 void initParser()
2044 {
2045         fill(theCatcode, theCatcode + 128, catOther);
2046         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
2047         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
2048
2049         theCatcode[int('\\')] = catEscape;
2050         theCatcode[int('{')]  = catBegin;
2051         theCatcode[int('}')]  = catEnd;
2052         theCatcode[int('$')]  = catMath;
2053         theCatcode[int('&')]  = catAlign;
2054         theCatcode[int('\n')] = catNewline;
2055         theCatcode[int('#')]  = catParameter;
2056         theCatcode[int('^')]  = catSuper;
2057         theCatcode[int('_')]  = catSub;
2058         theCatcode[int(0x7f)] = catIgnore;
2059         theCatcode[int(' ')]  = catSpace;
2060         theCatcode[int('\t')] = catSpace;
2061         theCatcode[int('\r')] = catNewline;
2062         theCatcode[int('~')]  = catActive;
2063         theCatcode[int('%')]  = catComment;
2064 }
2065
2066
2067 } // namespace lyx