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