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