]> git.lyx.org Git - features.git/blob - src/mathed/MathFactory.cpp
support for formal math script
[features.git] / src / mathed / MathFactory.cpp
1 /**
2  * \file MathFactory.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "MathFactory.h"
14
15 #include "InsetMathAMSArray.h"
16 #include "InsetMathArray.h"
17 #include "InsetMathBoldSymbol.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathCases.h"
20 #include "InsetMathColor.h"
21 #include "InsetMathDecoration.h"
22 #include "InsetMathDots.h"
23 #include "InsetMathEnsureMath.h"
24 #include "InsetMathFont.h"
25 #include "InsetMathFontOld.h"
26 #include "InsetMathFrac.h"
27 #include "InsetMathKern.h"
28 #include "InsetMathLefteqn.h"
29 #include "InsetMathOverset.h"
30 #include "InsetMathPhantom.h"
31 #include "InsetMathRef.h"
32 #include "InsetMathRoot.h"
33 #include "InsetMathSize.h"
34 #include "InsetMathSpace.h"
35 #include "InsetMathSpecialChar.h"
36 #include "InsetMathSplit.h"
37 #include "InsetMathSqrt.h"
38 #include "InsetMathStackrel.h"
39 #include "InsetMathSubstack.h"
40 #include "InsetMathSymbol.h"
41 #include "InsetMathTabular.h"
42 #include "InsetMathUnderset.h"
43 #include "InsetMathUnknown.h"
44 #include "InsetMathHull.h"
45 #include "InsetMathXArrow.h"
46 #include "InsetMathXYMatrix.h"
47 #include "MacroTable.h"
48 #include "MathMacro.h"
49 #include "MathMacroArgument.h"
50 #include "MathParser.h"
51 #include "MathStream.h"
52 #include "MathSupport.h"
53
54 #include "insets/InsetCommand.h"
55 #include "insets/InsetSpace.h"
56
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/FileName.h"
60 #include "support/filetools.h" // LibFileSearch
61 #include "support/lstrings.h"
62
63 #include "frontends/FontLoader.h"
64
65 #include "Buffer.h"
66 #include "BufferParams.h"
67 #include "Encoding.h"
68 #include "LyX.h" // use_gui
69 #include "OutputParams.h"
70
71 using namespace std;
72 using namespace lyx::support;
73
74 namespace lyx {
75
76 bool has_math_fonts;
77
78
79 namespace {
80
81 MathWordList theMathWordList;
82
83
84 bool isMathFontAvailable(docstring & name)
85 {
86         if (!use_gui)
87                 return false;
88
89         FontInfo f;
90         augmentFont(f, name);
91
92         // Do we have the font proper?
93         if (theFontLoader().available(f))
94                 return true;
95
96         // can we fake it?
97         if (name == "eufrak") {
98                 name = from_ascii("lyxfakefrak");
99                 return true;
100         }
101
102         LYXERR(Debug::MATHED,
103                 "font " << to_utf8(name) << " not available and I can't fake it");
104         return false;
105 }
106
107
108 void initSymbols()
109 {
110         FileName const filename = libFileSearch(string(), "symbols");
111         LYXERR(Debug::MATHED, "read symbols from " << filename);
112         if (filename.empty()) {
113                 lyxerr << "Could not find symbols file" << endl;
114                 return;
115         }
116
117         ifstream fs(filename.toFilesystemEncoding().c_str());
118         string line;
119         bool skip = false;
120         while (getline(fs, line)) {
121                 int charid     = 0;
122                 int fallbackid = 0;
123                 if (line.empty() || line[0] == '#')
124                         continue;
125
126                 // special case of iffont/else/endif
127                 if (line.size() >= 7 && line.substr(0, 6) == "iffont") {
128                         istringstream is(line);
129                         string tmp;
130                         is >> tmp;
131                         is >> tmp;
132                         docstring t = from_utf8(tmp);
133                         skip = !isMathFontAvailable(t);
134                         continue;
135                 } else if (line.size() >= 4 && line.substr(0, 4) == "else") {
136                         skip = !skip;
137                         continue;
138                 } else if (line.size() >= 5 && line.substr(0, 5) == "endif") {
139                         skip = false;
140                         continue;
141                 } else if (skip)
142                         continue;
143
144                 // special case of pre-defined macros
145                 if (line.size() > 8 && line.substr(0, 5) == "\\def\\") {
146                         //lyxerr << "macro definition: '" << line << '\'' << endl;
147                         istringstream is(line);
148                         string macro;
149                         string requires;
150                         is >> macro >> requires;
151                         MacroTable::globalMacros().insert(0, from_utf8(macro), requires);
152                         continue;
153                 }
154
155                 idocstringstream is(from_utf8(line));
156                 latexkeys tmp;
157                 is >> tmp.name >> tmp.inset;
158                 if (isFontName(tmp.inset))
159                         is >> charid >> fallbackid >> tmp.extra >> tmp.xmlname;
160                 else
161                         is >> tmp.extra;
162                 // requires is optional
163                 if (is)
164                         is >> tmp.requires;
165                 else {
166                         LYXERR(Debug::MATHED, "skipping line '" << line << "'\n"
167                                 << to_utf8(tmp.name) << ' ' << to_utf8(tmp.inset) << ' '
168                                 << to_utf8(tmp.extra));
169                         continue;
170                 }
171
172                 if (isFontName(tmp.inset)) {
173                         // tmp.inset _is_ the fontname here.
174                         // create fallbacks if necessary
175
176                         // store requirements as long as we can
177                         if (tmp.requires.empty()) {
178                                 if (tmp.inset == "msa" || tmp.inset == "msb")
179                                         tmp.requires = from_ascii("amssymb");
180                                 else if (tmp.inset == "wasy")
181                                         tmp.requires = from_ascii("wasysym");
182                                 else if (tmp.inset == "mathscr")
183                                         tmp.requires = from_ascii("mathrsfs");
184                         }
185
186                         // symbol font is not available sometimes
187                         docstring symbol_font = from_ascii("lyxsymbol");
188
189                         if (tmp.extra == "func" || tmp.extra == "funclim" || tmp.extra == "special") {
190                                 LYXERR(Debug::MATHED, "symbol abuse for " << to_utf8(tmp.name));
191                                 tmp.draw = tmp.name;
192                         } else if (isMathFontAvailable(tmp.inset)) {
193                                 LYXERR(Debug::MATHED, "symbol available for " << to_utf8(tmp.name));
194                                 tmp.draw.push_back(char_type(charid));
195                         } else if (fallbackid && isMathFontAvailable(symbol_font)) {
196                                 if (tmp.inset == "cmex")
197                                         tmp.inset = from_ascii("lyxsymbol");
198                                 else
199                                         tmp.inset = from_ascii("lyxboldsymbol");
200                                 LYXERR(Debug::MATHED, "symbol fallback for " << to_utf8(tmp.name));
201                                 tmp.draw.push_back(char_type(fallbackid));
202                         } else {
203                                 LYXERR(Debug::MATHED, "faking " << to_utf8(tmp.name));
204                                 tmp.draw = tmp.name;
205                                 tmp.inset = from_ascii("lyxtex");
206                         }
207                 } else {
208                         // it's a proper inset
209                         LYXERR(Debug::MATHED, "inset " << to_utf8(tmp.inset)
210                                               << " used for " << to_utf8(tmp.name));
211                 }
212
213                 if (theMathWordList.find(tmp.name) != theMathWordList.end())
214                         LYXERR(Debug::MATHED, "readSymbols: inset " << to_utf8(tmp.name)
215                                 << " already exists.");
216                 else
217                         theMathWordList[tmp.name] = tmp;
218
219                 LYXERR(Debug::MATHED, "read symbol '" << to_utf8(tmp.name)
220                         << "  inset: " << to_utf8(tmp.inset)
221                         << "  draw: " << int(tmp.draw.empty() ? 0 : tmp.draw[0])
222                         << "  extra: " << to_utf8(tmp.extra)
223                         << "  requires: " << to_utf8(tmp.requires) << '\'');
224         }
225         docstring tmp = from_ascii("cmm");
226         docstring tmp2 = from_ascii("cmsy");
227         has_math_fonts = isMathFontAvailable(tmp) && isMathFontAvailable(tmp2);
228 }
229
230
231 bool isSpecialChar(docstring const & name)
232 {
233         if (name.size() != 1)
234                 return  name == "textasciicircum" || name == "mathcircumflex" ||
235                         name == "textasciitilde"  || name == "textbackslash";
236
237         char_type const c = name.at(0);
238         return  c == '{' || c == '}' || c == '&' || c == '$' ||
239                 c == '#' || c == '%' || c == '_' || c == ' ';
240 }
241
242
243 } // namespace anon
244
245 MathWordList const & mathedWordList()
246 {
247         return theMathWordList;
248 }
249
250
251 void initMath()
252 {
253         static bool initialized = false;
254         if (!initialized) {
255                 initialized = true;
256                 initParser();
257                 initSymbols();
258         }
259 }
260
261
262 bool ensureMath(WriteStream & os, bool needs_math_mode, bool macro)
263 {
264         bool brace = os.pendingBrace();
265         os.pendingBrace(false);
266         if (!os.latex())
267                 return brace;
268         if (os.textMode() && needs_math_mode) {
269                 os << "\\ensuremath{";
270                 os.textMode(false);
271                 brace = true;
272         } else if (macro && brace && !needs_math_mode) {
273                 // This is a user defined macro, but not a MathMacro, so we
274                 // cannot be sure what mode is needed. As it was entered in
275                 // a text box, we restore the text mode.
276                 os << '}';
277                 os.textMode(true);
278                 brace = false;
279         }
280         return brace;
281 }
282
283
284 int ensureMode(WriteStream & os, InsetMath::mode_type mode,
285                 bool locked, bool ascii)
286 {
287         bool textmode = mode == InsetMath::TEXT_MODE;
288         if (os.latex() && textmode && os.pendingBrace()) {
289                 os.os() << '}';
290                 os.pendingBrace(false);
291                 os.pendingSpace(false);
292                 os.textMode(true);
293         }
294         int oldmodes = os.textMode() ? 0x01 : 0;
295         os.textMode(textmode);
296         oldmodes |= os.lockedMode() ? 0x02 : 0;
297         os.lockedMode(locked);
298         oldmodes |= os.asciiOnly() ? 0x04 : 0;
299         os.asciiOnly(ascii);
300         return oldmodes;
301 }
302
303
304 latexkeys const * in_word_set(docstring const & str)
305 {
306         MathWordList::iterator it = theMathWordList.find(str);
307         return it != theMathWordList.end() ? &(it->second) : 0;
308 }
309
310
311 MathAtom createInsetMath(char const * const s, Buffer * buf)
312 {
313         return createInsetMath(from_utf8(s), buf);
314 }
315
316
317 MathAtom createInsetMath(docstring const & s, Buffer * buf)
318 {
319         //lyxerr << "creating inset with name: '" << to_utf8(s) << '\'' << endl;
320         if ((s == "ce" || s == "cf") && buf
321             && buf->params().use_mhchem == BufferParams::package_off)
322                 return MathAtom(new MathMacro(buf, s));
323
324         latexkeys const * l = in_word_set(s);
325         if (l) {
326                 docstring const & inset = l->inset;
327                 //lyxerr << " found inset: '" << inset << '\'' << endl;
328                 if (inset == "ref")
329                         return MathAtom(new InsetMathRef(buf, l->name));
330                 if (inset == "overset")
331                         return MathAtom(new InsetMathOverset(buf));
332                 if (inset == "underset")
333                         return MathAtom(new InsetMathUnderset(buf));
334                 if (inset == "decoration")
335                         return MathAtom(new InsetMathDecoration(buf, l));
336                 if (inset == "space")
337                         return MathAtom(new InsetMathSpace(to_ascii(l->name), ""));
338                 if (inset == "dots")
339                         return MathAtom(new InsetMathDots(l));
340                 if (inset == "mbox")
341                         // return MathAtom(new InsetMathMBox);
342                         // InsetMathMBox is proposed to replace InsetMathBox,
343                         // but is not ready yet (it needs a BufferView for
344                         // construction)
345                         return MathAtom(new InsetMathBox(buf, l->name));
346 //              if (inset == "fbox")
347 //                      return MathAtom(new InsetMathFBox(l));
348                 if (inset == "style")
349                         return MathAtom(new InsetMathSize(buf, l));
350                 if (inset == "font")
351                         return MathAtom(new InsetMathFont(buf, l));
352                 if (inset == "oldfont")
353                         return MathAtom(new InsetMathFontOld(buf, l));
354                 if (inset == "matrix")
355                         return MathAtom(new InsetMathAMSArray(buf, s));
356                 if (inset == "split")
357                         return MathAtom(new InsetMathSplit(buf, s));
358                 if (inset == "big")
359                         // we can't create a InsetMathBig, since the argument
360                         // is missing.
361                         return MathAtom(new InsetMathUnknown(s));
362                 return MathAtom(new InsetMathSymbol(l));
363         }
364
365         if (s.size() == 2 && s[0] == '#' && s[1] >= '1' && s[1] <= '9')
366                 return MathAtom(new MathMacroArgument(s[1] - '0'));
367         if (s.size() == 3 && s[0] == '\\' && s[1] == '#'
368                         && s[2] >= '1' && s[2] <= '9')
369                 return MathAtom(new MathMacroArgument(s[2] - '0'));
370         if (s == "boxed")
371                 return MathAtom(new InsetMathBoxed(buf));
372         if (s == "fbox")
373                 return MathAtom(new InsetMathFBox(buf));
374         if (s == "framebox")
375                 return MathAtom(new InsetMathMakebox(buf, true));
376         if (s == "makebox")
377                 return MathAtom(new InsetMathMakebox(buf, false));
378         if (s == "kern")
379                 return MathAtom(new InsetMathKern);
380         if (s.substr(0, 8) == "xymatrix") {
381                 char spacing_code = '\0';
382                 Length spacing;
383                 bool equal_spacing = false;
384                 size_t const len = s.length();
385                 size_t i = 8;
386                 if (i < len && s[i] == '@') {
387                         ++i;
388                         if (i < len && s[i] == '!') {
389                                 equal_spacing = true;
390                                 ++i;
391                                 if (i < len) {
392                                         switch (s[i]) {
393                                         case '0':
394                                         case 'R':
395                                         case 'C':
396                                                 spacing_code = static_cast<char>(s[i]);
397                                         }
398                                 }
399                         } else if (i < len) {
400                                 switch (s[i]) {
401                                 case 'R':
402                                 case 'C':
403                                 case 'M':
404                                 case 'W':
405                                 case 'H':
406                                 case 'L':
407                                         spacing_code = static_cast<char>(s[i]);
408                                         ++i;
409                                         break;
410                                 }
411                                 if (i < len && s[i] == '=') {
412                                         ++i;
413                                         spacing = Length(to_ascii(s.substr(i)));
414                                 }
415                         }
416                 }
417                 return MathAtom(new InsetMathXYMatrix(buf, spacing, spacing_code,
418                         equal_spacing));
419         }
420         if (s == "xrightarrow" || s == "xleftarrow")
421                 return MathAtom(new InsetMathXArrow(buf, s));
422         if (s == "split" || s == "alignedat")
423                 return MathAtom(new InsetMathSplit(buf, s));
424         if (s == "cases")
425                 return MathAtom(new InsetMathCases(buf));
426         if (s == "substack")
427                 return MathAtom(new InsetMathSubstack(buf));
428         if (s == "subarray" || s == "array")
429                 return MathAtom(new InsetMathArray(buf, s, 1, 1));
430         if (s == "sqrt")
431                 return MathAtom(new InsetMathSqrt(buf));
432         if (s == "root")
433                 return MathAtom(new InsetMathRoot(buf));
434         if (s == "tabular")
435                 return MathAtom(new InsetMathTabular(buf, s, 1, 1));
436         if (s == "stackrel")
437                 return MathAtom(new InsetMathStackrel(buf));
438         if (s == "binom")
439                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BINOM));
440         if (s == "dbinom")
441                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::DBINOM));
442         if (s == "tbinom")
443                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::TBINOM));
444         if (s == "choose")
445                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::CHOOSE));
446         if (s == "brace")
447                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACE));
448         if (s == "brack")
449                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACK));
450         if (s == "frac")
451                 return MathAtom(new InsetMathFrac(buf));
452         if (s == "cfrac")
453                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC));
454         if (s == "dfrac")
455                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::DFRAC));
456         if (s == "tfrac")
457                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::TFRAC));
458         if (s == "over")
459                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::OVER));
460         if (s == "nicefrac")
461                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::NICEFRAC));
462         if (s == "unitfrac")
463                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC));
464         // These string values are only for math toolbar use, no LaTeX names
465         if (s == "unitfracthree")
466                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3));
467         if (s == "unitone")
468                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1));
469         if (s == "unittwo")
470                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT));
471         if (s == "cfracleft")
472                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT));
473         if (s == "cfracright")
474                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT));
475         //if (s == "infer")
476         //      return MathAtom(new MathInferInset);
477         if (s == "atop")
478                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::ATOP));
479         if (s == "lefteqn")
480                 return MathAtom(new InsetMathLefteqn(buf));
481         if (s == "boldsymbol")
482                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::AMS_BOLD));
483         if (s == "bm")
484                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_BOLD));
485         if (s == "heavysymbol" || s == "hm")
486                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_HEAVY));
487         if (s == "color" || s == "normalcolor")
488                 return MathAtom(new InsetMathColor(buf, true));
489         if (s == "textcolor")
490                 return MathAtom(new InsetMathColor(buf, false));
491         if (s == "hphantom")
492                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::hphantom));
493         if (s == "phantom")
494                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::phantom));
495         if (s == "vphantom")
496                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::vphantom));
497         if (s == "ensuremath")
498                 return MathAtom(new InsetMathEnsureMath(buf));
499         if (isSpecialChar(s))
500                 return MathAtom(new InsetMathSpecialChar(s));
501
502         if (s == "regexp")
503                 return MathAtom(new InsetMathHull(buf, hullRegexp));
504
505         return MathAtom(new MathMacro(buf, s));
506 }
507
508
509 bool createInsetMath_fromDialogStr(docstring const & str, MathData & ar)
510 {
511         // An example str:
512         // "ref LatexCommand ref\nreference \"sec:Title\"\n\\end_inset\n\n";
513         docstring name;
514         docstring body = split(str, name, ' ');
515
516         if (name == "ref") {
517                 InsetCommandParams icp(REF_CODE);
518                 // FIXME UNICODE
519                 InsetCommand::string2params("ref", to_utf8(str), icp);
520                 Encoding const * const utf8 = encodings.fromLyXName("utf8");
521                 OutputParams op(utf8);
522                 mathed_parse_cell(ar, icp.getCommand(op));
523         } else if (name == "mathspace") {
524                 InsetSpaceParams isp(true);
525                 InsetSpace::string2params(to_utf8(str), isp);
526                 InsetSpace is(isp);
527                 odocstringstream os;
528                 Encoding const * const ascii = encodings.fromLyXName("ascii");
529                 OutputParams op(ascii);
530                 is.latex(os, op);
531                 mathed_parse_cell(ar, os.str());
532                 if (ar.size() == 2) {
533                         // remove "{}"
534                         if (ar[1].nucleus()->asBraceInset())
535                                 ar.pop_back();
536                 }
537         } else
538                 return false;
539
540         if (ar.size() != 1)
541                 return false;
542
543         return ar[0].nucleus();
544 }
545
546
547 bool isAsciiOrMathAlpha(char_type c)
548 {
549         return c < 0x80 || Encodings::isMathAlpha(c);
550 }
551
552
553 } // namespace lyx