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