]> git.lyx.org Git - lyx.git/blob - src/mathed/math_parser.C
try to fix free memory leak
[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 }
428
429
430 void Parser::parse_lines(MathGridInset * p, bool numbered, bool outmost)
431 {
432         const int cols = p->ncols();
433
434         // save global variables
435         bool   const saved_num   = curr_num_;
436         string const saved_label = curr_label_;
437
438         for (int row = 0; true; ++row) {
439                 // reset global variables
440                 curr_num_   = numbered;
441                 curr_label_.erase();
442
443                 // reading a row
444                 for (int col = 0; col < cols; ++col) {
445                         //lyxerr << "reading cell " << row << " " << col << "\n";
446                         parse_into(p->cell(col + row * cols), FLAG_BLOCK);
447
448                         // no ampersand
449                         if (prevToken().cat() != catAlign) {
450                                 //lyxerr << "less cells read than normal in row/col: "
451                                 //      << row << " " << col << "\n";
452                                 break;
453                         }
454                 }
455
456                 if (outmost) {
457                         MathMatrixInset * m = static_cast<MathMatrixInset *>(p);
458                         m->numbered(row, curr_num_);
459                         m->label(row, curr_label_);
460                         if (curr_skip_.size()) {
461                                 m->vskip(LyXLength(curr_skip_), row);
462                                 curr_skip_.erase();
463                         }
464                 }
465
466                 // no newline?
467                 if (prevToken() != Token("\\")) {
468                         //lyxerr << "no newline here\n";
469                         break;
470                 }
471
472                 p->appendRow();
473         }
474
475         // restore "global" variables
476         curr_num_   = saved_num;
477         curr_label_ = saved_label;
478 }
479
480
481 MathMacroTemplate * Parser::parse_macro()
482 {
483         while (nextToken().cat() == catSpace)
484                 getToken();
485
486         if (getToken().cs() != "newcommand") {
487                 lyxerr << "\\newcommand expected\n";
488                 return 0;
489         }
490
491         if (getToken().cat() != catBegin) {
492                 lyxerr << "'{' expected\n";
493                 return 0;
494         }
495
496         string name = getToken().cs();
497
498         if (getToken().cat() != catEnd) {
499                 lyxerr << "'}' expected\n";
500                 return 0;
501         }
502
503         string arg  = getArg('[', ']');
504         int    narg = arg.empty() ? 0 : atoi(arg.c_str()); 
505         //lyxerr << "creating macro " << name << " with " << narg <<  "args\n";
506         MathMacroTemplate * p = new MathMacroTemplate(name, narg);
507         parse_into(p->cell(0), FLAG_BRACE | FLAG_BRACE_LAST);
508         return p;
509 }
510
511
512 MathMatrixInset * Parser::parse_normal()
513 {
514         while (nextToken().cat() == catSpace)
515                 getToken();
516
517         Token const & t = getToken();
518
519         if (t.cat() == catMath || t.cs() == "(") {
520                 MathMatrixInset * p = new MathMatrixInset(LM_OT_SIMPLE);
521                 parse_into(p->cell(0), 0);
522                 return p;
523         }
524
525         if (!t.cs().size()) {
526                 lyxerr << "start of math expected, got '" << t << "'\n";
527                 return 0;
528         }
529
530         string const & cs = t.cs();
531
532         if (cs == "[") {
533                 curr_num_ = 0;
534                 curr_label_.erase();
535                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
536                 parse_into(p->cell(0), 0);
537                 p->numbered(0, curr_num_);
538                 p->label(0, curr_label_);
539                 return p;
540         }
541
542         if (cs != "begin") {
543                 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
544                 return 0;
545         }
546
547         string const name = getArg('{', '}');
548
549         if (name == "equation" || name == "equation*") {
550                 curr_num_ = !stared(name);
551                 curr_label_.erase();
552                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQUATION);
553                 parse_into(p->cell(0), FLAG_END);
554                 p->numbered(0, curr_num_);
555                 p->label(0, curr_label_);
556                 return p;
557         }
558
559         if (name == "eqnarray" || name == "eqnarray*") {
560                 MathMatrixInset * p = new MathMatrixInset(LM_OT_EQNARRAY);
561                 parse_lines(p, !stared(name), true);
562                 return p;
563         }
564
565         if (name == "align" || name == "align*") {
566                 MathMatrixInset * p = new MathMatrixInset(LM_OT_ALIGN);
567                 parse_lines(p, !stared(name), true);
568                 return p;
569         }
570
571         if (name == "alignat" || name == "alignat*") {
572                 MathMatrixInset * p =
573                         new MathMatrixInset(LM_OT_ALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
574                 parse_lines(p, !stared(name), true);
575                 return p;
576         }
577
578         if (name == "xalignat" || name == "xalignat*") {
579                 MathMatrixInset * p =
580                         new MathMatrixInset(LM_OT_XALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
581                 parse_lines(p, !stared(name), true);
582                 return p;
583         }
584
585         if (name == "xxalignat") {
586                 MathMatrixInset * p =
587                         new MathMatrixInset(LM_OT_XXALIGNAT, 2 * atoi(getArg('{', '}').c_str()));
588                 parse_lines(p, !stared(name), true);
589                 return p;
590         }
591
592         if (name == "multline" || name == "multline*") {
593                 MathMatrixInset * p = new MathMatrixInset(LM_OT_MULTLINE);
594                 parse_lines(p, !stared(name), true);
595                 return p;
596         }
597
598         if (name == "gather" || name == "gather*") {
599                 MathMatrixInset * p = new MathMatrixInset(LM_OT_GATHER);
600                 parse_lines(p, !stared(name), true);
601                 return p;
602         }
603
604         lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
605         return 0;
606 }
607
608
609 latexkeys const * Parser::read_delim()
610 {
611         Token const & t = getToken();
612         latexkeys const * l = in_word_set(t.asString());
613         return l ? l : in_word_set(".");
614 }
615
616
617 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
618 {
619         MathTextCodes yyvarcode = LM_TC_MIN;
620
621         bool panic  = false;
622
623         while (good()) {
624                 Token const & t = getToken();
625         
626                 //lyxerr << "t: " << t << " flags: " << flags << "'\n";
627                 //array.dump(lyxerr);
628                 //lyxerr << "\n";
629
630                 if (flags & FLAG_ITEM) {
631                         flags &= ~FLAG_ITEM;
632                         if (t.cat() == catBegin) { 
633                                 // skip the brace and collect everything to the next matching
634                                 // closing brace
635                                 flags |= FLAG_BRACE_LAST;
636                                 continue;
637                         } else {
638                                 // handle only this single token, leave the loop if done
639                                 flags |= FLAG_LEAVE;
640                         }
641                 }
642
643                 if (flags & FLAG_BRACE) {
644                         if (t.cat() != catBegin) {
645                                 error("Expected {. Maybe you forgot to enclose an argument in {}");
646                                 panic = true;
647                                 break;
648                         } else {
649                                 flags &= ~FLAG_BRACE;
650                                 continue;
651                         }
652                 }
653
654                 if (flags & FLAG_BLOCK) {
655                         if (t.cat() == catAlign || t.cs() == "\\")
656                                 return;
657                         if (t.cs() == "end") {
658                                 getArg('{', '}');
659                                 return;
660                         }
661                 }
662
663                 //
664                 // cat codes
665                 //
666                 if (t.cat() == catMath)
667                         break;
668
669                 else if (t.cat() == catLetter)
670                         array.push_back(new MathCharInset(t.character(), yyvarcode));
671
672                 else if (t.cat() == catSpace &&
673                                 (yyvarcode == LM_TC_TEXTRM || code == LM_TC_TEXTRM))
674                         array.push_back(new MathCharInset(' ', yyvarcode));
675
676                 else if (t.cat() == catParameter) {
677                         Token const & n = getToken();
678                         MathMacroArgument * p = new MathMacroArgument(n.character() - '0');
679                         array.push_back(p);
680                 }
681
682                 else if (t.cat() == catBegin) {
683                         array.push_back(new MathCharInset('{', LM_TC_TEX));
684                 }
685
686                 else if (t.cat() == catEnd) {
687                         if (flags & FLAG_BRACE_LAST)
688                                 return;
689                         array.push_back(new MathCharInset('}', LM_TC_TEX));
690                 }
691                 
692                 else if (t.cat() == catAlign) {
693                         lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
694                         array.push_back(new MathCharInset('&', LM_TC_TEX));
695                 }
696                 
697                 else if (t.cat() == catSuper || t.cat() == catSub) {
698                         bool up = (t.cat() == catSuper);
699                         if (array.empty())
700                                 array.push_back(new MathCharInset(' '));
701                         parse_into(array.back().ensure(up)->cell(0), FLAG_ITEM);
702                 }
703
704                 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
705                         return;
706
707                 else if (t.cat() == catOther)
708                         array.push_back(new MathCharInset(t.character(), yyvarcode));
709                 
710                 //
711                 // codesequences
712                 //      
713                 else if (t.cs() == "protect") 
714                         ;
715
716                 else if (t.cs() == "end")
717                         break;
718
719                 else if (t.cs() == ")")
720                         break;
721
722                 else if (t.cs() == "]")
723                         break;
724
725                 else if (t.cs() == "\\") {
726                         curr_skip_ = getArg('[', ']');
727                         if (flags & FLAG_NEWLINE)
728                                 return;
729                         lyxerr[Debug::MATHED]
730                                         << "found newline unexpectedly, array: '" << array << "'\n";
731                         array.push_back(createMathInset("\\"));
732                 }
733         
734                 else if (t.cs() == "limits" && array.size())
735                         array.back().limits(1);
736                 
737                 else if (t.cs() == "nolimits" && array.size())
738                         array.back().limits(-1);
739                 
740                 else if (t.cs() == "nonumber")
741                         curr_num_ = false;
742
743                 else if (t.cs() == "number")
744                         curr_num_ = true;
745
746                 else if (t.cs() == "sqrt") {
747                         char c = getChar();
748                         if (c == '[') {
749                                 array.push_back(new MathRootInset);
750                                 parse_into(array.back().nucleus()->cell(0), FLAG_BRACK_END);
751                                 parse_into(array.back().nucleus()->cell(1), FLAG_ITEM);
752                         } else {
753                                 putback();
754                                 array.push_back(new MathSqrtInset);
755                                 parse_into(array.back().nucleus()->cell(0), FLAG_ITEM);
756                         }
757                 }
758                 
759                 else if (t.cs() == "left") {
760                         latexkeys const * l = read_delim();
761                         MathArray ar;
762                         parse_into(ar, FLAG_RIGHT);
763                         latexkeys const * r = read_delim();
764                         MathDelimInset * dl = new MathDelimInset(l, r);
765                         dl->cell(0) = ar;
766                         array.push_back(dl);
767                 }
768                 
769                 else if (t.cs() == "right") {
770                         if (!(flags & FLAG_RIGHT))
771                                 error("Unmatched right delimiter");
772                         return;
773                 }
774
775 /*              
776                 case LM_TK_STY:
777                 {
778                         lyxerr[Debug::MATHED] << "LM_TK_STY not implemented\n";
779                         //MathArray tmp = array;
780                         //MathSizeInset * p = new MathSizeInset(MathStyles(lval_->id));
781                         //array.push_back(p);
782                         //parse_into(p->cell(0), FLAG_BRACE_FONT);
783                         break; 
784                 }
785
786                 else  LM_TK_SPECIAL:
787                         array.push_back(new MathCharInset(ival_, LM_TC_TEX));
788                         break;
789 */
790                 
791                 else if (t.cs() == "begin") {
792                         string const name = getArg('{', '}');   
793                         if (name == "array") {
794                                 string const valign = getArg('[', ']') + 'c';
795                                 string const halign = getArg('{', '}');
796                                 MathArrayInset * m = new MathArrayInset(halign.size(), 1);
797                                 m->valign(valign[0]);
798                                 m->halign(halign);
799                                 parse_lines(m, false, false);
800                                 array.push_back(m);
801                         } else if (name == "split") {
802                                 MathSplitInset * m = new MathSplitInset(1);
803                                 parse_lines(m, false, false);
804                                 array.push_back(m);
805                         } else 
806                                 lyxerr[Debug::MATHED] << "unknow math inset begin '" << name << "'\n";  
807                 }
808         
809                 else if (t.cs() == "kern") {
810 #ifdef WITH_WARNINGS
811 #warning A hack...
812 #endif
813                         string s;
814                         while (1) {
815                                 Token const & t = getToken();
816                                 if (!good()) {
817                                         putback();      
818                                         break;
819                                 }
820                                 s += t.character();
821                                 if (isValidLength(s))
822                                         break;
823                         }
824                         array.push_back(new MathKernInset(s));
825                 }
826
827                 else if (t.cs() == "label") {
828                         //MathArray ar;
829                         //parse_into(ar, FLAG_ITEM);
830                         //ostringstream os;
831                         //ar.write(os, true);
832                         //curr_label_ = os.str();
833                         // was: 
834                         curr_label_ = getArg('{', '}');
835                 }
836
837                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
838                         MathInset * p = createMathInset(t.cs());
839                         // search backward for position of last '{' if any
840                         int pos;
841                         for (pos = array.size() - 1; pos >= 0; --pos)
842                                 if (array.at(pos)->nucleus()->getChar() == '{')
843                                         break;
844                         if (pos >= 0) {
845                                 // found it -> use the part after '{' as "numerator", erase the '{'
846                                 p->cell(0) = MathArray(array, pos + 1, array.size());
847                                 array.erase(pos, array.size());
848                         } else {
849                                 // not found -> use everything as "numerator"
850                                 p->cell(0).swap(array);
851                         }
852                         parse_into(p->cell(1), FLAG_BLOCK);
853                         array.push_back(p);
854                 }
855         
856                 else if (t.cs().size()) {
857                         latexkeys const * l = in_word_set(t.cs());
858                         if (l) {
859                                 if (l->token == LM_TK_FONT) {
860                                         //lyxerr << "starting font\n";
861                                         //CatCode catSpaceSave = theCatcode[' '];
862                                         //if (l->id == LM_TC_TEXTRM) {
863                                         //      // temporarily change catcode   
864                                         //      theCatcode[' '] = catLetter;    
865                                         //}
866
867                                         MathTextCodes t = static_cast<MathTextCodes>(l->id);
868                                         MathArray ar;
869                                         parse_into(ar, FLAG_ITEM, t);
870                                         for (MathArray::iterator it = ar.begin(); it != ar.end(); ++it)
871                                                 it->nucleus()->handleFont(t);
872                                         array.push_back(ar);
873
874                                         // undo catcode changes
875                                         ////theCatcode[' '] = catSpaceSave;
876                                         //lyxerr << "ending font\n";
877                                 }
878
879                                 else if (l->token == LM_TK_OLDFONT)
880                                         yyvarcode = static_cast<MathTextCodes>(l->id);
881
882                                 else {
883                                         MathInset * p = createMathInset(t.cs());
884                                         for (int i = 0; i < p->nargs(); ++i) 
885                                                 parse_into(p->cell(i), FLAG_ITEM);
886                                         array.push_back(p);
887                                 }
888                         }
889
890                         else {
891                                 MathInset * p = createMathInset(t.cs());
892                                 if (p) {
893                                         for (int i = 0; i < p->nargs(); ++i)
894                                                 parse_into(p->cell(i), FLAG_ITEM);
895                                         array.push_back(p);
896                                 } else {
897                                         error("Unrecognized token");
898                                         //lyxerr[Debug::MATHED] << "[" << t << "]\n";
899                                         lyxerr << t << "\n";
900                                 }       
901                         }
902                 }
903
904
905                 if (flags & FLAG_LEAVE) {
906                         flags &= ~FLAG_LEAVE;
907                         break;
908                 }
909         }
910
911         if (panic) {
912                 lyxerr << " Math Panic, expect problems!\n";
913                 //   Search for the end command. 
914                 Token t;
915                 do {
916                         t = getToken();
917                 } while (good() && t.cs() != "end");
918         }
919 }
920
921 } // anonymous namespace
922
923
924
925 MathArray mathed_parse_cell(string const & str)
926 {
927         istringstream is(str.c_str());
928         Parser parser(is);
929         MathArray ar;
930         parser.parse_into(ar, 0);
931         return ar;
932 }
933
934
935
936 MathMacroTemplate * mathed_parse_macro(string const & str)
937 {
938         istringstream is(str.c_str());
939         Parser parser(is);
940         return parser.parse_macro();
941 }
942
943 MathMacroTemplate * mathed_parse_macro(istream & is)
944 {
945         Parser parser(is);
946         return parser.parse_macro();
947 }
948
949 MathMacroTemplate * mathed_parse_macro(LyXLex & lex)
950 {
951         Parser parser(lex);
952         return parser.parse_macro();
953 }
954
955
956
957 MathMatrixInset * mathed_parse_normal(string const & str)
958 {
959         istringstream is(str.c_str());
960         Parser parser(is);
961         return parser.parse_normal();
962 }
963
964 MathMatrixInset * mathed_parse_normal(istream & is)
965 {
966         Parser parser(is);
967         return parser.parse_normal();
968 }
969
970 MathMatrixInset * mathed_parse_normal(LyXLex & lex)
971 {
972         Parser parser(lex);
973         return parser.parse_normal();
974 }