]> git.lyx.org Git - lyx.git/blob - src/mathed/math_parser.C
move around debugging stuff
[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 /* 
19
20 If someone desperately needs partial "structures" (such as a few cells of
21 an array inset or similar) (s)he could uses the following hack as starting
22 point to write some macros:
23
24   \newif\ifcomment
25   \commentfalse
26   \ifcomment
27           \def\makeamptab{\catcode`\&=4\relax}
28           \def\makeampletter{\catcode`\&=11\relax}
29     \def\b{\makeampletter\expandafter\makeamptab\bi}
30     \long\def\bi#1\e{}
31   \else
32     \def\b{}\def\e{}
33   \fi
34
35   ...
36
37   \[\begin{array}{ccc}
38    1 & 2\b & 3^2\\
39    4 & 5\e & 6\\
40    7 & 8 & 9
41   \end{array}\]
42
43 */
44
45
46 #include <config.h>
47
48 #ifdef __GNUG__
49 #pragma implementation
50 #endif
51
52 #include "math_parser.h"
53 #include "math_inset.h"
54 #include "math_arrayinset.h"
55 #include "math_braceinset.h"
56 #include "math_boxinset.h"
57 #include "math_charinset.h"
58 #include "math_deliminset.h"
59 #include "math_factory.h"
60 #include "math_funcinset.h"
61 #include "math_kerninset.h"
62 #include "math_macro.h"
63 #include "math_macrotable.h"
64 #include "math_macrotemplate.h"
65 #include "math_hullinset.h"
66 #include "math_rootinset.h"
67 #include "math_sizeinset.h"
68 #include "math_sqrtinset.h"
69 #include "math_scriptinset.h"
70 #include "math_specialcharinset.h"
71 #include "math_sqrtinset.h"
72 #include "math_support.h"
73 #include "math_xyarrowinset.h"
74
75 #include "lyxlex.h"
76 #include "debug.h"
77 #include "support/LAssert.h"
78 #include "support/lstrings.h"
79
80 #include <cctype>
81 #include <stack>
82 #include <algorithm>
83
84 using std::istream;
85 using std::ostream;
86 using std::ios;
87 using std::endl;
88 using std::stack;
89 using std::fill;
90
91 //#define FILEDEBUG
92
93
94 namespace {
95
96 bool stared(string const & s)
97 {
98         string::size_type const n = s.size();
99         return n && s[n - 1] == '*';
100 }
101
102
103 void add(MathArray & ar, char c, MathTextCodes code)
104 {
105         ar.push_back(MathAtom(new MathCharInset(c, code)));
106 }
107
108
109 // These are TeX's catcodes
110 enum CatCode {
111         catEscape,     // 0    backslash 
112         catBegin,      // 1    {
113         catEnd,        // 2    }
114         catMath,       // 3    $
115         catAlign,      // 4    &
116         catNewline,    // 5    ^^M
117         catParameter,  // 6    #
118         catSuper,      // 7    ^
119         catSub,        // 8    _
120         catIgnore,     // 9       
121         catSpace,      // 10   space
122         catLetter,     // 11   a-zA-Z
123         catOther,      // 12   none of the above
124         catActive,     // 13   ~
125         catComment,    // 14   %
126         catInvalid     // 15   <delete>
127 };
128
129 CatCode theCatcode[256];  
130
131
132 inline CatCode catcode(unsigned char c)
133 {
134         return theCatcode[c];
135 }
136
137
138 enum {
139         FLAG_BRACE_LAST = 1 << 1,  //  last closing brace ends the parsing process
140         FLAG_RIGHT      = 1 << 2,  //  next \\right ends the parsing process
141         FLAG_END        = 1 << 3,  //  next \\end ends the parsing process
142         FLAG_BRACK_END  = 1 << 4,  //  next closing bracket ends the parsing process
143         FLAG_BOX        = 1 << 5,  //  we are in a box
144         FLAG_ITEM       = 1 << 6,  //  read a (possibly braced token)
145         FLAG_BLOCK      = 1 << 7,  //  next block ends the parsing process
146         FLAG_BLOCK2     = 1 << 8,  //  next block2 ends the parsing process
147         FLAG_LEAVE      = 1 << 9   //  leave the loop at the end
148 };
149
150
151 void catInit()
152 {
153         fill(theCatcode, theCatcode + 256, catOther);
154         fill(theCatcode + 'a', theCatcode + 'z' + 1, catLetter);
155         fill(theCatcode + 'A', theCatcode + 'Z' + 1, catLetter);
156
157         theCatcode['\\'] = catEscape;   
158         theCatcode['{']  = catBegin;    
159         theCatcode['}']  = catEnd;      
160         theCatcode['$']  = catMath;     
161         theCatcode['&']  = catAlign;    
162         theCatcode['\n'] = catNewline;  
163         theCatcode['#']  = catParameter;        
164         theCatcode['^']  = catSuper;    
165         theCatcode['_']  = catSub;      
166         theCatcode['\7f'] = catIgnore;    
167         theCatcode[' ']  = catSpace;    
168         theCatcode['\t'] = catSpace;    
169         theCatcode['\r'] = catSpace;    
170         theCatcode['~']  = catActive;   
171         theCatcode['%']  = catComment;  
172 }
173
174
175
176 //
177 // Helper class for parsing
178 //
179
180 class Token {
181 public:
182         ///
183         Token() : cs_(), char_(0), cat_(catIgnore) {}
184         ///
185         Token(char c, CatCode cat) : cs_(), char_(c), cat_(cat) {}
186         ///
187         Token(string const & cs) : cs_(cs), char_(0), cat_(catIgnore) {}
188
189         ///
190         string const & cs() const { return cs_; }
191         ///
192         CatCode cat() const { return cat_; }
193         ///
194         char character() const { return char_; }
195         ///
196         string asString() const;
197         ///
198         bool isCR() const;
199
200 private:        
201         ///
202         string cs_;
203         ///
204         char char_;
205         ///
206         CatCode cat_;
207 };
208
209 bool Token::isCR() const
210 {
211         return cs_ == "\\" || cs_ == "cr" || cs_ == "crcr";
212 }
213
214 string Token::asString() const
215 {
216         return cs_.size() ? cs_ : string(1, char_);
217 }
218
219 // Angus' compiler says these are not needed
220 //bool operator==(Token const & s, Token const & t)
221 //{
222 //      return s.character() == t.character()
223 //              && s.cat() == t.cat() && s.cs() == t.cs(); 
224 //}
225 //
226 //bool operator!=(Token const & s, Token const & t)
227 //{
228 //      return !(s == t);
229 //}
230
231 ostream & operator<<(ostream & os, Token const & t)
232 {
233         if (t.cs().size())
234                 os << "\\" << t.cs();
235         else
236                 os << "[" << t.character() << "," << t.cat() << "]";
237         return os;
238 }
239
240
241 class Parser {
242
243 public:
244         ///
245         Parser(LyXLex & lex);
246         ///
247         Parser(istream & is);
248
249         ///
250         bool parse_macro(string & name);
251         ///
252         bool parse_normal(MathAtom &);
253         ///
254         void parse_into(MathArray & array, unsigned flags, MathTextCodes = LM_TC_MIN);
255         ///
256         int lineno() const { return lineno_; }
257         ///
258         void putback();
259
260 private:
261         ///
262         void parse_into1(MathArray & array, unsigned flags, MathTextCodes);
263         ///
264         string getArg(char lf, char rf);
265         ///
266         char getChar();
267         ///
268         void error(string const & msg);
269         ///
270         bool parse_lines(MathAtom & t, bool numbered, bool outmost);
271         /// parses {... & ... \\ ... & ... }
272         bool parse_lines2(MathAtom & t, bool braced);
273         /// dump contents to screen
274         void dump() const;
275
276 private:
277         ///
278         void tokenize(istream & is);
279         ///
280         void tokenize(string const & s);
281         ///
282         void skipSpaceTokens(istream & is, char c);
283         ///
284         void push_back(Token const & t);
285         ///
286         void pop_back();
287         ///
288         Token const & prevToken() const;
289         ///
290         Token const & nextToken() const;
291         ///
292         Token const & getToken();
293         /// skips spaces if any
294         void skipSpaces();
295         /// skips opening brace
296         void skipBegin();
297         /// skips closing brace
298         void skipEnd();
299         /// counts a sequence of hlines
300         int readHLines();
301         ///
302         void lex(string const & s);
303         ///
304         bool good() const;
305
306         ///
307         int lineno_;
308         ///
309         std::vector<Token> tokens_;
310         ///
311         unsigned pos_;
312         ///
313         bool   curr_num_;
314         ///
315         string curr_label_;
316         ///
317         string curr_skip_;
318 };
319
320
321 Parser::Parser(LyXLex & lexer)
322         : lineno_(lexer.getLineNo()), pos_(0), curr_num_(false)
323 {
324         tokenize(lexer.getStream());
325         lexer.eatLine();
326 }
327
328
329 Parser::Parser(istream & is)
330         : lineno_(0), pos_(0), curr_num_(false)
331 {
332         tokenize(is);
333 }
334
335
336 void Parser::push_back(Token const & t)
337 {
338         tokens_.push_back(t);
339 }
340
341
342 void Parser::pop_back()
343 {
344         tokens_.pop_back();
345 }
346
347
348 Token const & Parser::prevToken() const
349 {
350         static const Token dummy;
351         return pos_ > 0 ? tokens_[pos_ - 1] : dummy;
352 }
353
354
355 Token const & Parser::nextToken() const
356 {
357         static const Token dummy;
358         return good() ? tokens_[pos_] : dummy;
359 }
360
361
362 Token const & Parser::getToken()
363 {
364         static const Token dummy;
365         //lyxerr << "looking at token " << tokens_[pos_] << " pos: " << pos_ << '\n';
366         return good() ? tokens_[pos_++] : dummy;
367 }
368
369
370 void Parser::skipSpaces()
371 {
372         while (nextToken().cat() == catSpace)
373                 getToken();
374 }
375
376
377 void Parser::skipBegin()
378 {
379         if (nextToken().cat() == catBegin)
380                 getToken();
381         else
382                 lyxerr << "'{' expected\n";
383 }
384
385
386 void Parser::skipEnd()
387 {
388         if (nextToken().cat() == catEnd)
389                 getToken();
390         else
391                 lyxerr << "'}' expected\n";
392 }
393
394
395 int Parser::readHLines()
396 {
397         int num = 0;
398         skipSpaces();
399         while (nextToken().cs() == "hline") {
400                 getToken();
401                 ++num;
402                 skipSpaces();
403         }
404         return num;
405 }
406
407
408 void Parser::putback()
409 {
410         --pos_;
411 }
412
413
414 bool Parser::good() const
415 {
416         return pos_ < tokens_.size();
417 }
418
419
420 char Parser::getChar()
421 {
422         if (!good())
423                 lyxerr << "The input stream is not well..." << endl;
424         return tokens_[pos_++].character();
425 }
426
427
428 string Parser::getArg(char lf, char rg)
429 {
430         skipSpaces();
431
432         string result;
433         char c = getChar();
434
435         if (c != lf)  
436                 putback();
437         else 
438                 while ((c = getChar()) != rg && good())
439                         result += c;
440
441         return result;
442 }
443
444
445 void Parser::tokenize(istream & is)
446 {
447         // eat everything up to the next \end_inset or end of stream
448         // and store it in s for further tokenization
449         string s;
450         char c;
451         while (is.get(c)) {
452                 s += c;
453                 if (s.size() >= 10 && s.substr(s.size() - 10) == "\\end_inset") {
454                         s = s.substr(0, s.size() - 10);
455                         break;
456                 }
457         }
458
459         // tokenize buffer
460         tokenize(s);
461 }
462
463
464 void Parser::skipSpaceTokens(istream & is, char c)
465 {
466         // skip trailing spaces
467         while (catcode(c) == catSpace || catcode(c) == catNewline)
468                 if (!is.get(c))
469                         break;
470         //lyxerr << "putting back: " << c << "\n";
471         is.putback(c);
472 }
473
474
475 void Parser::tokenize(string const & buffer)
476 {
477         static bool init_done = false;
478         
479         if (!init_done) {
480                 catInit();
481                 init_done = true;
482         }
483
484         istringstream is(buffer.c_str(), ios::in | ios::binary);
485
486         char c;
487         while (is.get(c)) {
488                 //lyxerr << "reading c: " << c << "\n";
489
490                 switch (catcode(c)) {
491                         case catNewline: {
492                                 ++lineno_; 
493                                 is.get(c);
494                                 if (catcode(c) == catNewline)
495                                         ; //push_back(Token("par"));
496                                 else {
497                                         push_back(Token(' ', catSpace));
498                                         is.putback(c);  
499                                 }
500                                 break;
501                         }
502
503                         case catComment: {
504                                 while (is.get(c) && catcode(c) != catNewline)
505                                         ;
506                                 ++lineno_; 
507                                 break;
508                         }
509
510                         case catEscape: {
511                                 is.get(c);
512                                 if (!is) {
513                                         error("unexpected end of input");
514                                 } else {
515                                         string s(1, c);
516                                         if (catcode(c) == catLetter) {
517                                                 // collect letters
518                                                 while (is.get(c) && catcode(c) == catLetter)
519                                                         s += c;
520                                                 skipSpaceTokens(is, c);
521                                         }       
522                                         push_back(Token(s));
523                                 }
524                                 break;
525                         }
526
527                         case catSuper:
528                         case catSub: {
529                                 push_back(Token(c, catcode(c)));
530                                 is.get(c);
531                                 skipSpaceTokens(is, c);
532                                 break;
533                         }
534
535                         case catIgnore: {
536                                 lyxerr << "ignoring a char: " << int(c) << "\n";
537                                 break;
538                         }
539
540                         default:
541                                 push_back(Token(c, catcode(c)));
542                 }
543         }
544
545 #ifdef FILEDEBUG
546         dump();
547 #endif
548 }
549
550
551 void Parser::dump() const
552 {
553         lyxerr << "\nTokens: ";
554         for (unsigned i = 0; i < tokens_.size(); ++i)
555                 lyxerr << tokens_[i];
556         lyxerr << "\n";
557 }
558
559
560 void Parser::error(string const & msg) 
561 {
562         lyxerr << "Line ~" << lineno_ << ": Math parse error: " << msg << endl;
563         dump();
564         //exit(1);
565 }
566
567
568
569 bool Parser::parse_lines(MathAtom & t, bool numbered, bool outmost)
570 {       
571         MathGridInset * p = t->asGridInset();
572         if (!p) {
573                 dump();
574                 lyxerr << "error in Parser::parse_lines() 1\n";
575                 return false;
576         }
577
578         // save global variables
579         bool   const saved_num   = curr_num_;
580         string const saved_label = curr_label_;
581
582         // read initial hlines
583         p->rowinfo(0).lines_ = readHLines();
584
585         for (int row = 0; true; ++row) {
586                 // reset global variables
587                 curr_num_   = numbered;
588                 curr_label_.erase();
589
590                 // reading a row
591                 for (MathInset::col_type col = 0; col < p->ncols(); ++col) {
592                         //lyxerr << "reading cell " << row << " " << col << "\n";
593                         //lyxerr << "ncols: " << p->ncols() << "\n";
594                 
595                         MathArray & ar = p->cell(col + row * p->ncols());
596                         parse_into(ar, FLAG_BLOCK);
597                         // remove 'unnecessary' braces:
598                         if (ar.size() == 1 && ar.back()->asBraceInset())
599                                 ar = ar.back()->asBraceInset()->cell(0);
600                         //lyxerr << "ar: " << ar << "\n";
601
602                         // break if cell is not followed by an ampersand
603                         if (nextToken().cat() != catAlign) {
604                                 //lyxerr << "less cells read than normal in row/col: "
605                                 //      << row << " " << col << "\n";
606                                 break;
607                         }
608                         
609                         // skip the ampersand
610                         getToken();
611                 }
612
613                 if (outmost) {
614                         MathHullInset * m = t->asHullInset();
615                         if (!m) {
616                                 lyxerr << "error in Parser::parse_lines() 2\n";
617                                 return false;
618                         }
619                         m->numbered(row, curr_num_);
620                         m->label(row, curr_label_);
621                         if (curr_skip_.size()) {
622                                 m->vcrskip(LyXLength(curr_skip_), row);
623                                 curr_skip_.erase();
624                         }
625                 }
626
627                 // is a \\ coming?
628                 if (nextToken().isCR()) {
629                         // skip the cr-token
630                         getToken();
631
632                         // try to read a length
633                         //get
634
635                         // read hlines for next row
636                         p->rowinfo(row + 1).lines_ = readHLines();
637                 }
638
639                 // we are finished if the next token is an 'end'
640                 if (nextToken().cs() == "end") {
641                         // skip the end-token
642                         getToken();
643                         getArg('{','}');
644
645                         // leave the 'read a line'-loop
646                         break;
647                 }
648
649                 // otherwise, we have to start a new row
650                 p->appendRow();
651         }
652
653         // restore "global" variables
654         curr_num_   = saved_num;
655         curr_label_ = saved_label;
656
657         return true;
658 }
659
660
661 bool Parser::parse_lines2(MathAtom & t, bool braced)
662 {       
663         MathGridInset * p = t->asGridInset();
664         if (!p) {
665                 lyxerr << "error in Parser::parse_lines() 1\n";
666                 return false;
667         }
668
669         for (int row = 0; true; ++row) {
670                 // reading a row
671                 for (MathInset::col_type col = 0; true; ++col) {
672                         //lyxerr << "reading cell " << row << " " << col << " " << p->ncols() << "\n";
673                 
674                         if (col >= p->ncols()) {
675                                 //lyxerr << "adding col " << col << "\n";
676                                 p->addCol(p->ncols());
677                         }
678
679                         parse_into(p->cell(col + row * p->ncols()), FLAG_BLOCK2);
680                         //lyxerr << "read cell: " << p->cell(col + row * p->ncols()) << "\n";
681
682                         // break if cell is not followed by an ampersand
683                         if (nextToken().cat() != catAlign) {
684                                 //lyxerr << "less cells read than normal in row/col: " << row << " " << col << "\n";
685                                 break;
686                         }
687                         
688                         // skip the ampersand
689                         getToken();
690                 }
691
692                 // is a \\ coming?
693                 if (nextToken().isCR()) {
694                         // skip the cr-token
695                         getToken();
696                 }
697
698                 // we are finished if the next token is the one we expected
699                 // skip the end-token
700                 // leave the 'read a line'-loop
701                 if (braced) {
702                         if (nextToken().cat() == catEnd) {
703                                 getToken();
704                                 break;
705                         }
706                 } else {
707                         if (nextToken().cs() == "end") {
708                                 getToken();
709                                 getArg('{','}');
710                                 break;
711                         }
712                 }
713
714                 // otherwise, we have to start a new row
715                 p->appendRow();
716         }
717
718         return true;
719 }
720
721
722
723 bool Parser::parse_macro(string & name)
724 {
725         name = "{error}";
726         skipSpaces();
727
728         if (getToken().cs() != "newcommand") {
729                 lyxerr << "\\newcommand expected\n";
730                 return false;
731         }
732
733         if (getToken().cat() != catBegin) {
734                 lyxerr << "'{' in \\newcommand expected (1)\n";
735                 return false;
736         }
737
738         name = getToken().cs();
739
740         if (getToken().cat() != catEnd) {
741                 lyxerr << "'}' expected\n";
742                 return false;
743         }
744
745         string    arg  = getArg('[', ']');
746         int       narg = arg.empty() ? 0 : atoi(arg.c_str()); 
747
748         if (getToken().cat() != catBegin) {
749                 lyxerr << "'{' in \\newcommand expected (2)\n";
750                 return false;
751         }
752
753         MathArray ar;
754         parse_into(ar, FLAG_BRACE_LAST);
755
756         // we cannot handle recursive stuff at all
757         MathArray test;
758         test.push_back(createMathInset(name));
759         if (ar.contains(test)) {
760                 lyxerr << "we cannot handle recursive macros at all.\n";
761                 return false;
762         }
763
764         MathMacroTable::create(name, narg, ar);
765         return true;
766 }
767
768
769 bool Parser::parse_normal(MathAtom & matrix)
770 {
771         skipSpaces();
772         Token const & t = getToken();
773
774         if (t.cs() == "(") {
775                 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
776                 parse_into(matrix->cell(0), 0);
777                 return true;
778         }
779
780         if (t.cat() == catMath) {
781                 Token const & n = getToken();
782                 if (n.cat() == catMath) {
783                         // TeX's $$...$$ syntax for displayed math
784                         matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
785                         MathHullInset * p = matrix->asHullInset();
786                         parse_into(p->cell(0), 0);
787                         p->numbered(0, curr_num_);
788                         p->label(0, curr_label_);
789                 } else {
790                         // simple $...$  stuff
791                         putback();
792                         matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
793                         parse_into(matrix->cell(0), 0);
794                 }
795                 return true;
796         }
797
798         if (!t.cs().size()) {
799                 lyxerr << "start of math expected, got '" << t << "'\n";
800                 return false;
801         }
802
803         string const & cs = t.cs();
804
805         if (cs == "[") {
806                 curr_num_ = 0;
807                 curr_label_.erase();
808                 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
809                 MathHullInset * p = matrix->asHullInset();
810                 parse_into(p->cell(0), 0);
811                 p->numbered(0, curr_num_);
812                 p->label(0, curr_label_);
813                 return true;
814         }
815
816         if (cs != "begin") {
817                 lyxerr << "'begin' of un-simple math expected, got '" << cs << "'\n";
818                 return false;
819         }
820
821         string const name = getArg('{', '}');
822
823         if (name == "math") {
824                 matrix = MathAtom(new MathHullInset(LM_OT_SIMPLE));
825                 parse_into(matrix->cell(0), 0);
826                 return true;
827         }
828
829         if (name == "equation" || name == "equation*" || name == "displaymath") {
830                 curr_num_ = (name == "equation");
831                 curr_label_.erase();
832                 matrix = MathAtom(new MathHullInset(LM_OT_EQUATION));
833                 MathHullInset * p = matrix->asHullInset();
834                 parse_into(p->cell(0), FLAG_END);
835                 p->numbered(0, curr_num_);
836                 p->label(0, curr_label_);
837                 return true;
838         }
839
840         if (name == "eqnarray" || name == "eqnarray*") {
841                 matrix = MathAtom(new MathHullInset(LM_OT_EQNARRAY));
842                 return parse_lines(matrix, !stared(name), true);
843         }
844
845         if (name == "align" || name == "align*") {
846                 matrix = MathAtom(new MathHullInset(LM_OT_ALIGN));
847                 return parse_lines(matrix, !stared(name), true);
848         }
849
850         if (name == "alignat" || name == "alignat*") {
851                 int nc = 2 * atoi(getArg('{', '}').c_str());
852                 matrix = MathAtom(new MathHullInset(LM_OT_ALIGNAT, nc));
853                 return parse_lines(matrix, !stared(name), true);
854         }
855
856         if (name == "xalignat" || name == "xalignat*") {
857                 int nc = 2 * atoi(getArg('{', '}').c_str());
858                 matrix = MathAtom(new MathHullInset(LM_OT_XALIGNAT, nc));
859                 return parse_lines(matrix, !stared(name), true);
860         }
861
862         if (name == "xxalignat") {
863                 int nc = 2 * atoi(getArg('{', '}').c_str());
864                 matrix = MathAtom(new MathHullInset(LM_OT_XXALIGNAT, nc));
865                 return parse_lines(matrix, !stared(name), true);
866         }
867
868         if (name == "multline" || name == "multline*") {
869                 matrix = MathAtom(new MathHullInset(LM_OT_MULTLINE));
870                 return parse_lines(matrix, !stared(name), true);
871         }
872
873         if (name == "gather" || name == "gather*") {
874                 matrix = MathAtom(new MathHullInset(LM_OT_GATHER));
875                 return parse_lines(matrix, !stared(name), true);
876         }
877
878         lyxerr[Debug::MATHED] << "1: unknown math environment: " << name << "\n";
879         lyxerr << "1: unknown math environment: " << name << "\n";
880         return false;
881 }
882
883
884 void Parser::parse_into(MathArray & array, unsigned flags, MathTextCodes code)
885 {
886         parse_into1(array, flags, code);
887         // remove 'unnecessary' braces:
888         if (array.size() == 1 && array.back()->asBraceInset()) {
889                 lyxerr << "extra braces removed\n";
890                 array = array.back()->asBraceInset()->cell(0);
891         }
892 }
893
894
895 void Parser::parse_into1(MathArray & array, unsigned flags, MathTextCodes code)
896 {
897         bool panic  = false;
898         int  limits = 0;
899
900         while (good()) {
901                 Token const & t = getToken();
902         
903 #ifdef FILEDEBUG
904                 lyxerr << "t: " << t << " flags: " << flags << "\n";
905                 //array.dump();
906                 lyxerr << "\n";
907 #endif
908
909                 if (flags & FLAG_ITEM) {
910                         flags &= ~FLAG_ITEM;
911                         if (t.cat() == catBegin) { 
912                                 // skip the brace and collect everything to the next matching
913                                 // closing brace
914                                 flags |= FLAG_BRACE_LAST;
915                                 continue;
916                         } else {
917                                 // handle only this single token, leave the loop if done
918                                 flags |= FLAG_LEAVE;
919                         }
920                 }
921
922                 if (flags & FLAG_BLOCK) {
923                         if (t.cat() == catAlign || t.isCR() || t.cs() == "end") {
924                                 putback();
925                                 return;
926                         }
927                 }
928
929                 if (flags & FLAG_BLOCK2) {
930                         if (t.cat() == catAlign || t.isCR() || t.cs() == "end"
931                                         || t.cat() == catEnd) {
932                                 putback();
933                                 return;
934                         }
935                 }
936
937                 //
938                 // cat codes
939                 //
940                 if (t.cat() == catMath) {
941                         if (flags & FLAG_BOX) {
942                                 // we are inside an mbox, so opening new math is allowed
943                                 array.push_back(MathAtom(new MathHullInset(LM_OT_SIMPLE)));
944                                 parse_into(array.back()->cell(0), 0);
945                         } else {
946                                 // otherwise this is the end of the formula
947                                 break;
948                         }
949                 }
950
951                 else if (t.cat() == catLetter)
952                         add(array, t.character(), code);
953
954                 else if (t.cat() == catSpace && code == LM_TC_TEXTRM)
955                         add(array, t.character(), code);
956
957                 else if (t.cat() == catParameter) {
958                         Token const & n = getToken();
959                         array.push_back(MathAtom(new MathMacroArgument(n.character()-'0', code)));
960                 }
961
962                 else if (t.cat() == catBegin) {
963                         MathArray ar;
964                         parse_into(ar, FLAG_BRACE_LAST);
965 #ifndef WITH_WARNINGS
966 #warning this might be wrong in general!
967 #endif
968                         // ignore braces around simple items
969                         if ((ar.size() == 1 && !ar.front()->needsBraces()
970        || (ar.size() == 2 && !ar.front()->needsBraces()
971                                             && ar.back()->asScriptInset()))
972        || (ar.size() == 0 && array.size() == 0))
973                         {
974                                 array.push_back(ar);
975                         } else {
976                                 array.push_back(MathAtom(new MathBraceInset));
977                                 array.back()->cell(0).swap(ar);
978                         }
979                 }
980
981                 else if (t.cat() == catEnd) {
982                         if (flags & FLAG_BRACE_LAST)
983                                 return;
984                         lyxerr << "found '}' unexpectedly, array: '" << array << "'\n";
985                         //lyxerr << "found '}' unexpectedly\n";
986                         lyx::Assert(0);
987                         add(array, '}', LM_TC_TEX);
988                 }
989                 
990                 else if (t.cat() == catAlign) {
991                         lyxerr << "found tab unexpectedly, array: '" << array << "'\n";
992                         //lyxerr << "found tab unexpectedly\n";
993                         add(array, '&', LM_TC_TEX);
994                 }
995                 
996                 else if (t.cat() == catSuper || t.cat() == catSub) {
997                         bool up = (t.cat() == catSuper);
998                         MathScriptInset * p = 0; 
999                         if (array.size()) 
1000                                 p = array.back()->asScriptInset();
1001                         if (!p || p->has(up)) {
1002                                 array.push_back(MathAtom(new MathScriptInset(up)));
1003                                 p = array.back()->asScriptInset();
1004                         }
1005                         p->ensure(up);
1006                         parse_into(p->cell(up), FLAG_ITEM);
1007                         p->limits(limits);
1008                         limits = 0;
1009                 }
1010
1011                 else if (t.character() == ']' && (flags & FLAG_BRACK_END))
1012                         return;
1013
1014                 else if (t.cat() == catOther)
1015                         add(array, t.character(), code);
1016                 
1017                 //
1018                 // control sequences
1019                 //      
1020                 else if (t.cs() == "protect")
1021                         // ignore \\protect, will be re-added during output 
1022                         ;
1023
1024                 else if (t.cs() == "end")
1025                         break;
1026
1027                 else if (t.cs() == ")")
1028                         break;
1029
1030                 else if (t.cs() == "]")
1031                         break;
1032
1033                 else if (t.cs() == "\\") {
1034                         curr_skip_ = getArg('[', ']');
1035                         //lyxerr << "found newline unexpectedly, array: '" << array << "'\n";
1036                         lyxerr << "found newline unexpectedly\n";
1037                         array.push_back(createMathInset("\\"));
1038                 }
1039         
1040                 else if (t.cs() == "limits")
1041                         limits = 1;
1042                 
1043                 else if (t.cs() == "nolimits")
1044                         limits = -1;
1045                 
1046                 else if (t.cs() == "nonumber")
1047                         curr_num_ = false;
1048
1049                 else if (t.cs() == "number")
1050                         curr_num_ = true;
1051
1052                 else if (t.cs() == "sqrt") {
1053                         char c = getChar();
1054                         if (c == '[') {
1055                                 array.push_back(MathAtom(new MathRootInset));
1056                                 parse_into(array.back()->cell(0), FLAG_BRACK_END);
1057                                 parse_into(array.back()->cell(1), FLAG_ITEM);
1058                         } else {
1059                                 putback();
1060                                 array.push_back(MathAtom(new MathSqrtInset));
1061                                 parse_into(array.back()->cell(0), FLAG_ITEM);
1062                         }
1063                 }
1064                 
1065                 else if (t.cs() == "left") {
1066                         string l = getToken().asString();
1067                         MathArray ar;
1068                         parse_into(ar, FLAG_RIGHT);
1069                         string r = getToken().asString();
1070                         MathAtom dl(new MathDelimInset(l, r));
1071                         dl->cell(0) = ar;
1072                         array.push_back(dl);
1073                 }
1074                 
1075                 else if (t.cs() == "right") {
1076                         if (!(flags & FLAG_RIGHT)) {
1077                                 //lyxerr << "got so far: '" << array << "'\n";
1078                                 error("Unmatched right delimiter");
1079                         }
1080                         return;
1081                 }
1082
1083                 else if (t.cs() == "begin") {
1084                         string const name = getArg('{', '}');   
1085                         if (name == "array" || name == "subarray") {
1086                                 string const valign = getArg('[', ']') + 'c';
1087                                 string const halign = getArg('{', '}');
1088                                 array.push_back(MathAtom(new MathArrayInset(name, valign[0], halign)));
1089                                 parse_lines(array.back(), false, false);
1090                         } else if (name == "split" || name == "cases") {
1091                                 array.push_back(createMathInset(name));
1092                                 parse_lines(array.back(), false, false);
1093                         } else if (name == "pmatrix" || name == "bmatrix" ||
1094                                          name == "vmatrix" || name == "Vmatrix") {
1095                                 array.push_back(createMathInset(name));
1096                                 parse_lines2(array.back(), false);
1097                         } else 
1098                                 lyxerr << "unknow math inset begin '" << name << "'\n"; 
1099                 }
1100         
1101                 else if (t.cs() == "kern") {
1102 #ifdef WITH_WARNINGS
1103 #warning A hack...
1104 #endif
1105                         string s;
1106                         while (1) {
1107                                 Token const & t = getToken();
1108                                 if (!good()) {
1109                                         putback();      
1110                                         break;
1111                                 }
1112                                 s += t.character();
1113                                 if (isValidLength(s))
1114                                         break;
1115                         }
1116                         array.push_back(MathAtom(new MathKernInset(s)));
1117                 }
1118
1119                 else if (t.cs() == "label") {
1120                         curr_label_ = getArg('{', '}');
1121                 }
1122
1123                 else if (t.cs() == "choose" || t.cs() == "over" || t.cs() == "atop") {
1124                         MathAtom p = createMathInset(t.cs());
1125                         array.swap(p->cell(0));
1126                         parse_into(p->cell(1), flags, code);
1127                         array.push_back(p);
1128                         return;
1129                 }
1130
1131                 else if (t.cs() == "substack") {
1132                         array.push_back(createMathInset(t.cs()));
1133                         skipBegin();
1134                         parse_lines2(array.back(), true);
1135                 }
1136
1137                 else if (t.cs() == "xymatrix") {
1138                         array.push_back(createMathInset(t.cs()));
1139                         skipBegin();
1140                         parse_lines2(array.back(), true);
1141                 }
1142
1143 #if 0
1144                 // Disabled
1145                 else if (1 && t.cs() == "ar") {
1146                         MathXYArrowInset * p = new MathXYArrowInset;
1147
1148                         // try to read target
1149                         char c = getChar();
1150                         if (c == '[') {
1151                                 parse_into(p->cell(0), FLAG_BRACK_END);
1152                                 //lyxerr << "read target: " << p->cell(0) << "\n";
1153                         } else {
1154                                 putback();
1155                         }
1156
1157                         // try to read label
1158                         if (nextToken().cat() == catSuper || nextToken().cat() == catSub) {
1159                                 p->up_ = nextToken().cat() == catSuper;
1160                                 getToken();
1161                                 parse_into(p->cell(1), FLAG_ITEM);
1162                                 //lyxerr << "read label: " << p->cell(1) << "\n";
1163                         }
1164
1165                         array.push_back(MathAtom(p));
1166                         //lyxerr << "read array: " << array << "\n";
1167                 }
1168 #endif
1169
1170 #if 0
1171                 else if (t.cs() == "mbox" || t.cs() == "text") {
1172                         //array.push_back(createMathInset(t.cs()));
1173                         array.push_back(MathAtom(new MathBoxInset(t.cs())));
1174                         // slurp in the argument of mbox
1175         
1176                         MathBoxInset * p = array.back()->asBoxInset();
1177                         //lyx::assert(p);
1178                 }
1179 #endif
1180
1181         
1182                 else if (t.cs().size()) {
1183                         latexkeys const * l = in_word_set(t.cs());
1184                         if (l) {
1185                                 if (l->token == LM_TK_FONT) {
1186                                         //lyxerr << "starting font\n";
1187                                         //CatCode catSpaceSave = theCatcode[' '];
1188                                         //if (l->id == LM_TC_TEXTRM) {
1189                                         //      // temporarily change catcode   
1190                                         //      theCatcode[' '] = catLetter;    
1191                                         //}
1192
1193                                         MathArray ar;
1194                                         parse_into(ar, FLAG_ITEM, static_cast<MathTextCodes>(l->id));
1195                                         array.push_back(ar);
1196
1197                                         // undo catcode changes
1198                                         ////theCatcode[' '] = catSpaceSave;
1199                                         //lyxerr << "ending font\n";
1200                                 }
1201
1202                                 else if (l->token == LM_TK_OLDFONT) {
1203                                         code = static_cast<MathTextCodes>(l->id);
1204                                 }
1205
1206                                 else if (l->token == LM_TK_BOX) {
1207                                         MathAtom p = createMathInset(t.cs());
1208                                         parse_into(p->cell(0), FLAG_ITEM | FLAG_BOX, LM_TC_BOX);
1209                                         array.push_back(p);
1210                                 }
1211
1212                                 else if (l->token == LM_TK_STY) {
1213                                         MathAtom p = createMathInset(t.cs());
1214                                         parse_into(p->cell(0), flags, code);
1215                                         array.push_back(p);
1216                                         return;
1217                                 }
1218
1219                                 else {
1220                                         MathAtom p = createMathInset(t.cs());
1221                                         for (MathInset::idx_type i = 0; i < p->nargs(); ++i) 
1222                                                 parse_into(p->cell(i), FLAG_ITEM);
1223                                         array.push_back(p);
1224                                 }
1225                         }
1226
1227                         else {
1228                                 MathAtom p = createMathInset(t.cs());
1229                                 for (MathInset::idx_type i = 0; i < p->nargs(); ++i)
1230                                         parse_into(p->cell(i), FLAG_ITEM);
1231                                 array.push_back(p);
1232                         }
1233                 }
1234
1235
1236                 if (flags & FLAG_LEAVE) {
1237                         flags &= ~FLAG_LEAVE;
1238                         break;
1239                 }
1240         }
1241
1242         if (panic) {
1243                 lyxerr << " Math Panic, expect problems!\n";
1244                 //   Search for the end command. 
1245                 Token t;
1246                 do {
1247                         t = getToken();
1248                 } while (good() && t.cs() != "end");
1249         }
1250 }
1251
1252
1253
1254 } // anonymous namespace
1255
1256
1257 void mathed_parse_cell(MathArray & ar, string const & str)
1258 {
1259         istringstream is(str.c_str());
1260         mathed_parse_cell(ar, is);
1261 }
1262
1263
1264 void mathed_parse_cell(MathArray & ar, istream & is)
1265 {
1266         Parser(is).parse_into(ar, 0);
1267 }
1268
1269
1270
1271 bool mathed_parse_macro(string & name, string const & str)
1272 {
1273         istringstream is(str.c_str());
1274         Parser parser(is);
1275         return parser.parse_macro(name);
1276 }
1277
1278 bool mathed_parse_macro(string & name, istream & is)
1279 {
1280         Parser parser(is);
1281         return parser.parse_macro(name);
1282 }
1283
1284 bool mathed_parse_macro(string & name, LyXLex & lex)
1285 {
1286         Parser parser(lex);
1287         return parser.parse_macro(name);
1288 }
1289
1290
1291
1292 bool mathed_parse_normal(MathAtom & t, string const & str)
1293 {
1294         istringstream is(str.c_str());
1295         Parser parser(is);
1296         return parser.parse_normal(t);
1297 }
1298
1299 bool mathed_parse_normal(MathAtom & t, istream & is)
1300 {
1301         Parser parser(is);
1302         return parser.parse_normal(t);
1303 }
1304
1305 bool mathed_parse_normal(MathAtom & t, LyXLex & lex)
1306 {
1307         Parser parser(lex);
1308         return parser.parse_normal(t);
1309 }