]> git.lyx.org Git - lyx.git/blob - src/mathed/math_parser.C
re-enable { and } in seperate cells;
[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_sqrtinset.h"
43 #include "debug.h"
44 #include "support.h"
45 #include "lyxlex.h"
46 #include "support/lstrings.h"
47
48 using std::istream;
49 using std::ostream;
50 using std::ios;
51 using std::endl;
52
53
54 namespace {
55
56 bool stared(string const & s)
57 {
58         unsigned n = s.size();
59         return n && s[n - 1] == '*';
60 }
61
62 MathScriptInset * prevScriptInset(MathArray const & array)
63 {
64         MathInset * p = array.back();
65         return (p && p->isScriptInset()) ? static_cast<MathScriptInset *>(p) : 0;
66 }
67
68
69 MathInset * lastScriptInset(MathArray & array, bool up, int limits)
70 {
71         MathScriptInset * p = prevScriptInset(array);
72         if (!p) {
73                 MathInset * b = array.back();
74                 if (b && b->isScriptable()) {
75                         p = new MathScriptInset(up, !up, b->clone());
76                         array.pop_back();       
77                 } else {
78                         p = new MathScriptInset(up, !up);
79                 }
80                 array.push_back(p);
81         }
82         if (up)
83                 p->up(true);
84         else
85                 p->down(true);
86         if (limits)
87                 p->limits(limits);
88         return p;
89 }
90
91
92 // These are TeX's catcodes
93 enum CatCode {
94         catEscape,     // 0    backslash 
95         catBegin,      // 1    {
96         catEnd,        // 2    }
97         catMath,       // 3    $
98         catAlign,      // 4    &
99         catNewline,    // 5    ^^M
100         catParameter,  // 6    #
101         catSuper,      // 7    ^
102         catSub,        // 8    _
103         catIgnore,     // 9       
104         catSpace,      // 10   space
105         catLetter,     // 11   a-zA-Z
106         catOther,      // 12   none of the above
107         catActive,     // 13   ~
108         catComment,    // 14   %
109         catInvalid     // 15   <delete>
110 };
111
112 CatCode theCatcode[256];  
113
114
115 inline CatCode catcode(unsigned char c)
116 {
117         return theCatcode[c];
118 }
119
120
121 enum {
122         FLAG_BRACE      = 1 << 0,  //  an opening brace needed
123         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing process
124         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
125         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
126         FLAG_BRACK_END  = 1 << 4,  //  next closing bracket ends the parsing process
127         FLAG_NEWLINE    = 1 << 6,  //  next \\\\ ends the parsing process
128         FLAG_ITEM       = 1 << 7,  //  read a (possibly braced token)
129         FLAG_BLOCK      = 1 << 8,  //  next block ends the parsing process
130         FLAG_LEAVE      = 1 << 9   //  leave the loop at the end
131 };
132
133
134 void catInit()
135 {
136         for (int i = 0; i <= 255; ++i) 
137                 theCatcode[i] = catOther;
138         for (int i = 'a'; i <= 'z'; ++i) 
139                 theCatcode[i] = catLetter;
140         for (int i = 'A'; i <= 'Z'; ++i) 
141                 theCatcode[i] = catLetter;
142
143         theCatcode['\\'] = catEscape;   
144         theCatcode['{']  = catBegin;    
145         theCatcode['}']  = catEnd;      
146         theCatcode['$']  = catMath;     
147         theCatcode['&']  = catAlign;    
148         theCatcode['\n'] = catNewline;  
149         theCatcode['#']  = catParameter;        
150         theCatcode['^']  = catSuper;    
151         theCatcode['_']  = catSub;      
152         theCatcode['\7f'] = catIgnore;    
153         theCatcode[' ']  = catSpace;    
154         theCatcode['\t'] = catSpace;    
155         theCatcode['\r'] = catSpace;    
156         theCatcode['~']  = catActive;   
157         theCatcode['%']  = catComment;  
158 }
159
160
161
162 //
163 // Helper class for parsing
164 //
165
166 class Token {
167 public:
168         ///
169         Token() : cs_(), char_(0), cat_(catIgnore) {}
170         ///
171         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
172         ///
173         Token(const string & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
174
175         ///
176         string const & cs() const { return cs_; }
177         ///
178         CatCode cat() const { return cat_; }
179         ///
180         char character() const { return char_; }
181         ///
182         string asString() const;
183
184 private:        
185         ///
186         string cs_;
187         ///
188         char char_;
189         ///
190         CatCode cat_;
191 };
192
193 string Token::asString() const
194 {
195         return cs_.size() ? cs_ : string(1, char_);
196 }
197
198 bool operator==(Token const & s, Token const & t)
199 {
200         return s.character() == t.character()
201                 && s.cat() == t.cat() && s.cs() == t.cs(); 
202 }
203
204 bool operator!=(Token const & s, Token const & t)
205 {
206         return !(s == t);
207 }
208
209 ostream & operator<<(ostream & os, Token const & t)
210 {
211         if (t.cs().size())
212                 os << "\\" << t.cs();
213         else
214                 os << "[" << t.character() << "," << t.cat() << "]";
215         return os;
216 }
217
218
219 class Parser {
220
221 public:
222         ///
223         Parser(LyXLex & lex);
224         ///
225         Parser(istream & is);
226
227         ///
228         MathMacroTemplate * parse_macro();
229         ///
230         MathMatrixInset * parse_normal();
231         ///
232         void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
233         ///
234         int lineno() const { return lineno_; }
235         ///
236         void putback();
237
238 private:
239         ///
240         string getArg(char lf, char rf);
241         ///
242         char getChar();
243         ///
244         void error(string const & msg);
245         ///
246         void parse_lines(MathGridInset * p, bool numbered, bool outmost);
247         ///
248         latexkeys const * read_delim();
249
250 private:
251         ///
252         void tokenize(istream & is);
253         ///
254         void tokenize(string const & s);
255         ///
256         void push_back(Token const & t);
257         ///
258         void pop_back();
259         ///
260         Token const & prevToken() const;
261         ///
262         Token const & nextToken() const;
263         ///
264         Token const & getToken();
265         ///
266         void lex(string const & s);
267         ///
268         bool good() const;
269
270         ///
271         int lineno_;
272         ///
273         std::vector<Token> tokens_;
274         ///
275         unsigned pos_;
276         ///
277         bool   curr_num_;
278         ///
279         string curr_label_;
280         ///
281         string curr_skip_;
282 };
283
284
285 Parser::Parser(LyXLex & lexer)
286         : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
287 {
288         tokenize(lexer.getStream());
289         lexer.eatLine();
290 }
291
292
293 Parser::Parser(istream & is)
294         : lineno_(0), pos_(0), curr_num_(false)
295 {
296         tokenize(is);
297 }
298
299
300 void Parser::push_back(Token const & t)
301 {
302         tokens_.push_back(t);
303 }
304
305
306 void Parser::pop_back()
307 {
308         tokens_.pop_back();
309 }
310
311
312 Token const & Parser::prevToken() const
313 {
314         static const Token dummy;
315         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
316 }
317
318
319 Token const & Parser::nextToken() const
320 {
321         static const Token dummy;
322         return good() ? tokens_[pos_] : dummy;
323 }
324
325
326 Token const & Parser::getToken()
327 {
328         static const Token dummy;
329         return good() ? tokens_[pos_++] : dummy;
330 }
331
332
333 void Parser::putback()
334 {
335         --pos_;
336 }
337
338
339 bool Parser::good() const
340 {
341         return pos_ < tokens_.size();
342 }
343
344
345 char Parser::getChar()
346 {
347         if (!good())
348                 lyxerr << "The input stream is not well..." << endl;
349         return tokens_[pos_++].character();
350 }
351
352
353 string Parser::getArg(char lf, char rg)
354 {
355         string result;
356         char c = getChar();
357
358         if (c != lf)  
359                 putback();
360         else 
361                 while ((c = getChar()) != rg && good())
362                         result += c;
363
364         return result;
365 }
366
367
368 void Parser::tokenize(istream & is)
369 {
370         // eat everything up to the next \end_inset or end of stream
371         // and store it in s for further tokenization
372         string s;
373         char c;
374         while (is.get(c)) {
375                 s += c;
376                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
377                         s = s.substr(0, s.size() - 10);
378                         break;
379                 }
380         }
381
382         // tokenize buffer
383         tokenize(s);
384 }
385
386
387 void Parser::tokenize(string const & buffer)
388 {
389         static bool init_done = false;
390         
391         if (!init_done) {
392                 catInit();
393                 init_done = true;
394         }
395
396         istringstream is(buffer, ios::in | ios::binary);
397
398         char c;
399         while (is.get(c)) {
400
401                 switch (catcode(c)) {
402                         case catNewline: {
403                                 ++lineno_; 
404                                 is.get(c);
405                                 if (catcode(c) == catNewline)
406                                         ; //push_back(Token("par"));
407                                 else {
408                                         push_back(Token(' ', catSpace));
409                                         is.putback(c);  
410                                 }
411                                 break;
412                         }
413
414                         case catComment: {
415                                 while (is.get(c) && catcode(c) != catNewline)
416                                         ;
417                                 ++lineno_; 
418                                 break;
419                         }
420
421                         case catEscape: {
422                                 is.get(c);
423                                 string s(1, c);
424                                 if (catcode(c) == catLetter) {
425                                         while (is.get(c) && catcode(c) == catLetter)
426                                                 s += c;
427                                         if (catcode(c) == catSpace)
428                                                 while (is.get(c) && catcode(c) == catSpace)
429                                                         ;
430                                         is.putback(c);
431                                 }       
432                                 push_back(Token(s));
433                                 break;
434                         }
435
436                         default:
437                                 push_back(Token(c, catcode(c)));
438                 }
439         }
440
441 #if 1
442         lyxerr << "\nTokens: ";
443         for (unsigned i = 0; i < tokens_.size(); ++i)
444                 lyxerr << tokens_[i];
445         lyxerr << "\n";
446 #endif
447 }
448
449
450 void Parser::error(string const & msg) 
451 {
452         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
453 }
454
455
456 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
457 {
458         const int cols = p->ncols();
459
460         // save global variables
461         bool   const saved_num   = curr_num_;
462         string const saved_label = curr_label_;
463
464         for (int row = 0; true; ++row) {
465                 // reset global variables
466                 curr_num_   = numbered;
467                 curr_label_.erase();
468
469                 // reading a row
470                 for (int col = 0; col < cols; ++col) {
471                         //lyxerr << "reading cell " << row << " " << col << "\n";
472                         parse_into(p->cell(col + row * cols), FLAG_BLOCK);
473
474                         // no ampersand
475                         if (prevToken().cat() != catAlign) {
476                                 //lyxerr << "less cells read than normal in row/col: "
477                                 //      << row << " " << col << "\n";
478                                 break;
479                         }
480                 }
481
482                 if (outmost) {
483                         MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
484                         m->numbered(row, curr_num_);
485                         m->label(row, curr_label_);
486                         if (curr_skip_.size()) {
487                                 m->vskip(LyXLength(curr_skip_), row);
488                                 curr_skip_.erase();
489                         }
490                 }
491
492                 // no newline?
493                 if (prevToken() != Token("\\")) {
494                         //lyxerr << "no newline here\n";
495                         break;
496                 }
497
498                 p->appendRow();
499         }
500
501         // restore "global" variables
502         curr_num_   = saved_num;
503         curr_label_ = saved_label;
504 }
505
506
507 MathMacroTemplate * Parser::parse_macro()
508 {
509         while (nextToken().cat() == catSpace)
510                 getToken();
511
512         if (getToken().cs() != "newcommand") {
513                 lyxerr << "\\newcommand expected\n";
514                 return 0;
515         }
516
517         if (getToken().cat() != catBegin) {
518                 lyxerr << "'{' expected\n";
519                 return 0;
520         }
521
522         string name = getToken().cs();
523
524         if (getToken().cat() != catEnd) {
525                 lyxerr << "'}' expected\n";
526                 return 0;
527         }
528
529         string arg  = getArg('[', ']');
530         int    narg = arg.empty() ? 0 : atoi(arg.c_str()); 
531         //lyxerr << "creating macro " << name << " with " << narg <<  "args\n";
532         MathMacroTemplate * p = new MathMacroTemplate(name, narg);
533         parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
534         return p;
535 }
536
537
538 MathMatrixInset * Parser::parse_normal()
539 {
540         while (nextToken().cat() == catSpace)
541                 getToken();
542
543         Token const & t = getToken();
544
545         if (t.cat() == catMath || t.cs() == "(") {
546                 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
547                 parse_into(p->cell(0), 0);
548                 return p;
549         }
550
551         if (!t.cs().size()) {
552                 lyxerr << "start of math expected, got '" << t << "'\n";
553                 return 0;
554         }
555
556         string const & cs = t.cs();
557
558         if (cs == "[") {
559                 curr_num_ = 0;
560                 curr_label_.erase();
561                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
562                 parse_into(p->cell(0), 0);
563                 p->numbered(0, curr_num_);
564                 p->label(0, curr_label_);
565                 return p;
566         }
567
568         if (cs != "begin") {
569                 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
570                 return 0;
571         }
572
573         string const name = getArg('{', '}');
574
575         if (name == "equation" || name == "equation*") {
576                 curr_num_ = !stared(name);
577                 curr_label_.erase();
578                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
579                 parse_into(p->cell(0), FLAG_END);
580                 p->numbered(0, curr_num_);
581                 p->label(0, curr_label_);
582                 return p;
583         }
584
585         if (name == "eqnarray" || name == "eqnarray*") {
586                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
587                 parse_lines(p, !stared(name), true);
588                 return p;
589         }
590
591         if (name == "align" || name == "align*") {
592                 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
593                 p->halign(getArg('{', '}'));
594                 parse_lines(p, !stared(name), true);
595                 return p;
596         }
597
598         if (name == "alignat" || name == "alignat*") {
599                 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGNAT);
600                 p->halign(getArg('{', '}'));
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         int  limits = 0;
624
625         while (good()) {
626                 Token const & t = getToken();
627         
628                 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
629                 //array.dump(lyxerr);
630                 //lyxerr << "\n";
631
632                 if (flags & FLAG_ITEM) {
633                         flags &= ~FLAG_ITEM;
634                         if (t.cat() == catBegin) { 
635                                 // skip the brace and collect everything to the next matching
636                                 // closing brace
637                                 flags |= FLAG_BRACE_LAST;
638                                 continue;
639                         } else {
640                                 // handle only this single token, leave the loop if done
641                                 flags |= FLAG_LEAVE;
642                         }
643                 }
644
645                 if (flags & FLAG_BRACE) {
646                         if (t.cat() != catBegin) {
647                                 error("Expected {. Maybe you forgot to enclose an argument in {}");
648                                 panic = true;
649                                 break;
650                         } else {
651                                 flags &= ~FLAG_BRACE;
652                                 continue;
653                         }
654                 }
655
656                 if (flags & FLAG_BLOCK) {
657                         if (t.cat() == catAlign || t.cs() == "\\")
658                                 return;
659                         if (t.cs() == "end") {
660                                 getArg('{', '}');
661                                 return;
662                         }
663                 }
664
665                 //
666                 // cat codes
667                 //
668                 if (t.cat() == catMath)
669                         break;
670
671                 else if (t.cat() == catLetter)
672                         array.push_back(new MathCharInset(t.character(), yyvarcode));
673
674                 else if (t.cat() == catSpace &&
675                                 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
676                         array.push_back(new MathCharInset(' ', yyvarcode));
677
678                 else if (t.cat() == catParameter) {
679                         Token const & n = getToken();
680                         MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
681                         array.push_back(p);
682                 }
683
684                 else if (t.cat() == catBegin) {
685                         array.push_back(new MathCharInset('{', LM_TC_SPECIAL));
686                 }
687
688                 else if (t.cat() == catEnd) {
689                         if (flags & FLAG_BRACE_LAST)
690                                 return;
691                         array.push_back(new MathCharInset('}', LM_TC_SPECIAL));
692                 }
693                 
694                 else if (t.cat() == catAlign) {
695                         lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
696                         array.push_back(new MathCharInset('&', LM_TC_SPECIAL));
697                 }
698                 
699                 else if (t.cat() == catSuper)
700                         parse_into(lastScriptInset(array, true, limits)->cell(0), FLAG_ITEM);
701                 
702                 else if (t.cat() == catSub)
703                         parse_into(lastScriptInset(array, false, limits)->cell(1), FLAG_ITEM);
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") 
736                         limits = 1;
737                 
738                 else if (t.cs() == "nolimits") 
739                         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()->cell(0), FLAG_BRACK_END);
752                                 parse_into(array.back()->cell(1), FLAG_ITEM);
753                         } else {
754                                 putback();
755                                 array.push_back(new MathSqrtInset);
756                                 parse_into(array.back()->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                                 error("Unmatched right delimiter");
773                         return;
774                 }
775
776 /*              
777                 case LM_TK_STY:
778                 {
779                         lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
780                         //MathArray tmp = array;
781                         //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
782                         //array.push_back(p);
783                         //parse_into(p->cell(0), FLAG_BRACE_FONT);
784                         break; 
785                 }
786
787                 case LM_TK_UNDEF: 
788                         if (MathMacroTable::hasTemplate(sval_)) {
789                                 MathMacro * m = MathMacroTable::cloneTemplate(sval_);
790                                 for (int i = 0; i < m->nargs(); ++i) 
791                                         parse_into(m->cell(i), FLAG_ITEM);
792                                 array.push_back(m);
793                                 m->metrics(LM_ST_TEXT);
794                         } else
795                                 array.push_back(new MathFuncInset(sval_));
796                         break;
797
798                 else  LM_TK_SPECIAL:
799                         array.push_back(new MathCharInset(ival_, LM_TC_SPECIAL));
800                         break;
801 */
802                 
803                 else if (t.cs() == "begin") {
804                         string const name = getArg('{', '}');   
805                         if (name == "array") {
806                                 string const valign = getArg('[', ']') + 'c';
807                                 string const halign = getArg('{', '}');
808                                 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
809                                 m->valign(valign[0]);
810                                 m->halign(halign);
811                                 parse_lines(m, false, false);
812                                 array.push_back(m);
813                         } else 
814                                 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";  
815                 }
816         
817                 else if (t.cs() == "kern") {
818 #ifdef WITH_WARNINGS
819 #warning A hack...
820 #endif
821                         string s;
822                         while (1) {
823                                 Token const & t = getToken();
824                                 if (!good()) {
825                                         putback();      
826                                         break;
827                                 }
828                                 s += t.character();
829                                 if (isValidLength(s))
830                                         break;
831                         }
832                         array.push_back(new MathKernInset(s));
833                 }
834
835                 else if (t.cs() == "label") {
836                         //MathArray ar;
837                         //parse_into(ar, FLAG_ITEM);
838                         //ostringstream os;
839                         //ar.write(os, true);
840                         //curr_label_ = os.str();
841                         // was: 
842                         curr_label_ = getArg('{', '}');
843                 }
844
845                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
846                         limits = 0;
847                         MathInset * p = createMathInset(t.cs());
848                         // search backward for position of last '{' if any
849                         int pos;
850                         for (pos = array.size() - 1; pos >= 0; --pos) {
851                                 MathInset * q = array.nextInset(pos);
852                                 if (q->getChar() == '{' && q->code() == LM_TC_SPECIAL)
853                                         break;
854                         }
855                         if (pos >= 0) {
856                                 // found it -> use the part after '{' as "numerator", erase the '{'
857                                 p->cell(0) = MathArray(array, pos + 1, array.size());
858                                 array.erase(pos, array.size());
859                         } else {
860                                 // not found -> use everything as "numerator"
861                                 p->cell(0).swap(array);
862                         }
863                         array.push_back(p);
864                         parse_into(p->cell(1), FLAG_BLOCK);
865                 }
866         
867                 else if (t.cs().size()) {
868                         limits = 0;
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)->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 }