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