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.
8 * Dependencies: Xlib, XForms
10 * Copyright: 1996, Alejandro Aguilar Sierra
14 * You are free to use and modify this code under the terms of
15 * the GNU General Public Licence version 2 or later.
23 #pragma implementation "math_parser.h"
26 #include "math_parser.h"
27 #include "math_iter.h"
28 #include "math_inset.h"
29 #include "math_macro.h"
30 #include "math_root.h"
36 FLAG_BRACE = 1, // A { needed
37 FLAG_BRACE_ARG = 2, // Next { is argument
38 FLAG_BRACE_OPT = 4, // Optional {
39 FLAG_BRACE_LAST = 8, // Last } ends the parsing process
40 FLAG_BRACK_ARG = 16, // Optional [
41 FLAG_RIGHT = 32, // Next right ends the parsing process
42 FLAG_END = 64, // Next end ends the parsing process
43 FLAG_BRACE_FONT = 128, // Next } closes a font
44 FLAG_BRACK_END = 256 // Next ] ends the parsing process
50 static short mathed_env = LM_EN_INTEXT;
52 char * mathed_label = 0;
54 char const * latex_mathenv[] = {
64 char const * latex_mathspace[] = {
65 "!", ",", ":", ";", "quad", "qquad"
68 char const * latex_special_chars = "#$%&_{}";
70 // These are lexical codes, not semantic
76 LexBOP, // Binary operators or relations
88 static lexcode_enum lexcode[256];
89 static char yytext[256];
91 static istream * yyis;
92 static bool yy_mtextmode= false;
95 char * strnew(char const * s)
97 char * s1 = new char[strlen(s) + 1]; // this leaks when not delete[]'ed
104 void mathPrintError(char const * msg)
106 lyxerr << "Line ~" << yylineno << ": Math parse error: "
114 for (int i = 0; i <= 255; ++i) {
115 if (isalpha(i)) lexcode[i] = LexAlpha;
116 else if (isdigit(i)) lexcode[i] = LexDigit;
117 else if (isspace(i)) lexcode[i] = LexSpace;
118 else lexcode[i] = LexNone;
121 lexcode['\t'] = lexcode['\f'] = lexcode[' '] = LexSpace;
122 lexcode['\n'] = LexNewLine;
123 lexcode['%'] = LexComment;
124 lexcode['#'] = LexArgument;
125 lexcode['+'] = lexcode['-'] = lexcode['*'] = lexcode['/'] =
126 lexcode['<'] = lexcode['>'] = lexcode['='] = LexBOP;
128 lexcode['!'] = lexcode[','] = lexcode[':'] = lexcode[';'] = LexMathSpace;
129 lexcode['('] = lexcode[')'] = lexcode['|'] = lexcode['.'] = lexcode['?'] = LexOther;
130 lexcode['\'']= LexAlpha;
132 lexcode['['] = lexcode[']'] = lexcode['^'] = lexcode['_'] =
133 lexcode['&'] = LexSelf;
135 lexcode['\\'] = LexESC;
136 lexcode['{'] = LexOpen;
137 lexcode['}'] = LexClose;
142 char LexGetArg(char lf, bool accept_spaces= false)
145 char * p = &yytext[0];
149 while (yyis->good()) {
153 if (!lf) lf = c; else
155 lyxerr << "Math parse error: unexpected '"
160 rg = (lf == '{') ? '}': ((lf == '[') ? ']': ((lf == '(') ? ')': 0));
162 lyxerr << "Math parse error: unknown bracket '"
163 << lf << "'" << endl;
171 if ((c > ' ' || (c == ' ' && accept_spaces)) && bcnt>0) *(p++) = c;
172 } while (bcnt > 0 && yyis->good());
181 static int init_done = 0;
185 if (!init_done) LexInitCodes();
187 while (yyis->good()) {
191 if (yy_mtextmode && c == ' ') {
196 if (lexcode[c] == LexNewLine) {
201 if (lexcode[c] == LexComment)
202 do { yyis->get(cc); c = cc; } while (c != '\n' % yyis->good()); // eat comments
204 if (lexcode[c] == LexDigit || lexcode[c] == LexOther || lexcode[c] == LexMathSpace) { yylval.i = c; return LM_TK_STR; }
205 if (lexcode[c] == LexAlpha) { yylval.i= c; return LM_TK_ALPHA; }
206 if (lexcode[c] == LexBOP) { yylval.i= c; return LM_TK_BOP; }
207 if (lexcode[c] == LexSelf) { return c; }
208 if (lexcode[c] == LexArgument) {
212 return LM_TK_ARGUMENT;
214 if (lexcode[c] == LexOpen) { return LM_TK_OPEN; }
215 if (lexcode[c] == LexClose) { return LM_TK_CLOSE; }
217 if (lexcode[c] == LexESC) {
220 if (c == '\\') { return LM_TK_NEWLINE; }
221 if (c == '(') { yylval.i = LM_EN_INTEXT; return LM_TK_BEGIN; }
222 if (c == ')') { yylval.i = LM_EN_INTEXT; return LM_TK_END; }
223 if (c == '[') { yylval.i = LM_EN_DISPLAY; return LM_TK_BEGIN; }
224 if (c == ']') { yylval.i = LM_EN_DISPLAY; return LM_TK_END; }
225 if (strchr(latex_special_chars, c)) {
227 return LM_TK_SPECIAL;
229 if (lexcode[c] == LexMathSpace) {
231 for (i = 0; i < 4 && static_cast<int>(c) != latex_mathspace[i][0]; ++i);
232 yylval.i = (i < 4) ? i: 0;
235 if (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
236 char * p = &yytext[0];
237 while (lexcode[c] == LexAlpha || lexcode[c] == LexDigit) {
244 if (yyis->good()) yyis->putback(c);
245 latexkeys * l = in_word_set (yytext, strlen(yytext));
247 if (l->token == LM_TK_BEGIN || l->token == LM_TK_END) {
250 // for (i = 0; i < 5 && strncmp(yytext, latex_mathenv[i],
251 // strlen(latex_mathenv[i])); ++i);
253 for (i = 0; i < 6 && strcmp(yytext, latex_mathenv[i]); ++i);
256 if (l->token == LM_TK_SPACE)
272 int parse_align(char * hor, char *)
275 for (char * c = hor; c && *c > ' '; ++c) ++nc;
280 // Accent hacks only for 0.12. Stolen from Cursor.
284 void setAccent(int ac)
286 if (ac > 0 && accent < 8) {
287 nestaccent[accent++] = ac;
289 accent = 0; // consumed!
293 MathedInset * doAccent(byte c, MathedTextCodes t)
295 MathedInset * ac = 0;
297 for (int i = accent - 1; i >= 0; --i) {
299 ac = new MathAccentInset(c, t, nestaccent[i]);
301 ac = new MathAccentInset(ac, nestaccent[i]);
303 accent = 0; // consumed!
309 MathedInset * doAccent(MathedInset * p)
311 MathedInset * ac = 0;
313 for (int i = accent - 1; i >= 0; --i) {
315 ac = new MathAccentInset(p, nestaccent[i]);
317 ac = new MathAccentInset(ac, nestaccent[i]);
319 accent = 0; // consumed!
325 LyxArrayBase * mathed_parse(unsigned flags, LyxArrayBase * array,
328 int t = yylex(), tprev = 0;
330 static int plevel = -1;
331 static int size = LM_ST_TEXT;
332 MathedTextCodes varcode = LM_TC_VAR;
333 MathedInset * binset = 0;
334 static MathMacroTemplate * macro= 0;
339 MathParInset * mt = (mtx) ? *mtx : 0;//(MathParInset*)0;
340 MathedRowSt * crow = (mt) ? mt->getRowSt() : 0;
343 if (!array) array = new LyxArrayBase;
344 MathedIter data(array);
346 if ((flags & FLAG_BRACE) && t != LM_TK_OPEN) {
347 if ((flags & FLAG_BRACK_ARG) && t == '[') {
350 mathPrintError("Expected {. Maybe you forgot to enclose an argument in {}");
355 MathedInsetTypes fractype = LM_OT_FRAC;
360 data.Insert(doAccent(yylval.i, varcode));
362 data.Insert (yylval.i, varcode); //LM_TC_VAR);
368 data.Insert(macro->getMacroPar(yylval.i-1), LM_TC_INSET);
372 case LM_TK_NEWCOMMAND:
377 // This name lives until quitting, for that reason
378 // I didn't care on deleting explicitly. Later I will.
379 char const * name = strnew(&yytext[1]);
380 // ugly trick to be removed soon (lyx3)
381 char c; yyis->get(c);
387 macro = new MathMacroTemplate(name, na);
388 flags = FLAG_BRACE|FLAG_BRACE_LAST;
390 macro->SetData(array);
395 data.Insert (yylval.i, LM_TC_SPECIAL);
401 data.Insert(doAccent(yylval.i, LM_TC_CONST));
403 data.Insert (yylval.i, LM_TC_CONST);
409 if (accent && tprev == LM_TK_ACCENT) {
410 acc_braces[acc_brace++] = brace;
413 if (flags & FLAG_BRACE_OPT) {
414 flags &= ~FLAG_BRACE_OPT;
418 if (flags & FLAG_BRACE)
419 flags &= ~FLAG_BRACE;
421 data.Insert ('{', LM_TC_TEX);
429 mathPrintError("Unmatching braces");
433 if (acc_brace && brace == acc_braces[acc_brace-1]-1) {
437 if (flags & FLAG_BRACE_FONT) {
439 yy_mtextmode = false;
440 flags &= ~FLAG_BRACE_FONT;
443 if (brace == 0 && (flags & FLAG_BRACE_LAST)) {
447 data.Insert ('}', LM_TC_TEX);
454 if (flags & FLAG_BRACK_ARG) {
455 flags &= ~FLAG_BRACK_ARG;
456 char rg = LexGetArg('[');
458 mathPrintError("Expected ']'");
462 // if (arg) strcpy(arg, yytext);
469 if (flags & FLAG_BRACK_END) {
479 MathParInset * p = new MathParInset(size, "", LM_OT_SCRIPT);
480 LyxArrayBase * ar = mathed_parse(FLAG_BRACE_OPT|FLAG_BRACE_LAST, 0);
482 // lyxerr << "UP[" << p->GetStyle() << "]" << endl;
483 data.Insert (p, LM_TC_UP);
488 MathParInset * p = new MathParInset(size, "", LM_OT_SCRIPT);
489 LyxArrayBase * ar = mathed_parse(FLAG_BRACE_OPT|FLAG_BRACE_LAST, 0);
491 data.Insert (p, LM_TC_DOWN);
498 binset->SetLimits(bool(yylval.l->id));
506 if ((flags & FLAG_END) && mt && data.getCol()<mt->GetColumns()-1) {
507 data.setNumCols(mt->GetColumns());
508 data.Insert('T', LM_TC_TAB);
510 mathPrintError("Unexpected tab");
511 // debug info. [made that conditional -JMarc]
512 if (lyxerr.debugging(Debug::MATHED))
513 lyxerr << data.getCol() << " " << mt->GetColumns() << endl;
518 if (mt && (flags & FLAG_END)) {
519 if (mt->Permit(LMPF_ALLOW_CR)) {
521 crow->setNext(new MathedRowSt(mt->GetColumns()+1)); // this leaks
522 crow = crow->getNext();
524 data.Insert('K', LM_TC_CR);
526 mathPrintError("Unexpected newline");
532 binset = new MathBigopInset(yylval.l->name, yylval.l->id);
538 if (yylval.l->id < 256) {
539 MathedTextCodes tc = MathIsBOPS(yylval.l->id) ? LM_TC_BOPS: LM_TC_SYMB;
541 data.Insert(doAccent(yylval.l->id, tc));
543 data.Insert (yylval.l->id, tc);
545 MathFuncInset * bg = new MathFuncInset(yylval.l->name);
547 data.Insert(doAccent(bg));
549 data.Insert(bg, true);
556 data.Insert(doAccent(yylval.i, LM_TC_BOP));
558 data.Insert (yylval.i, LM_TC_BOP);
564 mt->UserSetSize(yylval.l->id);
571 MathSpaceInset * sp = new MathSpaceInset(yylval.i);
578 MathDotsInset * p = new MathDotsInset(yylval.l->name, yylval.l->id);
583 fractype = LM_OT_STACKREL;
586 MathFracInset * fc = new MathFracInset(fractype);
587 LyxArrayBase * num = mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST);
588 LyxArrayBase * den = mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST);
589 fc->SetData(num, den);
590 data.Insert(fc, LM_TC_ACTIVE_INSET);
597 char c; yyis->get(c);
600 rt = new MathRootInset(size);
601 rt->setArgumentIdx(0);
602 rt->SetData(mathed_parse(FLAG_BRACK_END, 0, &rt));
603 rt->setArgumentIdx(1);
606 rt = new MathSqrtInset(size);
608 rt->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST, 0, &rt));
609 data.Insert(rt, LM_TC_ACTIVE_INSET);
617 if (lfd == LM_TK_SYM || lfd == LM_TK_STR || lfd == LM_TK_BOP|| lfd == LM_TK_SPECIAL)
618 lfd = (lfd == LM_TK_SYM) ? yylval.l->id: yylval.i;
619 // lyxerr << "L[" << lfd << " " << lfd << "]";
620 LyxArrayBase * a = mathed_parse(FLAG_RIGHT);
622 // lyxerr << "R[" << rgd << "]";
623 if (rgd == LM_TK_SYM || rgd == LM_TK_STR || rgd == LM_TK_BOP || rgd == LM_TK_SPECIAL)
624 rgd = (rgd == LM_TK_SYM) ? yylval.l->id: yylval.i;
625 MathDelimInset * dl = new MathDelimInset(lfd, rgd);
627 data.Insert(dl, LM_TC_ACTIVE_INSET);
628 // lyxerr << "RL[" << lfd << " " << rgd << "]";
633 if (flags & FLAG_RIGHT) {
637 mathPrintError("Unmatched right delimiter");
645 varcode = static_cast<MathedTextCodes>(yylval.l->id);
646 yy_mtextmode = bool(varcode == LM_TC_TEXTRM);
647 flags |= (FLAG_BRACE|FLAG_BRACE_FONT);
652 MathDecorationInset * sq = new MathDecorationInset(yylval.l->id,
654 sq->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
655 data.Insert(sq, LM_TC_ACTIVE_INSET);
659 case LM_TK_ACCENT: setAccent(yylval.l->id); break;
664 crow->setNumbered(false);
671 MathedInset * bg = new MathFuncInset(yylval.l->name);
680 data.Insert(new MathFuncInset(yylval.l->name, LM_OT_FUNCLIM));
687 MathMacroTable::mathMTable.getMacro(yylval.s);
690 data.Insert(doAccent(p), p->getTCode());
692 data.Insert(p, p->getTCode());
693 for (int i = 0; p->setArgumentIdx(i); ++i)
694 p->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
697 MathedInset * q = new MathFuncInset(yylval.s, LM_OT_UNDEF);
699 data.Insert(doAccent(q));
708 if (mathed_env != yylval.i && yylval.i!= LM_EN_ARRAY)
709 mathPrintError("Unmatched environment");
710 // debug info [made that conditional -JMarc]
711 if (lyxerr.debugging(Debug::MATHED))
712 lyxerr << "[" << yylval.i << "]" << endl;
714 if (mt) { // && (flags & FLAG_END)) {
722 if (yylval.i == LM_EN_ARRAY) {
723 char ar[120], ar2[8];
724 ar[0] = ar2[0] = '\0';
725 char rg = LexGetArg(0);
731 int nc = parse_align(ar, ar2);
732 MathParInset * mm = new MathMatrixInset(nc, 0);
733 mm->SetAlign(ar2[0], ar);
734 data.Insert(mm, LM_TC_ACTIVE_INSET);
735 mathed_parse(FLAG_END, mm->GetData(), &mm);
737 if (yylval.i >= LM_EN_INTEXT && yylval.i<= LM_EN_EQNARRAY) {
739 mathPrintError("Misplaced environment");
743 mathPrintError("0 paragraph.");
747 mathed_env = yylval.i;
748 if (mathed_env>= LM_EN_DISPLAY) {
749 size = LM_ST_DISPLAY;
750 if (mathed_env>LM_EN_EQUATION) {
751 mt = new MathMatrixInset(3, -1);
752 mt->SetAlign(' ', "rcl");
755 // data.Insert(' ', LM_TC_TAB);
756 // data.Insert(' ', LM_TC_TAB);
760 mt->SetType(mathed_env);
761 crow = mt->getRowSt();
765 lyxerr << "MATH BEGIN[" << mathed_env << "]" << endl;
768 // lyxerr << "MATHCRO[" << yytext << "]";
770 MathMacroTable::mathMTable.getMacro(yytext);
772 data.Insert(p, p->getTCode());
773 p->setArgumentIdx(0);
774 mathed_parse(FLAG_END, p->GetData(), reinterpret_cast<MathParInset**>(&p));
775 // for (int i = 0; p->setArgumentIdx(i); ++i)
776 // p->SetData(mathed_parse(FLAG_BRACE|FLAG_BRACE_LAST));
778 mathPrintError("Unrecognized environment");
786 MathMacroTable::mathMTable.getMacro(yylval.l->name);
790 data.Insert(doAccent(p));
792 data.Insert(p, static_cast<MathMacro*>(p)->getTCode());
799 char rg = LexGetArg('\0', true);
801 mathPrintError("Expected '{'");
803 lyxerr << "[" << yytext << "]" << endl;
808 // This is removed by crow's destructor. Bad design? yes, this
809 // will be changed after 0.12
810 crow->setLabel(strnew(yytext));
813 // where is this math_label free'ed?
814 // Supposedly in ~formula, another bad hack,
815 // give me some time please.
816 mathed_label = strnew(yytext);
819 lyxerr << "Label[" << mathed_label << "]" << endl;
824 mathPrintError("Unrecognized token");
826 lyxerr << "[" << t << " " << yytext << "]" << endl;
831 lyxerr << " Math Panic, expect problems!" << endl;
832 // Search for the end command.
833 do t = yylex (); while (t != LM_TK_END && t);
837 if ((flags & FLAG_BRACE_OPT)/* && t!= '^' && t!= '_'*/) {
838 flags &= ~FLAG_BRACE_OPT;
839 //data.Insert (LM_TC_CLOSE);
848 void mathed_parser_file(istream & is, int lineno)
852 if (!MathMacroTable::built)
853 MathMacroTable::mathMTable.builtinMacros();
857 int mathed_parser_lineno()