]> git.lyx.org Git - lyx.git/blob - src/mathed/math_parser.C
another parser fix (nested {} and \left..\right and \atop)
[lyx.git] / src / mathed / math_parser.C
1 /*
2  *  File:        math_parser.C
3  *  Purpose:     Parser for mathed
4  *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx> 
5  *  Created:     January 1996
6  *  Description: Parse LaTeX2e math mode code.
7  *
8  *  Dependencies: Xlib, XForms
9  *
10  *  Copyright: 1996, Alejandro Aguilar Sierra
11  *
12  *   Version: 0.8beta.
13  *
14  *   You are free to use and modify this code under the terms of
15  *   the GNU General Public Licence version 2 or later.
16  */
17
18 #include <config.h>
19
20 #include <cctype>
21
22 #ifdef __GNUG__
23 #pragma implementation
24 #endif
25
26 #include "math_parser.h"
27 #include "array.h"
28 #include "math_inset.h"
29 #include "math_arrayinset.h"
30 #include "math_charinset.h"
31 #include "math_deliminset.h"
32 #include "math_factory.h"
33 #include "math_funcinset.h"
34 #include "math_kerninset.h"
35 #include "math_macro.h"
36 #include "math_macrotable.h"
37 #include "math_macrotemplate.h"
38 #include "math_matrixinset.h"
39 #include "math_rootinset.h"
40 #include "math_sqrtinset.h"
41 #include "math_scriptinset.h"
42 #include "math_specialcharinset.h"
43 #include "math_splitinset.h"
44 #include "math_sqrtinset.h"
45 #include "debug.h"
46 #include "support.h"
47 #include "lyxlex.h"
48 #include "support/lstrings.h"
49
50 using std::istream;
51 using std::ostream;
52 using std::ios;
53 using std::endl;
54
55
56 namespace {
57
58 bool stared(string const & s)
59 {
60         unsigned n = s.size();
61         return n && s[n - 1] == '*';
62 }
63
64
65
66 // These are TeX's catcodes
67 enum CatCode {
68         catEscape,     // 0    backslash 
69         catBegin,      // 1    {
70         catEnd,        // 2    }
71         catMath,       // 3    $
72         catAlign,      // 4    &
73         catNewline,    // 5    ^^M
74         catParameter,  // 6    #
75         catSuper,      // 7    ^
76         catSub,        // 8    _
77         catIgnore,     // 9       
78         catSpace,      // 10   space
79         catLetter,     // 11   a-zA-Z
80         catOther,      // 12   none of the above
81         catActive,     // 13   ~
82         catComment,    // 14   %
83         catInvalid     // 15   <delete>
84 };
85
86 CatCode theCatcode[256];  
87
88
89 inline CatCode catcode(unsigned char c)
90 {
91         return theCatcode[c];
92 }
93
94
95 enum {
96         FLAG_BRACE      = 1 << 0,  //  an opening brace needed
97         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing process
98         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
99         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
100         FLAG_BRACK_END  = 1 << 4,  //  next closing bracket ends the parsing process
101         FLAG_NEWLINE    = 1 << 6,  //  next \\\\ ends the parsing process
102         FLAG_ITEM       = 1 << 7,  //  read a (possibly braced token)
103         FLAG_BLOCK      = 1 << 8,  //  next block ends the parsing process
104         FLAG_LEAVE      = 1 << 9   //  leave the loop at the end
105 };
106
107
108 void catInit()
109 {
110         for (int i = 0; i <= 255; ++i) 
111                 theCatcode[i] = catOther;
112         for (int i = 'a'; i <= 'z'; ++i) 
113                 theCatcode[i] = catLetter;
114         for (int i = 'A'; i <= 'Z'; ++i) 
115                 theCatcode[i] = catLetter;
116
117         theCatcode['\\'] = catEscape;   
118         theCatcode['{']  = catBegin;    
119         theCatcode['}']  = catEnd;      
120         theCatcode['$']  = catMath;     
121         theCatcode['&']  = catAlign;    
122         theCatcode['\n'] = catNewline;  
123         theCatcode['#']  = catParameter;        
124         theCatcode['^']  = catSuper;    
125         theCatcode['_']  = catSub;      
126         theCatcode['\7f'] = catIgnore;    
127         theCatcode[' ']  = catSpace;    
128         theCatcode['\t'] = catSpace;    
129         theCatcode['\r'] = catSpace;    
130         theCatcode['~']  = catActive;   
131         theCatcode['%']  = catComment;  
132 }
133
134
135
136 //
137 // Helper class for parsing
138 //
139
140 class Token {
141 public:
142         ///
143         Token() : cs_(), char_(0), cat_(catIgnore) {}
144         ///
145         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
146         ///
147         Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
148
149         ///
150         string const & cs() const { return cs_; }
151         ///
152         CatCode cat() const { return cat_; }
153         ///
154         char character() const { return char_; }
155         ///
156         string asString() const;
157
158 private:        
159         ///
160         string cs_;
161         ///
162         char char_;
163         ///
164         CatCode cat_;
165 };
166
167 string Token::asString() const
168 {
169         return cs_.size() ? cs_ : string(1, char_);
170 }
171
172 bool operator==(Token const & s, Token const & t)
173 {
174         return s.character() == t.character()
175                 && s.cat() == t.cat() && s.cs() == t.cs(); 
176 }
177
178 bool operator!=(Token const & s, Token const & t)
179 {
180         return !(s == t);
181 }
182
183 ostream & operator<<(ostream & os, Token const & t)
184 {
185         if (t.cs().size())
186                 os << "\\" << t.cs();
187         else
188                 os << "[" << t.character() << "," << t.cat() << "]";
189         return os;
190 }
191
192
193 class Parser {
194
195 public:
196         ///
197         Parser(LyXLex & lex);
198         ///
199         Parser(istream & is);
200
201         ///
202         MathMacroTemplate * parse_macro();
203         ///
204         MathMatrixInset * parse_normal();
205         ///
206         void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
207         ///
208         int lineno() const { return lineno_; }
209         ///
210         void putback();
211
212 private:
213         ///
214         string getArg(char lf, char rf);
215         ///
216         char getChar();
217         ///
218         void error(string const & msg);
219         ///
220         void parse_lines(MathGridInset * p, bool numbered, bool outmost);
221         ///
222         latexkeys const * read_delim();
223
224 private:
225         ///
226         void tokenize(istream & is);
227         ///
228         void tokenize(string const & s);
229         ///
230         void push_back(Token const & t);
231         ///
232         void pop_back();
233         ///
234         Token const & prevToken() const;
235         ///
236         Token const & nextToken() const;
237         ///
238         Token const & getToken();
239         ///
240         void lex(string const & s);
241         ///
242         bool good() const;
243
244         ///
245         int lineno_;
246         ///
247         std::vector<Token> tokens_;
248         ///
249         unsigned pos_;
250         ///
251         bool   curr_num_;
252         ///
253         string curr_label_;
254         ///
255         string curr_skip_;
256 };
257
258
259 Parser::Parser(LyXLex & lexer)
260         : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
261 {
262         tokenize(lexer.getStream());
263         lexer.eatLine();
264 }
265
266
267 Parser::Parser(istream & is)
268         : lineno_(0), pos_(0), curr_num_(false)
269 {
270         tokenize(is);
271 }
272
273
274 void Parser::push_back(Token const & t)
275 {
276         tokens_.push_back(t);
277 }
278
279
280 void Parser::pop_back()
281 {
282         tokens_.pop_back();
283 }
284
285
286 Token const & Parser::prevToken() const
287 {
288         static const Token dummy;
289         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
290 }
291
292
293 Token const & Parser::nextToken() const
294 {
295         static const Token dummy;
296         return good() ? tokens_[pos_] : dummy;
297 }
298
299
300 Token const & Parser::getToken()
301 {
302         static const Token dummy;
303         return good() ? tokens_[pos_++] : dummy;
304 }
305
306
307 void Parser::putback()
308 {
309         --pos_;
310 }
311
312
313 bool Parser::good() const
314 {
315         return pos_ < tokens_.size();
316 }
317
318
319 char Parser::getChar()
320 {
321         if (!good())
322                 lyxerr << "The input stream is not well..." << endl;
323         return tokens_[pos_++].character();
324 }
325
326
327 string Parser::getArg(char lf, char rg)
328 {
329         string result;
330         char c = getChar();
331
332         if (c != lf)  
333                 putback();
334         else 
335                 while ((c = getChar()) != rg && good())
336                         result += c;
337
338         return result;
339 }
340
341
342 void Parser::tokenize(istream & is)
343 {
344         // eat everything up to the next \end_inset or end of stream
345         // and store it in s for further tokenization
346         string s;
347         char c;
348         while (is.get(c)) {
349                 s += c;
350                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
351                         s = s.substr(0, s.size() - 10);
352                         break;
353                 }
354         }
355
356         // tokenize buffer
357         tokenize(s);
358 }
359
360
361 void Parser::tokenize(string const & buffer)
362 {
363         static bool init_done = false;
364         
365         if (!init_done) {
366                 catInit();
367                 init_done = true;
368         }
369
370         istringstream is(buffer.c_str(), ios::in | ios::binary);
371
372         char c;
373         while (is.get(c)) {
374
375                 switch (catcode(c)) {
376                         case catNewline: {
377                                 ++lineno_; 
378                                 is.get(c);
379                                 if (catcode(c) == catNewline)
380                                         ; //push_back(Token("par"));
381                                 else {
382                                         push_back(Token(' ', catSpace));
383                                         is.putback(c);  
384                                 }
385                                 break;
386                         }
387
388                         case catComment: {
389                                 while (is.get(c) && catcode(c) != catNewline)
390                                         ;
391                                 ++lineno_; 
392                                 break;
393                         }
394
395                         case catEscape: {
396                                 is.get(c);
397                                 string s(1, c);
398                                 if (catcode(c) == catLetter) {
399                                         while (is.get(c) && catcode(c) == catLetter)
400                                                 s += c;
401                                         if (catcode(c) == catSpace)
402                                                 while (is.get(c) && catcode(c) == catSpace)
403                                                         ;
404                                         is.putback(c);
405                                 }       
406                                 push_back(Token(s));
407                                 break;
408                         }
409
410                         default:
411                                 push_back(Token(c, catcode(c)));
412                 }
413         }
414
415 #if 0
416         lyxerr << "\nTokens: ";
417         for (unsigned i = 0; i < tokens_.size(); ++i)
418                 lyxerr << tokens_[i];
419         lyxerr << "\n";
420 #endif
421 }
422
423
424 void Parser::error(string const & msg) 
425 {
426         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
427         //exit(1);
428 }
429
430
431 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
432 {
433         const int cols = p->ncols();
434
435         // save global variables
436         bool   const saved_num   = curr_num_;
437         string const saved_label = curr_label_;
438
439         for (int row = 0; true; ++row) {
440                 // reset global variables
441                 curr_num_   = numbered;
442                 curr_label_.erase();
443
444                 // reading a row
445                 for (int col = 0; col < cols; ++col) {
446                         //lyxerr << "reading cell " << row << " " << col << "\n";
447                         parse_into(p->cell(col + row * cols), FLAG_BLOCK);
448
449                         // no ampersand
450                         if (prevToken().cat() != catAlign) {
451                                 //lyxerr << "less cells read than normal in row/col: "
452                                 //      << row << " " << col << "\n";
453                                 break;
454                         }
455                 }
456
457                 if (outmost) {
458                         MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
459                         m->numbered(row, curr_num_);
460                         m->label(row, curr_label_);
461                         if (curr_skip_.size()) {
462                                 m->vskip(LyXLength(curr_skip_), row);
463                                 curr_skip_.erase();
464                         }
465                 }
466
467                 // no newline?
468                 if (prevToken() != Token("\\")) {
469                         //lyxerr << "no newline here\n";
470                         break;
471                 }
472
473                 p->appendRow();
474         }
475
476         // restore "global" variables
477         curr_num_   = saved_num;
478         curr_label_ = saved_label;
479 }
480
481
482 MathMacroTemplate * Parser::parse_macro()
483 {
484         while (nextToken().cat() == catSpace)
485                 getToken();
486
487         if (getToken().cs() != "newcommand") {
488                 lyxerr << "\\newcommand expected\n";
489                 return 0;
490         }
491
492         if (getToken().cat() != catBegin) {
493                 lyxerr << "'{' expected\n";
494                 return 0;
495         }
496
497         string name = getToken().cs();
498
499         if (getToken().cat() != catEnd) {
500                 lyxerr << "'}' expected\n";
501                 return 0;
502         }
503
504         string arg  = getArg('[', ']');
505         int    narg = arg.empty() ? 0 : atoi(arg.c_str()); 
506         //lyxerr << "creating macro " << name << " with " << narg <<  "args\n";
507         MathMacroTemplate * p = new MathMacroTemplate(name, narg);
508         parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
509         return p;
510 }
511
512
513 MathMatrixInset * Parser::parse_normal()
514 {
515         while (nextToken().cat() == catSpace)
516                 getToken();
517
518         Token const & t = getToken();
519
520         if (t.cat() == catMath || t.cs() == "(") {
521                 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
522                 parse_into(p->cell(0), 0);
523                 return p;
524         }
525
526         if (!t.cs().size()) {
527                 lyxerr << "start of math expected, got '" << t << "'\n";
528                 return 0;
529         }
530
531         string const & cs = t.cs();
532
533         if (cs == "[") {
534                 curr_num_ = 0;
535                 curr_label_.erase();
536                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
537                 parse_into(p->cell(0), 0);
538                 p->numbered(0, curr_num_);
539                 p->label(0, curr_label_);
540                 return p;
541         }
542
543         if (cs != "begin") {
544                 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
545                 return 0;
546         }
547
548         string const name = getArg('{', '}');
549
550         if (name == "equation" || name == "equation*") {
551                 curr_num_ = !stared(name);
552                 curr_label_.erase();
553                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
554                 parse_into(p->cell(0), FLAG_END);
555                 p->numbered(0, curr_num_);
556                 p->label(0, curr_label_);
557                 return p;
558         }
559
560         if (name == "eqnarray" || name == "eqnarray*") {
561                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
562                 parse_lines(p, !stared(name), true);
563                 return p;
564         }
565
566         if (name == "align" || name == "align*") {
567                 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
568                 parse_lines(p, !stared(name), true);
569                 return p;
570         }
571
572         if (name == "alignat" || name == "alignat*") {
573                 MathMatrixInset * p =
574                         new MathMatrixInset(LM_OT_ALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
575                 parse_lines(p, !stared(name), true);
576                 return p;
577         }
578
579         if (name == "xalignat" || name == "xalignat*") {
580                 MathMatrixInset * p =
581                         new MathMatrixInset(LM_OT_XALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
582                 parse_lines(p, !stared(name), true);
583                 return p;
584         }
585
586         if (name == "xxalignat") {
587                 MathMatrixInset * p =
588                         new MathMatrixInset(LM_OT_XXALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
589                 parse_lines(p, !stared(name), true);
590                 return p;
591         }
592
593         if (name == "multline" || name == "multline*") {
594                 MathMatrixInset * p = new MathMatrixInset(LM_OT_MULTLINE);
595                 parse_lines(p, !stared(name), true);
596                 return p;
597         }
598
599         if (name == "gather" || name == "gather*") {
600                 MathMatrixInset * p = new MathMatrixInset(LM_OT_GATHER);
601                 parse_lines(p, !stared(name), true);
602                 return p;
603         }
604
605         lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
606         return 0;
607 }
608
609
610 latexkeys const * Parser::read_delim()
611 {
612         Token const & t = getToken();
613         latexkeys const * l = in_word_set(t.asString());
614         return l ? l : in_word_set(".");
615 }
616
617
618 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
619 {
620         MathTextCodes yyvarcode = LM_TC_MIN;
621
622         bool panic  = false;
623
624         while (good()) {
625                 Token const & t = getToken();
626         
627                 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
628                 //array.dump(lyxerr);
629                 //lyxerr << "\n";
630
631                 if (flags & FLAG_ITEM) {
632                         flags &= ~FLAG_ITEM;
633                         if (t.cat() == catBegin) { 
634                                 // skip the brace and collect everything to the next matching
635                                 // closing brace
636                                 flags |= FLAG_BRACE_LAST;
637                                 continue;
638                         } else {
639                                 // handle only this single token, leave the loop if done
640                                 flags |= FLAG_LEAVE;
641                         }
642                 }
643
644                 if (flags & FLAG_BRACE) {
645                         if (t.cat() != catBegin) {
646                                 error("Expected {. Maybe you forgot to enclose an argument in {}");
647                                 panic = true;
648                                 break;
649                         } else {
650                                 flags &= ~FLAG_BRACE;
651                                 continue;
652                         }
653                 }
654
655                 if (flags & FLAG_BLOCK) {
656                         if (t.cat() == catAlign || t.cs() == "\\")
657                                 return;
658                         if (t.cs() == "end") {
659                                 getArg('{', '}');
660                                 return;
661                         }
662                 }
663
664                 //
665                 // cat codes
666                 //
667                 if (t.cat() == catMath)
668                         break;
669
670                 else if (t.cat() == catLetter)
671                         array.push_back(new MathCharInset(t.character(), yyvarcode));
672
673                 else if (t.cat() == catSpace &&
674                                 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
675                         array.push_back(new MathCharInset(' ', yyvarcode));
676
677                 else if (t.cat() == catParameter) {
678                         Token const & n = getToken();
679                         MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
680                         array.push_back(p);
681                 }
682
683                 else if (t.cat() == catBegin) {
684                         array.push_back(new MathCharInset('{', LM_TC_TEX));
685                 }
686
687                 else if (t.cat() == catEnd) {
688                         if (flags & FLAG_BRACE_LAST)
689                                 return;
690                         array.push_back(new MathCharInset('}', LM_TC_TEX));
691                 }
692                 
693                 else if (t.cat() == catAlign) {
694                         lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
695                         array.push_back(new MathCharInset('&', LM_TC_TEX));
696                 }
697                 
698                 else if (t.cat() == catSuper || t.cat() == catSub) {
699                         bool up = (t.cat() == catSuper);
700                         if (array.empty())
701                                 array.push_back(new MathCharInset(' '));
702                         parse_into(array.back().ensure(up)->cell(0), FLAG_ITEM);
703                 }
704
705                 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
706                         return;
707
708                 else if (t.cat() == catOther)
709                         array.push_back(new MathCharInset(t.character(), yyvarcode));
710                 
711                 //
712                 // codesequences
713                 //      
714                 else if (t.cs() == "protect") 
715                         ;
716
717                 else if (t.cs() == "end")
718                         break;
719
720                 else if (t.cs() == ")")
721                         break;
722
723                 else if (t.cs() == "]")
724                         break;
725
726                 else if (t.cs() == "\\") {
727                         curr_skip_ = getArg('[', ']');
728                         if (flags & FLAG_NEWLINE)
729                                 return;
730                         lyxerr[Debug::MATHED]
731                                         << "found newline unexpectedly, array: '" << array << "'\n";
732                         array.push_back(createMathInset("\\"));
733                 }
734         
735                 else if (t.cs() == "limits" && array.size())
736                         array.back().limits(1);
737                 
738                 else if (t.cs() == "nolimits" && array.size())
739                         array.back().limits(-1);
740                 
741                 else if (t.cs() == "nonumber")
742                         curr_num_ = false;
743
744                 else if (t.cs() == "number")
745                         curr_num_ = true;
746
747                 else if (t.cs() == "sqrt") {
748                         char c = getChar();
749                         if (c == '[') {
750                                 array.push_back(new MathRootInset);
751                                 parse_into(array.back().nucleus()->cell(0), FLAG_BRACK_END);
752                                 parse_into(array.back().nucleus()->cell(1), FLAG_ITEM);
753                         } else {
754                                 putback();
755                                 array.push_back(new MathSqrtInset);
756                                 parse_into(array.back().nucleus()->cell(0), FLAG_ITEM);
757                         }
758                 }
759                 
760                 else if (t.cs() == "left") {
761                         latexkeys const * l = read_delim();
762                         MathArray ar;
763                         parse_into(ar, FLAG_RIGHT);
764                         latexkeys const * r = read_delim();
765                         MathDelimInset * dl = new MathDelimInset(l, r);
766                         dl->cell(0) = ar;
767                         array.push_back(dl);
768                 }
769                 
770                 else if (t.cs() == "right") {
771                         if (!(flags & FLAG_RIGHT)) {
772                                 lyxerr << "got so far: '" << array << "'\n";
773                                 error("Unmatched right delimiter");
774                         }
775                         return;
776                 }
777
778 /*              
779                 case LM_TK_STY:
780                 {
781                         lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
782                         //MathArray tmp = array;
783                         //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
784                         //array.push_back(p);
785                         //parse_into(p->cell(0), FLAG_BRACE_FONT);
786                         break; 
787                 }
788
789                 else  LM_TK_SPECIAL:
790                         array.push_back(new MathCharInset(ival_, LM_TC_TEX));
791                         break;
792 */
793                 
794                 else if (t.cs() == "begin") {
795                         string const name = getArg('{', '}');   
796                         if (name == "array") {
797                                 string const valign = getArg('[', ']') + 'c';
798                                 string const halign = getArg('{', '}');
799                                 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
800                                 m->valign(valign[0]);
801                                 m->halign(halign);
802                                 parse_lines(m, false, false);
803                                 array.push_back(m);
804                         } else if (name == "split") {
805                                 MathSplitInset * m = new MathSplitInset(1);
806                                 parse_lines(m, false, false);
807                                 array.push_back(m);
808                         } else 
809                                 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";  
810                 }
811         
812                 else if (t.cs() == "kern") {
813 #ifdef WITH_WARNINGS
814 #warning A hack...
815 #endif
816                         string s;
817                         while (1) {
818                                 Token const & t = getToken();
819                                 if (!good()) {
820                                         putback();      
821                                         break;
822                                 }
823                                 s += t.character();
824                                 if (isValidLength(s))
825                                         break;
826                         }
827                         array.push_back(new MathKernInset(s));
828                 }
829
830                 else if (t.cs() == "label") {
831                         //MathArray ar;
832                         //parse_into(ar, FLAG_ITEM);
833                         //ostringstream os;
834                         //ar.write(os, true);
835                         //curr_label_ = os.str();
836                         // was: 
837                         curr_label_ = getArg('{', '}');
838                 }
839
840                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
841                         MathInset * p = createMathInset(t.cs());
842                         // search backward for position of last '{' if any
843                         int pos;
844                         for (pos = array.size() - 1; pos >= 0; --pos)
845                                 if (array.at(pos)->nucleus()->getChar() == '{')
846                                         break;
847                         if (pos >= 0) {
848                                 // found it -> use the part after '{' as "numerator"
849                                 p->cell(0) = MathArray(array, pos + 1, array.size());
850                                 parse_into(p->cell(1), FLAG_BRACE_LAST);
851                                 // delete denominator and the '{'
852                                 array.erase(pos, array.size());
853                         } else if (flags & FLAG_RIGHT) {
854                                 // we are inside a \left ... \right block
855                                 //lyxerr << "found '" << t.cs() << "' enclosed by \\left .. \\right\n";
856                                 p->cell(0).swap(array);
857                                 parse_into(p->cell(1), FLAG_RIGHT);
858                                 // handle the right delimiter properly
859                                 putback();
860                         } else {
861                                 // not found -> use everything as "numerator"
862                                 p->cell(0).swap(array);
863                                 parse_into(p->cell(1), FLAG_BLOCK);
864                         }
865                         array.push_back(p);
866                 }
867         
868                 else if (t.cs().size()) {
869                         latexkeys const * l = in_word_set(t.cs());
870                         if (l) {
871                                 if (l->token == LM_TK_FONT) {
872                                         //lyxerr << "starting font\n";
873                                         //CatCode catSpaceSave = theCatcode[' '];
874                                         //if (l->id == LM_TC_TEXTRM) {
875                                         //      // temporarily change catcode   
876                                         //      theCatcode[' '] = catLetter;    
877                                         //}
878
879                                         MathTextCodes t = static_cast<MathTextCodes>(l->id);
880                                         MathArray ar;
881                                         parse_into(ar, FLAG_ITEM, t);
882                                         for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
883                                                 it->nucleus()->handleFont(t);
884                                         array.push_back(ar);
885
886                                         // undo catcode changes
887                                         ////theCatcode[' '] = catSpaceSave;
888                                         //lyxerr << "ending font\n";
889                                 }
890
891                                 else if (l->token == LM_TK_OLDFONT)
892                                         yyvarcode = static_cast<MathTextCodes>(l->id);
893
894                                 else {
895                                         MathInset * p = createMathInset(t.cs());
896                                         for (int i = 0; i < p->nargs(); ++i) 
897                                                 parse_into(p->cell(i), FLAG_ITEM);
898                                         array.push_back(p);
899                                 }
900                         }
901
902                         else {
903                                 MathInset * p = createMathInset(t.cs());
904                                 if (p) {
905                                         for (int i = 0; i < p->nargs(); ++i)
906                                                 parse_into(p->cell(i), FLAG_ITEM);
907                                         array.push_back(p);
908                                 } else {
909                                         error("Unrecognized token");
910                                         //lyxerr[Debug::MATHED] << "[" << t << "]\n";
911                                         lyxerr << t << "\n";
912                                 }       
913                         }
914                 }
915
916
917                 if (flags & FLAG_LEAVE) {
918                         flags &= ~FLAG_LEAVE;
919                         break;
920                 }
921         }
922
923         if (panic) {
924                 lyxerr << " Math Panic, expect problems!\n";
925                 //   Search for the end command. 
926                 Token t;
927                 do {
928                         t = getToken();
929                 } while (good() && t.cs() != "end");
930         }
931 }
932
933 } // anonymous namespace
934
935
936
937 MathArray mathed_parse_cell(string const & str)
938 {
939         istringstream is(str.c_str());
940         Parser parser(is);
941         MathArray ar;
942         parser.parse_into(ar, 0);
943         return ar;
944 }
945
946
947
948 MathMacroTemplate * mathed_parse_macro(string const & str)
949 {
950         istringstream is(str.c_str());
951         Parser parser(is);
952         return parser.parse_macro();
953 }
954
955 MathMacroTemplate * mathed_parse_macro(istream & is)
956 {
957         Parser parser(is);
958         return parser.parse_macro();
959 }
960
961 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
962 {
963         Parser parser(lex);
964         return parser.parse_macro();
965 }
966
967
968
969 MathMatrixInset * mathed_parse_normal(string const & str)
970 {
971         istringstream is(str.c_str());
972         Parser parser(is);
973         return parser.parse_normal();
974 }
975
976 MathMatrixInset * mathed_parse_normal(istream & is)
977 {
978         Parser parser(is);
979         return parser.parse_normal();
980 }
981
982 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
983 {
984         Parser parser(lex);
985         return parser.parse_normal();
986 }