]> git.lyx.org Git - lyx.git/blob - src/mathed/MathFactory.cpp
6750fa414fe421424b6959e9bdbc2f40d756e280
[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 "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                         }
183
184                         // symbol font is not available sometimes
185                         docstring symbol_font = from_ascii("lyxsymbol");
186
187                         if (tmp.extra == "func" || tmp.extra == "funclim" || tmp.extra == "special") {
188                                 LYXERR(Debug::MATHED, "symbol abuse for " << to_utf8(tmp.name));
189                                 tmp.draw = tmp.name;
190                         } else if (isMathFontAvailable(tmp.inset)) {
191                                 LYXERR(Debug::MATHED, "symbol available for " << to_utf8(tmp.name));
192                                 tmp.draw.push_back(char_type(charid));
193                         } else if (fallbackid && isMathFontAvailable(symbol_font)) {
194                                 if (tmp.inset == "cmex")
195                                         tmp.inset = from_ascii("lyxsymbol");
196                                 else
197                                         tmp.inset = from_ascii("lyxboldsymbol");
198                                 LYXERR(Debug::MATHED, "symbol fallback for " << to_utf8(tmp.name));
199                                 tmp.draw.push_back(char_type(fallbackid));
200                         } else {
201                                 LYXERR(Debug::MATHED, "faking " << to_utf8(tmp.name));
202                                 tmp.draw = tmp.name;
203                                 tmp.inset = from_ascii("lyxtex");
204                         }
205                 } else {
206                         // it's a proper inset
207                         LYXERR(Debug::MATHED, "inset " << to_utf8(tmp.inset)
208                                               << " used for " << to_utf8(tmp.name));
209                 }
210
211                 if (theMathWordList.find(tmp.name) != theMathWordList.end())
212                         LYXERR(Debug::MATHED, "readSymbols: inset " << to_utf8(tmp.name)
213                                 << " already exists.");
214                 else
215                         theMathWordList[tmp.name] = tmp;
216
217                 LYXERR(Debug::MATHED, "read symbol '" << to_utf8(tmp.name)
218                         << "  inset: " << to_utf8(tmp.inset)
219                         << "  draw: " << int(tmp.draw.empty() ? 0 : tmp.draw[0])
220                         << "  extra: " << to_utf8(tmp.extra)
221                         << "  requires: " << to_utf8(tmp.requires) << '\'');
222         }
223         docstring tmp = from_ascii("cmm");
224         docstring tmp2 = from_ascii("cmsy");
225         has_math_fonts = isMathFontAvailable(tmp) && isMathFontAvailable(tmp2);
226 }
227
228
229 bool isSpecialChar(docstring const & name)
230 {
231         if (name.size() != 1)
232                 return  name == "textasciicircum" || name == "mathcircumflex" ||
233                         name == "textasciitilde"  || name == "textbackslash";
234
235         char_type const c = name.at(0);
236         return  c == '{' || c == '}' || c == '&' || c == '$' ||
237                 c == '#' || c == '%' || c == '_' || c == ' ';
238 }
239
240
241 } // namespace anon
242
243 MathWordList const & mathedWordList()
244 {
245         return theMathWordList;
246 }
247
248
249 void initMath()
250 {
251         static bool initialized = false;
252         if (!initialized) {
253                 initialized = true;
254                 initParser();
255                 initSymbols();
256         }
257 }
258
259
260 bool ensureMath(WriteStream & os, bool needs_math_mode, bool macro)
261 {
262         bool brace = os.pendingBrace();
263         os.pendingBrace(false);
264         if (!os.latex())
265                 return brace;
266         if (os.textMode() && needs_math_mode) {
267                 os << "\\ensuremath{";
268                 os.textMode(false);
269                 brace = true;
270         } else if (macro && brace && !needs_math_mode) {
271                 // This is a user defined macro, but not a MathMacro, so we
272                 // cannot be sure what mode is needed. As it was entered in
273                 // a text box, we restore the text mode.
274                 os << '}';
275                 os.textMode(true);
276                 brace = false;
277         }
278         return brace;
279 }
280
281
282 int ensureMode(WriteStream & os, InsetMath::mode_type mode,
283                 bool locked, bool ascii)
284 {
285         bool textmode = mode == InsetMath::TEXT_MODE;
286         if (os.latex() && textmode && os.pendingBrace()) {
287                 os.os() << '}';
288                 os.pendingBrace(false);
289                 os.pendingSpace(false);
290                 os.textMode(true);
291         }
292         int oldmodes = os.textMode() ? 0x01 : 0;
293         os.textMode(textmode);
294         oldmodes |= os.lockedMode() ? 0x02 : 0;
295         os.lockedMode(locked);
296         oldmodes |= os.asciiOnly() ? 0x04 : 0;
297         os.asciiOnly(ascii);
298         return oldmodes;
299 }
300
301
302 latexkeys const * in_word_set(docstring const & str)
303 {
304         MathWordList::iterator it = theMathWordList.find(str);
305         return it != theMathWordList.end() ? &(it->second) : 0;
306 }
307
308
309 MathAtom createInsetMath(char const * const s, Buffer * buf)
310 {
311         return createInsetMath(from_utf8(s), buf);
312 }
313
314
315 MathAtom createInsetMath(docstring const & s, Buffer * buf)
316 {
317         //lyxerr << "creating inset with name: '" << to_utf8(s) << '\'' << endl;
318         if ((s == "ce" || s == "cf") && buf
319             && buf->params().use_mhchem == BufferParams::package_off)
320                 return MathAtom(new MathMacro(buf, s));
321
322         latexkeys const * l = in_word_set(s);
323         if (l) {
324                 docstring const & inset = l->inset;
325                 //lyxerr << " found inset: '" << inset << '\'' << endl;
326                 if (inset == "ref")
327                         return MathAtom(new InsetMathRef(buf, l->name));
328                 if (inset == "overset")
329                         return MathAtom(new InsetMathOverset(buf));
330                 if (inset == "underset")
331                         return MathAtom(new InsetMathUnderset(buf));
332                 if (inset == "decoration")
333                         return MathAtom(new InsetMathDecoration(buf, l));
334                 if (inset == "space")
335                         return MathAtom(new InsetMathSpace(to_ascii(l->name), ""));
336                 if (inset == "dots")
337                         return MathAtom(new InsetMathDots(l));
338                 if (inset == "mbox")
339                         // return MathAtom(new InsetMathMBox);
340                         // InsetMathMBox is proposed to replace InsetMathBox,
341                         // but is not ready yet (it needs a BufferView for
342                         // construction)
343                         return MathAtom(new InsetMathBox(buf, l->name));
344 //              if (inset == "fbox")
345 //                      return MathAtom(new InsetMathFBox(l));
346                 if (inset == "style")
347                         return MathAtom(new InsetMathSize(buf, l));
348                 if (inset == "font")
349                         return MathAtom(new InsetMathFont(buf, l));
350                 if (inset == "oldfont")
351                         return MathAtom(new InsetMathFontOld(buf, l));
352                 if (inset == "matrix")
353                         return MathAtom(new InsetMathAMSArray(buf, s));
354                 if (inset == "split")
355                         return MathAtom(new InsetMathSplit(buf, s));
356                 if (inset == "big")
357                         // we can't create a InsetMathBig, since the argument
358                         // is missing.
359                         return MathAtom(new InsetMathUnknown(s));
360                 return MathAtom(new InsetMathSymbol(l));
361         }
362
363         if (s.size() == 2 && s[0] == '#' && s[1] >= '1' && s[1] <= '9')
364                 return MathAtom(new MathMacroArgument(s[1] - '0'));
365         if (s.size() == 3 && s[0] == '\\' && s[1] == '#'
366                         && s[2] >= '1' && s[2] <= '9')
367                 return MathAtom(new MathMacroArgument(s[2] - '0'));
368         if (s == "boxed")
369                 return MathAtom(new InsetMathBoxed(buf));
370         if (s == "fbox")
371                 return MathAtom(new InsetMathFBox(buf));
372         if (s == "framebox")
373                 return MathAtom(new InsetMathMakebox(buf, true));
374         if (s == "makebox")
375                 return MathAtom(new InsetMathMakebox(buf, false));
376         if (s == "kern")
377                 return MathAtom(new InsetMathKern);
378         if (s.substr(0, 8) == "xymatrix") {
379                 char spacing_code = '\0';
380                 Length spacing;
381                 bool equal_spacing = false;
382                 size_t const len = s.length();
383                 size_t i = 8;
384                 if (i < len && s[i] == '@') {
385                         ++i;
386                         if (i < len && s[i] == '!') {
387                                 equal_spacing = true;
388                                 ++i;
389                                 if (i < len) {
390                                         switch (s[i]) {
391                                         case '0':
392                                         case 'R':
393                                         case 'C':
394                                                 spacing_code = static_cast<char>(s[i]);
395                                         }
396                                 }
397                         } else if (i < len) {
398                                 switch (s[i]) {
399                                 case 'R':
400                                 case 'C':
401                                 case 'M':
402                                 case 'W':
403                                 case 'H':
404                                 case 'L':
405                                         spacing_code = static_cast<char>(s[i]);
406                                         ++i;
407                                         break;
408                                 }
409                                 if (i < len && s[i] == '=') {
410                                         ++i;
411                                         spacing = Length(to_ascii(s.substr(i)));
412                                 }
413                         }
414                 }
415                 return MathAtom(new InsetMathXYMatrix(buf, spacing, spacing_code,
416                         equal_spacing));
417         }
418         if (s == "xrightarrow" || s == "xleftarrow")
419                 return MathAtom(new InsetMathXArrow(buf, s));
420         if (s == "split" || s == "alignedat")
421                 return MathAtom(new InsetMathSplit(buf, s));
422         if (s == "cases")
423                 return MathAtom(new InsetMathCases(buf));
424         if (s == "substack")
425                 return MathAtom(new InsetMathSubstack(buf));
426         if (s == "subarray" || s == "array")
427                 return MathAtom(new InsetMathArray(buf, s, 1, 1));
428         if (s == "sqrt")
429                 return MathAtom(new InsetMathSqrt(buf));
430         if (s == "root")
431                 return MathAtom(new InsetMathRoot(buf));
432         if (s == "tabular")
433                 return MathAtom(new InsetMathTabular(buf, s, 1, 1));
434         if (s == "stackrel")
435                 return MathAtom(new InsetMathStackrel(buf));
436         if (s == "binom")
437                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BINOM));
438         if (s == "dbinom")
439                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::DBINOM));
440         if (s == "tbinom")
441                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::TBINOM));
442         if (s == "choose")
443                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::CHOOSE));
444         if (s == "brace")
445                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACE));
446         if (s == "brack")
447                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACK));
448         if (s == "frac")
449                 return MathAtom(new InsetMathFrac(buf));
450         if (s == "cfrac")
451                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC));
452         if (s == "dfrac")
453                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::DFRAC));
454         if (s == "tfrac")
455                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::TFRAC));
456         if (s == "over")
457                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::OVER));
458         if (s == "nicefrac")
459                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::NICEFRAC));
460         if (s == "unitfrac")
461                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC));
462         // These string values are only for math toolbar use, no LaTeX names
463         if (s == "unitfracthree")
464                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3));
465         if (s == "unitone")
466                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1));
467         if (s == "unittwo")
468                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT));
469         if (s == "cfracleft")
470                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT));
471         if (s == "cfracright")
472                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT));
473         //if (s == "infer")
474         //      return MathAtom(new MathInferInset);
475         if (s == "atop")
476                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::ATOP));
477         if (s == "lefteqn")
478                 return MathAtom(new InsetMathLefteqn(buf));
479         if (s == "boldsymbol")
480                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::AMS_BOLD));
481         if (s == "bm")
482                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_BOLD));
483         if (s == "heavysymbol" || s == "hm")
484                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_HEAVY));
485         if (s == "color" || s == "normalcolor")
486                 return MathAtom(new InsetMathColor(buf, true));
487         if (s == "textcolor")
488                 return MathAtom(new InsetMathColor(buf, false));
489         if (s == "hphantom")
490                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::hphantom));
491         if (s == "phantom")
492                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::phantom));
493         if (s == "vphantom")
494                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::vphantom));
495         if (s == "ensuremath")
496                 return MathAtom(new InsetMathEnsureMath(buf));
497         if (isSpecialChar(s))
498                 return MathAtom(new InsetMathSpecialChar(s));
499
500         if (s == "regexp")
501                 return MathAtom(new InsetMathHull(buf, hullRegexp));
502
503         return MathAtom(new MathMacro(buf, s));
504 }
505
506
507 bool createInsetMath_fromDialogStr(docstring const & str, MathData & ar)
508 {
509         // An example str:
510         // "ref LatexCommand ref\nreference \"sec:Title\"\n\\end_inset\n\n";
511         docstring name;
512         docstring body = split(str, name, ' ');
513
514         if (name == "ref") {
515                 InsetCommandParams icp(REF_CODE);
516                 // FIXME UNICODE
517                 InsetCommand::string2params("ref", to_utf8(str), icp);
518                 Encoding const * const utf8 = encodings.fromLyXName("utf8");
519                 OutputParams op(utf8);
520                 mathed_parse_cell(ar, icp.getCommand(op));
521         } else if (name == "mathspace") {
522                 InsetSpaceParams isp(true);
523                 InsetSpace::string2params(to_utf8(str), isp);
524                 InsetSpace is(isp);
525                 odocstringstream os;
526                 Encoding const * const ascii = encodings.fromLyXName("ascii");
527                 OutputParams op(ascii);
528                 is.latex(os, op);
529                 mathed_parse_cell(ar, os.str());
530                 if (ar.size() == 2) {
531                         // remove "{}"
532                         if (ar[1].nucleus()->asBraceInset())
533                                 ar.pop_back();
534                 }
535         } else
536                 return false;
537
538         if (ar.size() != 1)
539                 return false;
540
541         return ar[0].nucleus();
542 }
543
544
545 bool isAsciiOrMathAlpha(char_type c)
546 {
547         return c < 0x80 || Encodings::isMathAlpha(c);
548 }
549
550
551 } // namespace lyx